gpt4 book ai didi

http - Go Golang 提供特定的 html 文件

转载 作者:IT老高 更新时间:2023-10-28 13:01:11 27 4
gpt4 key购买 nike

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

在静态目录中提供 html 文件。

在 Go 中有什么方法可以指定要服务的 html 文件吗?

Flask中的render_template之类的东西

我想做这样的事情:

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

最佳答案

也许使用 custom http.HandlerFunc会更容易:

除了你的情况,你的函数是 http.ServeFile一,只提供一个文件。

参见例如“Go Web Applications: Serving Static Files”:

Add the following below your home handler (see below):

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:]

实际上,不要那样做。
这在 Go 1.6 中是不可能的,因为 sztanpet comments , 与 commit 9b67a5d :

If the provided file or directory name is a relative path, it isinterpreted relative to the current directory and may ascend to parentdirectories.
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\\..

关于http - Go Golang 提供特定的 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25945538/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com