首页 > 解决方案 > 如何使用反向代理根据响应标头设置 cookie?

问题描述

我正在尝试根据反向代理请求中使用的中间件中的响应标头设置 cookie。

问题:我只能在之后获取响应标头,next.ServerHTTP(w, r)并且我只能在它之前设置一个 cookie。(所以它看起来)

handler请参阅我用作中间件的方法中的注释。(我已经为这个问题缩写了这段代码)

package main

import (

    "github.com/gorilla/mux"
    "log"
    "net/http"
    "net/http/httputil"
    "net/url"
)

func setCookie(w http.ResponseWriter, name string, value string) {
    ...
    http.SetCookie(w, &cookie)
}

func handler(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        // setCookie() works here
        // but I cannot access w.Header().Get("X-FOO")

        next.ServeHTTP(w, r)

        // I can access w.Header().Get("X-FOO") here
        // but setCookie() does not cookie the user's browser

        // If I could do it all in one place, this is what I would do:
        if r.Method == "POST" && r.URL.String() == "/login" {
            foo := w.Header().Get("X-FOO")
            setCookie(w, "MYAPPFOO", foo)

        }
    })
}

func main() {

    r := mux.NewRouter()
    r.Use(handler)
        proxy := httputil.NewSingleHostReverseProxy("https://baz.example.com/")
        r.PathPrefix("/").Handler(proxy)
        log.Fatal(http.ListenAndServe(":9001", r))
}

是否可以根据服务器的响应标头设置 cookie?

如果不清楚,这是所需的工作流程:

标签: go

解决方案


推荐阅读