go - 如何使用反向代理根据响应标头设置 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?
如果不清楚,这是所需的工作流程:
- 用户请求http://example.com/foo/bar
- 将应用代理转到http://baz.example.com
- baz.example.com 设置响应头
X-FOO
- Go 应用程序通过使用响应标头
MYAPPFOO
的值设置 cookie 来修改响应X-FOO
- cookie 被写入用户的浏览器
解决方案
推荐阅读
- excel - 替换为 3 个条件失败 - Excel VBA
- mysql - sequlize 与客户共享交易
- python - coco json的图像分割掩码到多边形
- javascript - 在 React 中使用 Grid 时出现 Material UI 错误
- python - 如何在 Django 中集成特定属性
- excel - 我应该更好地修改 .ClearContents 的一些代码吗?
- python - 多维实现的交叉熵
- applescript - Automator 在下载时抛出错误,但下载仍然完成?
- r - 如何在 purrr::map()“列表或原子向量”参数的参数中引用变量索引?
- workbox - 如何使用 workbox-cli 实现“先缓存后网络”策略?