javascript - 提供静态内容并设置Cookie

标签 javascript html go docker-compose webassembly

这是一段简短的代码,用以说明问题。
我正在尝试同时提供静态内容和设置Cookie。
运行代码时,不提供静态内容。
关键是要提供整个 Assets 文件夹。
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会尝试仅匹配给定的模板(在您的示例中为“/”)。
来自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))
}

关于javascript - 提供静态内容并设置Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62561356/

相关文章:

html - 从 DiagrammeR 导出美人鱼图

pointers - 声明一个指向结构的指针

xml - 戈朗 : Unmarshal Self Closing Tags

javascript - VoiceOver 不会读取 Chrome 中 window.alert 内的文本

javascript - 使用javascript检查textarea中是否输入了任何html标签

Javascript push 方法来填充数组

javascript - 一种将一堆输入绑定(bind)到一堆 Backbone 模型的方法

css - 在 div 中调整图像大小(再次)

html - 我如何在元标记文本中使用 css 选择器

opencv - go.go.gocmv运行时出错./cmd/version/main.go