【发布时间】:2023-04-10 17:34:02
【问题描述】:
我需要在提供静态内容、html、css 和 js 时设置 cookie。
下面的代码提供一个裸 html 文件,没有 css 等。
所有的 css 和 js 都位于与 index.html 相同级别的“assets”文件夹中。
有什么建议吗?
func indexHandler(w http.ResponseWriter, req *http.Request) {
http.SetCookie(w, &http.Cookie{Name: config.cookieName, Value: config.cookieValue})
cookie, err := req.Cookie(config.cookieName)
if err != nil {
log.Println(whereami.WhereAmI(), err.Error())
}
log.Println("Cookie: ", cookie)
http.StripPrefix("/", http.FileServer(http.Dir("./"))).ServeHTTP(w, req)
}
但是这样做会提供一个完整的 html 页面:
router.PathPrefix("/").Handler(http.FileServer(http.Dir("./")))
【问题讨论】:
-
http.FileServer返回一个Handler,您正在丢弃它,所以在这种情况下它什么也不做。创建一次FileServer,保存它,然后使用fs.ServeHTTP(w,req)传递调用。并移除WriteHeader调用,以便FileServer可以正确设置标题和状态。 -
如果它给出 404,那么您在 URL 中的任何路径都不会与当前工作目录中的相同路径(您告诉它查找文件的位置)对齐。跨度>
标签: go cookies docker-compose