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 phantomjs 动态代理实现

phantomjs 是个很优秀的软件,虽然现在被chrome headless 抢了风头,但在某些特定场合,使用phantomjs 还是很方便,这里是介绍使用Go 实现动态代理。...

Golang 泛型性能初识

编程时,我们通常需要编写“泛型”函数,其中确切的数据类型并不重要。例如,您可能想编写一个简单的函数来对数字进行求和。Go 直到最近才有这个概念,但最近才添加了它(从1.18版开始)。...

Golang Range 的性能提升Tip

Go 语言里使用 range 可以方便遍历数组(array)、切片(slice)、字典(map)和信道(chan)。这里主要关注他们的性能。...

Golang 把cookie 字符串解析为cookie 结构

在做爬虫时有时候会遇到需要带已登录的 cookie 请求,这个时候最简单的方法是在浏览器登录后,在开发者面板找到cookie 字符串,然后拷贝粘贴。这就面临一个问题需要把cookie 字符串解析成Go 语言 cookie 结构体。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms