html文件如何放置web站点,如何使用Go Web服务器提供静态html文件?
小编典典
使用Golang net / http包,该任务非常容易。
您需要做的只是:
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("./static")))
http.ListenAndServe(":3000", nil)
}
假设静态文件位于static项目根目录中命名的文件夹中。
如果在folder中static,您将进行index.html文件调用http://localhost:3000/,这将导致呈现该索引文件,而不是列出所有可用文件。
此外,调用该文件夹中的任何其他文件(例如http://localhost:3000/clients.html)将显示该文件,该文件已由浏览器正确渲染(至少是Chrome,Firefox和Safari
:)。
更新:通过不同于“ /”的网址提供文件
如果您想为文件,从文件夹说./public下网址:localhost:3000/static你必须 使用附加功能 :func
StripPrefix(prefix string, h Handler) Handler是这样的:
package main
import (
"net/http"
)
func main() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
http.ListenAndServe(":3000", nil)
}
因此,您的所有文件./public都可以在localhost:3000/static
没有http.StripPrefix功能,如果您尝试访问file
localhost:3000/static/test.html,服务器将在其中查找./public/static/test.html
这是因为服务器将整个URI视为文件的相对路径。
幸运的是,使用内置函数可以轻松解决该问题。
2020-07-02