I'm trying to set a cookie based on a response header from within middleware used in a reverse proxy request.
Problem: I can only get the response header after next.ServerHTTP(w, r)
and I can only set a cookie before it. (So it seems)
See the comments in the handler
method I'm using as middleware. (I've abbreviated this code for this question)
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))
}
Is it possible to set a cookie based on a response header from the server?
If it's not clear, here's the desired workflow:
- User requests http://example.com/foo/bar
- Go app proxies to http://baz.example.com
- baz.example.com sets a response header
X-FOO
- Go app modifies response by setting a
MYAPPFOO
cookie with the value of theX-FOO
response header - The cookie is written to the user's browser