【问题标题】:Serving static content & setting cookie提供静态内容和设置 cookie
【发布时间】:2020-10-15 02:02:03
【问题描述】:

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

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

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

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

ma​​in.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

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

【问题讨论】:

    标签: javascript html go docker-compose webassembly


    【解决方案1】:

    您需要使用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))
    }
    

    【讨论】:

    • 我刚刚注意到我在 html 文件旁边的 favicon.ico 上收到了 404。
    • 从您的仓库中,您似乎已将网站图标设置为 favicon.ico=1。不应该只是favicon.ico吗?
    • 不错的收获!有趣的是,它一直有效,所以我没有注意到。
    猜你喜欢
    • 2018-04-05
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多