Created
July 5, 2022 09:21
-
-
Save akhy/8cd25f6c770fdb9c97013cd680c63691 to your computer and use it in GitHub Desktop.
gRPC + HTTP handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mux | |
import ( | |
"net/http" | |
"strings" | |
"golang.org/x/net/http2" | |
"golang.org/x/net/http2/h2c" | |
) | |
// NewHandler create new HTTP handler to serve both gRPC and regular HTTP requests | |
func NewHandler(httpHandler http.Handler, grpcHandler http.Handler) http.Handler { | |
muxHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
if r.ProtoMajor == 2 && strings.HasPrefix(r.Header.Get("content-type"), "application/grpc") { | |
grpcHandler.ServeHTTP(w, r) | |
return | |
} | |
httpHandler.ServeHTTP(w, r) | |
}) | |
return h2c.NewHandler(muxHandler, &http2.Server{}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment