提供静态内容和设置 cookie



这是一段浓缩的代码来说明这个问题。

我正在尝试同时提供静态内容和设置 cookie。

运行代码时,不会提供静态内容。

关键是提供整个资产文件夹。

主去

package main
import (
"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")
}

Dockerfile

FROM golang:alpine AS builder
RUN mkdir /app
ADD . /app/
WORKDIR /app
COPY ./main.go .
COPY ./favicon.ico .
COPY ./assets /assets
RUN go mod init static.com
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build $(ls -1 *.go)
EXPOSE 9988
CMD ["go", "run", "."]

docker-compose.yml

version : '3'
services:
app:
container_name: container_static
build:
context: ./
ports:
- 9988:9988
restart: always

完整的存储库在这里:https://github.com/pigfox/static-cookie

您需要使用 PathPrefix 来注册处理程序,如下所示。 单独HandleFunc将尝试仅匹配给定的模板(在您的示例中:"/"(。

来自路径前缀的文档

路径前缀为 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))
}

相关内容

  • 没有找到相关文章

最新更新