Run starts a HTTP server and blocks while running if successful. The server will be shutdown when "ctx" is canceled.
(ctx context.Context, opts Options)
| 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(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 | // Do not use logRequestBody for ExcessBodyServer because it will perform |
| 60 | // io.ReadAll and mask the issue: |
| 61 | // https://github.com/grpc-ecosystem/grpc-gateway/issues/5236 |
| 62 | hmux := http.NewServeMux() |
| 63 | hmux.Handle("/rpc/excess-body/", allowCORS(mux)) |
| 64 | hmux.Handle("/", logRequestBody(allowCORS(mux))) |
| 65 | |
| 66 | s := &http.Server{ |
| 67 | Addr: opts.Addr, |
| 68 | Handler: hmux, |
| 69 | } |
| 70 | go func() { |
| 71 | <-ctx.Done() |
| 72 | grpclog.Infof("Shutting down the http server") |
| 73 | if err := s.Shutdown(context.Background()); err != nil { |
| 74 | grpclog.Errorf("Failed to shutdown http server: %v", err) |
| 75 | } |
| 76 | }() |
| 77 | |
| 78 | grpclog.Infof("Starting listening at %s", opts.Addr) |
| 79 | if err := s.ListenAndServe(); err != http.ErrServerClosed { |
| 80 | grpclog.Errorf("Failed to listen and serve: %v", err) |
| 81 | return err |
| 82 | } |
| 83 | return nil |
| 84 | } |