【问题标题】:Static content with HandleFunc使用 HandleFunc 的静态内容
【发布时间】: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


【解决方案1】:

就像@Adrian 提到的那样,这似乎是您期望提供的文件位置的问题。例如,下面的代码在 dir 结构中应该可以正常工作

main.go 
index.html
package main

import (
    "net/http"
)

func main() {
    http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
        http.SetCookie(w, &http.Cookie{Name: "foo", Value: "bar"})
        http.StripPrefix("/foo", http.FileServer(http.Dir("./"))).ServeHTTP(w, r)
    })

    panic(http.ListenAndServe(":3030", nil))
}

[编辑]:去除前缀

【讨论】:

  • @pigfox 我已经通过删除该处理程序的前缀来更新代码。请参阅this 了解更多关于为什么需要去除前缀。
  • 感谢您的建议,它现在提供没有 css 的 html 文件。代码已更新。
  • @pigfox CSS 提供不同的请求,请检查使用浏览器网络控制台发送的请求
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
相关资源
最近更新 更多