如何在 golang 中提供静态文件

时间:2021-07-15 17:48:34

标签: go

我正在尝试在 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)

2 个答案:

答案 0 :(得分:4)

现在当他们点击 /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

答案 1 :(得分:0)

我想通了(只是为了运气)

我必须把它放在 main.go 上

SVGElement

这个在标题上:

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

否则无效