Documentation ¶
Overview ¶
Package grpcutil implements a gRPC HTTP handler and OpenAPI proxy. Useful to serve gRPC requests from an existing HTTP servers.
Example (Client) ¶
package main import ( "context" "crypto/tls" "crypto/x509" "log" "github.com/c4milo/handlers/grpcutil" "google.golang.org/grpc" "google.golang.org/grpc/credentials" ) func main() { tlsKeyPair, err := tls.LoadX509KeyPair("testdata/selfsigned.pem", "testdata/selfsigned-key.pem") if err != nil { panic(err) } x509Cert, err := x509.ParseCertificate(tlsKeyPair.Certificate[0]) if err != nil { panic(err) } certPool := x509.NewCertPool() certPool.AddCert(x509Cert) clientCreds := credentials.NewClientTLSFromCert(certPool, "") clientOpts := []grpc.DialOption{ grpc.WithTransportCredentials(clientCreds), } clientConn, err := grpc.Dial("localhost:8080", clientOpts...) if err != nil { panic(err) } defer clientConn.Close() test := grpcutil.NewTestClient(clientConn) res, err := test.Hola(context.Background(), &grpcutil.HolaRequest{}) if err != nil { panic(err) } log.Println(res.Greeting) }
Output:
Example (Server) ¶
package main import ( "crypto/tls" "fmt" "net/http" "os" "os/signal" "github.com/c4milo/handlers/grpcutil" "github.com/c4milo/handlers/logger" "golang.org/x/net/context" ) type Service struct{} // Hola prints greeting message func (s *Service) Hola(ctx context.Context, r *grpcutil.HolaRequest) (*grpcutil.HolaResponse, error) { return &grpcutil.HolaResponse{Greeting: "Hola from gRPC service!"}, nil } func registerService(binding grpcutil.ServiceBinding) error { grpcutil.RegisterTestServer(binding.GRPCServer, new(Service)) return grpcutil.RegisterTestHandler(context.Background(), binding.GRPCGatewayMuxer, binding.GRPCGatewayClient) } func main() { tlsKeyPair, err := tls.LoadX509KeyPair("testdata/selfsigned.pem", "testdata/selfsigned-key.pem") if err != nil { panic(err) } mux := http.DefaultServeMux mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Hola from HTTP handler!") }) handler := logger.Handler(mux) options := []grpcutil.Option{ grpcutil.WithTLSCert(&tlsKeyPair), grpcutil.WithPort("8080"), grpcutil.WithServices([]grpcutil.ServiceRegisterFn{registerService}), } handler = grpcutil.Handler(handler, options...) srv := &http.Server{ Addr: "localhost:8080", Handler: handler, TLSConfig: &tls.Config{ Certificates: []tls.Certificate{tlsKeyPair}, NextProtos: []string{"h2"}, }, } c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) go func() { for range c { if srv != nil { srv.Close() } } }() done := make(chan bool) fmt.Printf("Starting server in %q... ", srv.Addr) go func() { if err := srv.ListenAndServeTLS("", ""); err != nil { done <- true if err != http.ErrServerClosed { panic(err) } } else { done <- true } }() fmt.Println("done") <-done }
Output:
Index ¶
- func ForwardMetadataCLIntcp() grpc.UnaryClientInterceptor
- func Handler(h http.Handler, opts ...Option) http.Handler
- func NewLZ4Compressor() grpc.Compressor
- func NewLZ4Decompressor() grpc.Decompressor
- type Option
- func WithCompressor(c grpc.Compressor) Option
- func WithDecompressor(d grpc.Decompressor) Option
- func WithGWServerOpts(opts []runtime.ServeMuxOption) Option
- func WithPort(port string) Option
- func WithServerOpts(opts []grpc.ServerOption) Option
- func WithServices(services []ServiceRegisterFn) Option
- func WithSkipPath(path ...string) Option
- func WithTLSCert(cert *tls.Certificate) Option
- type ServiceBinding
- type ServiceRegisterFn
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ForwardMetadataCLIntcp ¶
func ForwardMetadataCLIntcp() grpc.UnaryClientInterceptor
ForwardMetadataCLIntcp returns a client unary interceptor that forwards incoming context metadata to its outgoing counterpart. In some scenarios, using this interceptor may pose security risks since authorization tokens or credentials can be accidentally leaked to third-party services. It can be very handy otherwise when used with trusted services. Since it allows to delegate or impersonate users when reaching out to internal services by forwarding their original access tokens or authentication credentials.
func Handler ¶
Handler serves gRPC and OpenAPI requests or hands over to the next handler if they are not gRPC or application/json requests.
func NewLZ4Compressor ¶
func NewLZ4Compressor() grpc.Compressor
NewLZ4Compressor returns a new LZ4 compressor instance.
func NewLZ4Decompressor ¶
func NewLZ4Decompressor() grpc.Decompressor
NewLZ4Decompressor returns a new LZ4 decompressor instance.
Types ¶
type Option ¶
type Option func(*options)
Option implements http://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html
func WithCompressor ¶
func WithCompressor(c grpc.Compressor) Option
WithCompressor sets gRPC server and gateway client compressor. Use this function instead of passing compressor through grcputil.WithServerOpts()
func WithDecompressor ¶
func WithDecompressor(d grpc.Decompressor) Option
WithDecompressor sets gRPC server and gateway client decompressor. Use this function instead of passing a decompressor through grcputil.WithServerOpts()
func WithGWServerOpts ¶
func WithGWServerOpts(opts []runtime.ServeMuxOption) Option
WithGWServerOpts sets GRPC Gateway server options. Optional.
func WithPort ¶
WithPort sets the port for the OpenAPI gRPC client to use when connecting to the gRPC service.
func WithServerOpts ¶
func WithServerOpts(opts []grpc.ServerOption) Option
WithServerOpts sets gRPC server options. Optional.
func WithServices ¶
func WithServices(services []ServiceRegisterFn) Option
WithServices sets the list of services to register with the gRPC and OpenAPI servers. Required.
func WithSkipPath ¶
WithSkipPath allows other handlers to serve static JSON files by instructing the GRPC Gateway Muxer to skip serving the given prefixed paths.
func WithTLSCert ¶
func WithTLSCert(cert *tls.Certificate) Option
WithTLSCert sets the TLS certificate to use by the gRPC server and OpenAPI gRPC client. Required.
type ServiceBinding ¶
type ServiceBinding struct { GRPCServer *grpc.Server GRPCGatewayClient *grpc.ClientConn GRPCGatewayMuxer *runtime.ServeMux }
ServiceBinding are the gRPC server, and gRPC HTTP gateway to which the service will be bound to.
type ServiceRegisterFn ¶
type ServiceRegisterFn func(ServiceBinding) error
ServiceRegisterFn defines a function type for registering gRPC services.