回答

收藏

你如何使用 go web 服务器提供静态 html 文件?

技术问答 技术问答 204 人阅读 | 0 人回复 | 2023-09-12

如何使用 go web 服务器提供 index.html(或其他一些静态 HTML 文件)?; _% R" {1 g; J) @
我只想要一个基本的静态 HTML 文件(如文章)我可以从 go web 服务器提供。HTML 应该在 go 程序外修改就像使用 HTML 模板是一样的。. Y- E8 L$ N6 C! ~  M8 h3 J8 C0 i' l
这是我的 Web 服务器只托管硬编码文本(Hello world!”)。2 T3 g" `3 X6 S
    package mainimport (  "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)}
    4 ]+ Q8 e! D  T: s! m' N; [
               " H# O; m( f+ A9 H# ?3 ~
    解决方案:                                                                8 O( ]8 U4 o$ N! g  B# U, f
                                                                使用 Golang net/http 包,这个任务很容易。
) f7 E5 O3 U) f0 N' D你需要做的是:- q3 X) M* {! Q
    package mainimport (       "net/http")func main()(){        http.Handle("/",http.FileServer(http.Dir("./static")))        http.ListenAndServe(":3000",nil)}
    . b4 Y7 ]1 g# b+ v3 u' Z' P8 ~
假设静态文件位于static在项目根目录中命名的文件夹中。
: p- ~# m" }7 Z0 Y. l若在文件夹中static,您将进行index.html文件调用http://localhost:这将导致索引文件的呈现,而不是所有可用的文件。
8 d3 V7 h- _% H: z$ N此外,在文件夹中调用任何其他文件(例如http://localhost:3000/clients.html)浏览器正确显示文件(至少 Chrome、Firefox 和 Safari
$ w# z9 A) ]! O2 r- }更新: 不同于/url 提供文件如果您想提供文件,请从./publicurl 下文件夹说:localhost:3000/static您必须使用附加功能:func StripPrefix(prefix string,h Handler) Handler像这样:
6 q8 t( ]" K" X, S3 U
    package mainimport (       "net/http")func main()(){        http.Handle("/static/",http.StripPrefix("/static/",http.FileServer(http.Dir("./public"))))        http.ListenAndServe(":3000",nil)}$ n" o) G. T% Q+ ]
多亏了这一点,你所有的文件./public都可以在localhost:3000/static
8 g$ A5 |: G; t# x  i9 c没有http.StripPrefix如果您尝试访问 file localhost:3000/static/test.html,服务器将在./public/static/test.html
( d1 O, Z; l% S0 j5 L1 y* D这是因为服务器将整个 URI 被视为文件的相对路径。
8 b5 v$ ?# R7 i0 P幸运的是,它可以通过内置函数轻松解决。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则