Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add header in http.Handler,but not take effect #1835

Closed
damozhiying opened this issue Nov 23, 2020 · 1 comment
Closed

add header in http.Handler,but not take effect #1835

damozhiying opened this issue Nov 23, 2020 · 1 comment

Comments

@damozhiying
Copy link

damozhiying commented Nov 23, 2020

grpc-gateway rest server

srv := &http.Server{
		Addr:         httpPort,
		ReadTimeout:  60 * time.Second,
		WriteTimeout: 60 * time.Second,
		// add handler with middleware
		Handler: middleware.AddRequestID(
			middleware.AddLogger(log.WithField("gateway", "rest"), handler)),
	}

AddLogger code

func AddLogger(logger *logrus.Entry, h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

h.ServeHTTP(w, r)

w.Header().Set("Grpc-Metadata-Yyyyyyyyyyyyyyyy-Request-ID", "fadfadsfadsf")
		w.Header()["TEST-HEADER-EKY"] = []string{"TEST-HEADER-EKY-110"}
		hs["TEST-HEADER-EKY-1"] = []string{"TEST-HEADER-EKY-110-1"}
		w.Header().Set("Access-Control-Allow-Origin", "*")

browser f12 show

Content-Type →application/json
Lxf--Abc-Www-Authenticate →222222222xxxxxxxxxx
Lxf--Content-Type →application/grpc
Lxf--Grpc-Metadata-Some-Key →222222222xxxxxxxxxx
Lxf--Www-Authenticate →222222222xxxxxxxxxx
Date →Mon, 23 Nov 2020 01:18:04 GMT
Content-Length →120
@johanbrandhorst
Copy link
Collaborator

You can't use net/http like this. Headers can only be set before you start writing to the body, and calling h.ServeHTTP is going to write to the body before you're setting the headers (see https://golang.org/pkg/net/http/#ResponseWriter). In your last issue, I suggested you use a header matcher, which is documented here: https://grpc-ecosystem.github.io/grpc-gateway/docs/mapping/customizingyourgateway/#set-http-headers. If you want to set headers in a middleware wrapper you might have to do it before calling ServeHTTP.

Closing as this is not an issue with the grpc-gateway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants