|
| 1 | +package multiproto |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "strings" |
| 6 | + |
| 7 | + "github.com/improbable-eng/grpc-web/go/grpcweb" |
| 8 | + "golang.org/x/net/http2" |
| 9 | + "golang.org/x/net/http2/h2c" |
| 10 | + "google.golang.org/grpc" |
| 11 | +) |
| 12 | + |
| 13 | +func OriginAllowed(_ string) bool { |
| 14 | + return true |
| 15 | +} |
| 16 | + |
| 17 | +func WebSocketOriginAllowed(_ *http.Request) bool { |
| 18 | + return true |
| 19 | +} |
| 20 | + |
| 21 | +func NewHandler(grpcServer *grpc.Server) http.Handler { |
| 22 | + return h2c.NewHandler( |
| 23 | + &Handler{ |
| 24 | + grpcServer: grpcServer, |
| 25 | + webServer: grpcweb.WrapServer( |
| 26 | + grpcServer, |
| 27 | + grpcweb.WithWebsockets(true), |
| 28 | + grpcweb.WithOriginFunc(OriginAllowed), |
| 29 | + grpcweb.WithWebsocketOriginFunc(WebSocketOriginAllowed), |
| 30 | + ), |
| 31 | + httpHandler: http.DefaultServeMux, |
| 32 | + }, |
| 33 | + &http2.Server{}, |
| 34 | + ) |
| 35 | +} |
| 36 | + |
| 37 | +type Handler struct { |
| 38 | + grpcServer *grpc.Server |
| 39 | + webServer *grpcweb.WrappedGrpcServer |
| 40 | + httpHandler http.Handler |
| 41 | +} |
| 42 | + |
| 43 | +func (s *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 44 | + switch { |
| 45 | + case r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc"): |
| 46 | + s.grpcServer.ServeHTTP(w, r) |
| 47 | + case s.webServer.IsGrpcWebRequest(r) || s.webServer.IsGrpcWebSocketRequest(r): |
| 48 | + s.webServer.ServeHTTP(w, r) |
| 49 | + default: |
| 50 | + s.httpHandler.ServeHTTP(w, r) |
| 51 | + } |
| 52 | +} |
0 commit comments