Skip to content

Commit

Permalink
feat: enable h2c
Browse files Browse the repository at this point in the history
  • Loading branch information
pinglin committed Jan 13, 2023
1 parent c045d29 commit a1e3598
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 33 deletions.
4 changes: 2 additions & 2 deletions config/.env
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ API_GATEWAY_HOST=api-gateway
API_GATEWAY_HTTPS_PORT=8080
API_GATEWAY_STATS_PORT=8090
API_GATEWAY_METRICS_PORT=9000
API_GATEWAY_CERT_FILE=/etc/ssl/dev-cert.pem
API_GATEWAY_KEY_FILE=/etc/ssl/dev-key.pem
API_GATEWAY_CERT_FILE=
API_GATEWAY_KEY_FILE=
API_GATEWAY_LOG_LEVEL=DEBUG

# pipeline-backend
Expand Down
2 changes: 2 additions & 0 deletions config/base.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
"name": "API Gateway",
"port": {{ .ports.api_gateway_port }},
"allow_insecure_connections": true,
{{ if and .tls.public_key .tls.private_key }}
"tls": {
"public_key": "{{ .tls.public_key }}",
"private_key": "{{ .tls.private_key }}"
},
{{ end }}
"timeout": "3000ms",
"cache_ttl": "300s",
{{ include "plugin" }},
Expand Down
52 changes: 21 additions & 31 deletions plugin/server/grpc/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (

"github.com/akosyakov/grpc-proxy/proxy"
"github.com/gogo/status"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
Expand Down Expand Up @@ -38,7 +40,7 @@ func (r registerer) RegisterHandlers(f func(
}

func (r registerer) registerHandlers(ctx context.Context, extra map[string]interface{}, h http.Handler) (http.Handler, error) {

logger, _ := logger.GetZapLogger()
defer func() {
// can't handle the error due to https://github.com/uber-go/zap/issues/880
Expand Down Expand Up @@ -70,51 +72,39 @@ func (r registerer) registerHandlers(ctx context.Context, extra map[string]inter

target, _ := url.Parse(endpoint.(string))

conn, err := grpc.Dial(
conn, err := grpc.Dial(
target.Host,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithCodec(proxy.Codec()))

director := func(ctx context.Context, fullMethodName string) (context.Context, *grpc.ClientConn, error) {
md, ok := metadata.FromIncomingContext(ctx)
outCtx := metadata.NewOutgoingContext(ctx, md.Copy())
if ok {
if ok {
return outCtx, conn, err
}
return nil, nil, status.Errorf(codes.Unimplemented, "Unknown method")
}

grpcServerOpts = append(
grpcServerOpts,
grpcServerOpts,
grpc.UnknownServiceHandler(proxy.TransparentHandler(director)))

grpcServers[srv] = grpc.NewServer(grpcServerOpts...)
}

// Return the actual handler wrapping or your custom logic so it can be used as a replacement for the default http handler
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// According to https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
// The Content-Type of gRPC has the "application/grpc" prefix
if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
// r.URL.Path is /vdp.{service_name}.v1alpha.{service_name}Service/{method}
srv := strings.Split(strings.Split(r.URL.Path, "/")[1], ".")[1]
grpcServers[srv].ServeHTTP(w, r)
} else {
h.ServeHTTP(w, r)
}
}), nil
}

func removeDuplicateHeader(strSlice []string) []string {
allKeys := make(map[string]bool)
list := []string{}
for _, item := range strSlice {
if _, value := allKeys[item]; !value {
allKeys[item] = true
list = append(list, item)
}
}
return list
return h2c.NewHandler(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
// r.URL.Path is /vdp.{service_name}.v1alpha.{service_name}Service/{method}
srv := strings.Split(strings.Split(r.URL.Path, "/")[1], ".")[1]
grpcServers[srv].ServeHTTP(w, r)
} else {
h.ServeHTTP(w, r)
}
}),
&http2.Server{},
), nil
}

func init() {
Expand Down

0 comments on commit a1e3598

Please sign in to comment.