这是一段浓缩的代码来说明问题。我正在尝试同时提供静态内容和设置 cookie。运行代码时,不会提供静态内容。关键是为整个资产文件夹提供服务。main.gopackage mainimport ( "fmt" "log" "net/http" "github.com/gorilla/mux" "github.com/rs/cors" "github.com/jimlawless/whereami")func main(){ target:= "http://127.0.0.1:9988" corsOpts := cors.New(cors.Options{ AllowedOrigins: []string{target}, //you service is available and allowed for this base url AllowedMethods: []string{ http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodOptions, http.MethodHead, }, AllowedHeaders: []string{ "*", //or you can your header key values which you are using in your application }, }) router := mux.NewRouter() router.HandleFunc("/", indexHandler).Methods("GET") fmt.Println("Serving ", target) http.ListenAndServe(":9988", corsOpts.Handler(router))}func indexHandler(w http.ResponseWriter, req *http.Request){ addCookie(w, "static-cookie", "123654789") cookie, err := req.Cookie("static-cookie") if err != nil { log.Println(whereami.WhereAmI(), err.Error()) } log.Println("Cookie: ", cookie) http.StripPrefix("/", http.FileServer(http.Dir("./"))).ServeHTTP(w, req)}func addCookie(w http.ResponseWriter, name, value string) { cookie := http.Cookie{ Name: name, Value: value, Domain: "127.0.0.1", Path: "/", MaxAge: 0, HttpOnly: true, } http.SetCookie(w, &cookie) log.Println("Cookie added")}DockerfileFROM golang:alpine AS builderRUN mkdir /appADD . /app/WORKDIR /appCOPY ./main.go .COPY ./favicon.ico .COPY ./assets /assetsRUN go mod init static.comRUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build $(ls -1 *.go)EXPOSE 9988CMD ["go", "run", "."]码头工人-compose.ymlversion : '3'services: app: container_name: container_static build: context: ./ ports: - 9988:9988 restart: always完整的仓库在这里:https ://github.com/pigfox/static-cookie
1 回答
白衣染霜花
TA贡献1796条经验 获得超10个赞
您需要使用PathPrefix来注册您的处理程序,如下所示。HandleFunc单独将尝试仅匹配给定的模板(在您的示例中:“/”)。
来自 PathPrefix 的文档
PathPrefix 为 URL 路径前缀添加一个匹配器。如果给定模板是完整 URL 路径的前缀,则匹配
这可以确保您的所有路径(如 /index.html、/assets/.* 等)都匹配并由处理程序提供服务。
func main() {
router := mux.NewRouter()
router.PathPrefix("/").HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
http.SetCookie(rw, &http.Cookie{Name: "foo", Value: "bar"})
http.FileServer(http.Dir("./")).ServeHTTP(rw, r)
})
panic(http.ListenAndServe(":3030", router))
}
- 1 回答
- 0 关注
- 117 浏览
添加回答
举报
0/150
提交
取消