你如何使用 go web 服务器提供静态 html 文件?
技术问答
258 人阅读
|
0 人回复
|
2023-09-12
|
如何使用 go web 服务器提供 index.html(或其他一些静态 HTML 文件)?
; p2 _$ ]" j3 n+ U0 Z0 q- j2 g4 j我只想要一个基本的静态 HTML 文件(如文章)我可以从 go web 服务器提供。HTML 应该在 go 程序外修改就像使用 HTML 模板是一样的。
# J& z/ T: v2 u0 ^; x& m z. E这是我的 Web 服务器只托管硬编码文本(Hello world!”)。
) p. H8 ~& S5 V4 Npackage 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)}
* e9 B% W# w' i4 K5 W+ q. Z
" s/ N* U( h5 [; _ ? 解决方案: . c y0 @5 C2 ^( \$ D
使用 Golang net/http 包,这个任务很容易。. R( u! t( X) j7 c' @
你需要做的是:$ Q7 _; Z. h) N3 N
package mainimport ( "net/http")func main()(){ http.Handle("/",http.FileServer(http.Dir("./static"))) http.ListenAndServe(":3000",nil)}
: E6 Y i* G6 j' ~! t7 L) b+ }: k9 Z 假设静态文件位于static在项目根目录中命名的文件夹中。
6 m# Q9 }% R3 o$ M2 ^若在文件夹中static,您将进行index.html文件调用http://localhost:这将导致索引文件的呈现,而不是所有可用的文件。
' F v+ U; I/ _; W6 M此外,在文件夹中调用任何其他文件(例如http://localhost:3000/clients.html)浏览器正确显示文件(至少 Chrome、Firefox 和 Safari )
( H0 {7 f& ^6 A3 u; Q) ] W更新: 不同于/url 提供文件如果您想提供文件,请从./publicurl 下文件夹说:localhost:3000/static您必须使用附加功能:func StripPrefix(prefix string,h Handler) Handler像这样:& K5 {# d9 N* m: D
package mainimport ( "net/http")func main()(){ http.Handle("/static/",http.StripPrefix("/static/",http.FileServer(http.Dir("./public")))) http.ListenAndServe(":3000",nil)}
8 G% f$ R; @2 G0 Z) {' h 多亏了这一点,你所有的文件./public都可以在localhost:3000/static2 y p! ] Q; y8 N" b9 B* ]0 Z
没有http.StripPrefix如果您尝试访问 file localhost:3000/static/test.html,服务器将在./public/static/test.html, E- y7 K8 J$ S# \
这是因为服务器将整个 URI 被视为文件的相对路径。1 t5 _. ~: ~" R- Z2 l5 M
幸运的是,它可以通过内置函数轻松解决。 |
|
|
|
|
|