GolangNote

Golang笔记

Golang embed 的 index.html 文件存放路径

Permalink

go:embed 可提供嵌入静态文件功能,首页文件 index.html 的放置及设定。

plaintext: 文件结构
1
2
3
4
.
├── main.go
└── abc/
    └── index.html

Go: 指定
1
2
//go:embed abc
var abc embed.FS

Go: 配置路由
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 转摘请注明来源

Related articles

Golang WebAssembly 了解一下

Go 1.11 起开始支持 WebAssembly ,也就是说以后可以使用任何语言作为“前端语言”来进行 Web 开发。...

Write a Comment to "Golang embed 的 index.html 文件存放路径"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 35ms