gpt4 book ai didi

go - 使用 Go net/http 提供链接的 css 和 js

转载 作者:数据小太阳 更新时间:2023-10-29 03:46:42 31 4
gpt4 key购买 nike

我无法使 net/http 使用链接的 css 和脚本文件提供 html 文件。

我有

site/lib/ratchet/css/ratchet.css
site/lib/ratchet/js/ratchet.js

在我的项目文件夹结构中,以及

site/src/index.html

在这个 index.html 中我包含了两个文件

<link href="../lib/ratchet/css/ratchet.css" rel="stylesheet">

<script src="../lib/ratchet/js/ratchet.js"></script>

为它服务的 Go 函数是:

func index(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "/Users/faruk/dev/otp/site/src/index.html")
}

在 main() 中:

r.HandleFunc("/", index).
Methods("GET")

我在上面使用了 gorilla/mux。

我可以从浏览器查看它,但只有 html。这两个链接文件已给出 404。

http.ServeFile 不能自动解析链接的 css 和 js 文件以提供 index.html 或类似文件吗?在 Go net/http 中提供 html 文件的标准方法是什么?

最佳答案

您需要设置一个文件服务器来提供在您的 lib 目录中找到的文件。 Go在http包中有一个文件服务器

func init() {
http.Handle("/lib/", http.FileServer(http.Dir("/Users/faruk/dev/otp/site/")))
}

关于go - 使用 Go net/http 提供链接的 css 和 js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26026259/

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