提供静态内容和设置 cookie

Serving static content & setting cookie

这是一段精简的代码来说明问题。

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

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

重点是为整个资产文件夹提供服务。

main.go

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 alone 将尝试仅匹配给定的模板(在您的示例中:“/”)。

来自 PathPrefix 的文档

PathPrefix adds a matcher for the URL path prefix. This matches if the given template is a prefix of the full URL path

这可以确保您的所有路径(如 /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))
}