http.Handle("/", http.FileServer(http.Dir("static")))

服务于静态目录中的html文件.

我们有没有办法指定要提供的html个文件?

Flask中大约有render_template

我想做一些类似的事情:

http.Handle("/hello", http.FileServer(http.Dir("static/hello.html")))

推荐答案

也许使用custom http.HandlerFunc会更简单:

除了你的情况,你的func是http.ServeFile个,因为只提供一个文件.

例如,参见"Go Web Applications: Serving Static Files":

在您的家庭处理器下方添加以下内容(见下文):

http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
   // do NOT do this. (see below)
    http.ServeFile(w, r, r.URL.Path[1:])
})

This is using the net/http package’s ServeFile function to serve our content.
Effectively anything that makes a request starting with the /static/ path will be handled by this function.
One thing I found I had to do in order for the request to be handled correctly was trim the leading ‘/’ using:

r.URL.Path[1:]

Actually, do not do that.
This won't be possible in Go 1.6, as sztanpet comments, with commit 9b67a5d:

If the provided file or directory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories.
If the provided name is constructed from user input, it should be sanitized before calling ServeFile.
As a precaution, ServeFile will reject requests where r.URL.Path contains a ".." path element.

这将保护您免受以下"url"的攻击:

/../file
/..
/../
/../foo
/..\\foo
/file/a
/file/a..
/file/a/..
/file/a\\..

Go相关问答推荐

Go中的net.SplitHostPort(r.RemoteAddr)安全性

在GO中创建[]字符串类型的变量

如何配置vscode以在Go中显示不必要的(过度指定的)泛型?

正确使用pgtype的方法

可以';t从主机连接到ScyllaDB容器

无法使用exec从管道中读取.Go中的命令

如何将任何类型的数据值传递到 Golang 中的 GRPC Protobuf struct ?

Secrets Manager Update Secret - Secret String 额外的 JSON 编码

在 Go sync.Map 中,为什么这部分实现不一致或者我误解了什么?

使用 Grafana alert 在几分钟内重复alert

在嵌套模板中使用变量,它也被定义为 go 模板中的变量?

使用innerxml在 Go 中编码 XML 是否仅适用于某些类型?

如何编写一个以字符串或错误为参数的通用函数?

Golang Getrlimit 返回与 ulimit 不同的值

try 与 golang testify/suite 并行运行测试失败

Gorm 在保存/创建时序列化 struct

Golang prometheus 显示自定义指标

将 Golang Gin 与 AWS Lambda 和无服务器与代理路径一起使用

正确编码 JWT

在 Go 泛型中,如何对联合约束中的类型使用通用方法?