首页 > 解决方案 > 如何在 golang 中提供静态文件

问题描述

我正在尝试在 golang 中创建一个简单的网络服务器,但我不知道如何提供静态 css 文件。mi项目的结构如下:

project folder
->static
  ->templates
    ->index.gohtml
  ->styles
    ->style.css

在我的模板中,我有这个简单的 html 行:<link href="/styles/styles.css" type="text/css"> 在 main.go 我有这个:

http.Handle("/styles", http.FileServer(http.Dir("./static/styles")))
...
//show the backend homepage that refers to index.gohtml
http.HandleFunc("/backend/home", handler)

标签: go

解决方案


现在当他们点击时/styles,它会尝试访问./static/styles/styles,所以你通常像这样去掉前缀:

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

https://pkg.go.dev/net/http#example-FileServer-StripPrefix


推荐阅读