go:embedindex.html
1
2
3
4
.
├── main.go
└── abc/
    └── index.html
1
2
//go:embed abc
var abc embed.FS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func main() {
	// 以前的方式
	//fileServer := http.FileServer(http.Dir("./abc")) // New code
	//http.Handle("/", fileServer) // New code

	sub, _ := fs.Sub(abc, "abc")

	// 根目录 /index.html
	http.Handle("/", http.FileServer(http.FS(sub)))

	// 子目录 /abc/index.html
	http.Handle("/abc/", http.StripPrefix("/abc/", http.FileServer(http.FS(sub))))

	// 其它路由
	http.HandleFunc("/hello", helloHandler)

	fmt.Printf("Starting server at port 8081\n")
	if err := http.ListenAndServe(":8081", nil); err != nil {
		log.Fatal(err)
	}
}

你学废了吗?

本文网址: https://golangnote.com/topic/278.html 转摘请注明来源