如何使用 go web 服务器提供 index.html(或其他静态 HTML 文件)?
我只想要一个基本的、静态的 HTML 文件(例如一篇文章),我可以从 Go Web 服务器提供它。 HTML 应该可以在 go 程序之外进行修改,就像使用 HTML 模板时一样。
这是我的网络服务器,它只托管硬编码文本(“Hello world!”)。
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello world!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":3000", nil)
}
最佳答案
使用 Golang net/http 包可以轻松完成这项任务。
您需要做的就是:
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("./static")))
http.ListenAndServe(":3000", nil)
}
假设静态文件位于项目根目录下名为static
的文件夹中。
如果它在文件夹 static
中,您将有 index.html
文件调用 http://localhost:3000/
这将导致呈现该索引文件,而不是列出所有可用的文件。
此外,调用该文件夹中的任何其他文件(例如 http://localhost:3000/clients.html
)将显示该文件,由浏览器正确呈现(至少 Chrome、Firefox和 Safari :))
更新:从不同于“/”的 url 提供文件
如果你想提供文件,比如从文件夹 ./public
下的 url: 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
函数,如果你尝试访问文件 localhost:3000/static/test.html
,服务器会在 中查找它./public/static/test.html
这是因为服务器将整个 URI 视为文件的相对路径。
幸运的是,使用内置函数很容易解决。
关于go - 如何使用 Go Web 服务器提供静态 html 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26559557/