gpt4 book ai didi

go - 使用 go 通过 http 提供静态文件

转载 作者:IT王子 更新时间:2023-10-29 01:52:22 26 4
gpt4 key购买 nike

在我的 html 中,我试图包含 JS 使用

<script src="/js/app.js"></script>

我也试过相对路径(从服务器位置)

<script src="js/app.js"></script>

和 html 文件中的相对关系

我的文件结构

-js
app.js
-templates
index.html
hub.go
main.go

main.go 是服务器

func main() {
http.HandleFunc("/", rootHandler)
http.ListenAndServe(":8080", nil)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "Templates/index.html")
}

我是否遗漏了某些东西,我必须通过服务器来提供 css/js 服务吗?或者简单的 html 应该工作

最佳答案

要通过 http 提供文件,请为目录定义一个 FileServer,然后使用 http.Handle 将其路由到例如 "/assets/"
以下设置应该适合您:

目录结构:

├── assets/
│   ├── js
│   └── css
├── templates/
└── main.go

主.go

func main() {
http.HandleFunc("/", rootHandler)
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
http.ListenAndServe(":8080", nil)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "templates/index.html")
}

在你的模板文件中:

<script src="/assets/js/app.js"></script>

关于go - 使用 go 通过 http 提供静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43425594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com