如何包含 css 去 lang 应用程序



我在向我的 web 应用程序添加一些 CSS 时遇到问题,该应用程序是使用 go lang 创建的。 main.go和 html 文件包含在根目录中,style.css包含在root/css目录中

我的 .*go 代码是

package main
import (
    "html/template"
    "net/http"
)
func main(){
    http.HandleFunc("/home", mainViewHandler)
    http.ListenAndServe(":8080", nil)
}
func mainViewHandler(responseWriter http.ResponseWriter,request *http.Request){
    t, _ := template.ParseFiles("main.html")
    t.Execute(responseWriter, 0)
}

HTML代码是

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" href="todo/style.css">
        <meta charset="UTF-8">
        <title>Main Page</title>
    </head>
    <body>
        <h2>Take your choice</h2>
        <a href="/edit">Edit</a>
        <a href="/add">Add</a>
        <a href="/list">List</a>
    </body>
</html>

你需要告诉go从root/css目录提供文件。请记住,当您运行应用程序时,root/css 应该位于应用程序的工作文件夹中。

我不直接使用 http 包,但相信在你的情况下它应该如下(在 ListenAndServe 之前):

http.Handle("/todo/", http.StripPrefix("root/css/", http.FileServer(http.Dir("root/css"))))

但您可能需要根据实际文件夹配置进行调整。

请参阅此处的文档

相关内容

最新更新