implement grpc gateway and addl handler support

This commit is contained in:
2025-03-24 16:24:03 -04:00
parent 4e014d5ea0
commit 262f6a4232
12 changed files with 241 additions and 165 deletions

View File

@ -2,20 +2,18 @@ package grpc
import (
"context"
"net/http"
"fmt"
"net"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
)
const API_PATH = "/api" // TODO: Make Configurable
// TODO: Add GetClientConn method to appGRPCServer that supports TLS, auth, etc..
// Will probably have to convert server opts to client opts
func (a *appGRPCServer) registerServiceGatewayHandlers(ctx context.Context, service *opts.GRPCService) {
if len(service.GwRegistrationFuncs) < 1 {
return
@ -29,15 +27,30 @@ func (a *appGRPCServer) registerServiceGatewayHandlers(ctx context.Context, serv
))
defer span.End()
// TODO: move to GetClientConn method which doesn't exist yet
clientConn, _ := grpc.NewClient(a.opts.Listen)
clientConn := a.GetClientConn(ctx)
for _, registerGW := range service.GwRegistrationFuncs {
registerGW(ctx, a.gatewayMux, clientConn)
}
}
// Add our gateway mux to an existing http.ServeMux
func (a *appGRPCServer) mergeGatewayMuxWithHTTPMux(mux *http.ServeMux) {
mux.Handle(API_PATH, http.StripPrefix(API_PATH, a.gatewayMux))
func (a *appGRPCServer) GetClientConn(ctx context.Context) *grpc.ClientConn {
span := trace.SpanFromContext(ctx)
host, port, err := net.SplitHostPort(a.opts.Listen)
if err != nil {
panic(err)
}
if host == "" || host == "0.0.0.0" {
host = "localhost"
}
clientConn, err := grpc.NewClient(fmt.Sprintf("%s:%s", host, port), a.opts.GRPCDialOpts...)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
return clientConn
}