github.com/grpc-ecosystem/grpc-gateway/v2@v2.19.1/examples/internal/gateway/main.go (about) 1 package gateway 2 3 import ( 4 "context" 5 "net/http" 6 7 gwruntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" 8 "google.golang.org/grpc/grpclog" 9 ) 10 11 // Endpoint describes a gRPC endpoint 12 type Endpoint struct { 13 Network, Addr string 14 } 15 16 // Options is a set of options to be passed to Run 17 type Options struct { 18 // Addr is the address to listen 19 Addr string 20 21 // GRPCServer defines an endpoint of a gRPC service 22 GRPCServer Endpoint 23 24 // OpenAPIDir is a path to a directory from which the server 25 // serves OpenAPI specs. 26 OpenAPIDir string 27 28 // Mux is a list of options to be passed to the gRPC-Gateway multiplexer 29 Mux []gwruntime.ServeMuxOption 30 } 31 32 // Run starts a HTTP server and blocks while running if successful. 33 // The server will be shutdown when "ctx" is canceled. 34 func Run(ctx context.Context, opts Options) error { 35 ctx, cancel := context.WithCancel(ctx) 36 defer cancel() 37 38 conn, err := dial(ctx, opts.GRPCServer.Network, opts.GRPCServer.Addr) 39 if err != nil { 40 return err 41 } 42 go func() { 43 <-ctx.Done() 44 if err := conn.Close(); err != nil { 45 grpclog.Errorf("Failed to close a client connection to the gRPC server: %v", err) 46 } 47 }() 48 49 mux := http.NewServeMux() 50 mux.HandleFunc("/openapiv2/", openAPIServer(opts.OpenAPIDir)) 51 mux.HandleFunc("/healthz", healthzServer(conn)) 52 53 gw, err := newGateway(ctx, conn, opts.Mux) 54 if err != nil { 55 return err 56 } 57 mux.Handle("/", gw) 58 59 s := &http.Server{ 60 Addr: opts.Addr, 61 Handler: allowCORS(mux), 62 } 63 go func() { 64 <-ctx.Done() 65 grpclog.Infof("Shutting down the http server") 66 if err := s.Shutdown(context.Background()); err != nil { 67 grpclog.Errorf("Failed to shutdown http server: %v", err) 68 } 69 }() 70 71 grpclog.Infof("Starting listening at %s", opts.Addr) 72 if err := s.ListenAndServe(); err != http.ErrServerClosed { 73 grpclog.Errorf("Failed to listen and serve: %v", err) 74 return err 75 } 76 return nil 77 }