...

Source file src/github.com/grpc-ecosystem/grpc-gateway/examples/internal/gateway/main.go

Documentation: github.com/grpc-ecosystem/grpc-gateway/examples/internal/gateway

     1  package gateway
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  
     7  	"github.com/golang/glog"
     8  	gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
     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  	// SwaggerDir is a path to a directory from which the server
    25  	// serves swagger specs.
    26  	SwaggerDir 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  			glog.Errorf("Failed to close a client connection to the gRPC server: %v", err)
    46  		}
    47  	}()
    48  
    49  	mux := http.NewServeMux()
    50  	mux.HandleFunc("/swagger/", swaggerServer(opts.SwaggerDir))
    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  		glog.Infof("Shutting down the http server")
    66  		if err := s.Shutdown(context.Background()); err != nil {
    67  			glog.Errorf("Failed to shutdown http server: %v", err)
    68  		}
    69  	}()
    70  
    71  	glog.Infof("Starting listening at %s", opts.Addr)
    72  	if err := s.ListenAndServe(); err != http.ErrServerClosed {
    73  		glog.Errorf("Failed to listen and serve: %v", err)
    74  		return err
    75  	}
    76  	return nil
    77  }
    78  

View as plain text