Skip to content

Instantly share code, notes, and snippets.

@akhy
Created July 5, 2022 09:21
Show Gist options
  • Save akhy/8cd25f6c770fdb9c97013cd680c63691 to your computer and use it in GitHub Desktop.
Save akhy/8cd25f6c770fdb9c97013cd680c63691 to your computer and use it in GitHub Desktop.
gRPC + HTTP handler
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