...

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

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

     1  package gateway
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"google.golang.org/grpc/credentials/insecure"
     7  	"net"
     8  	"net/http"
     9  
    10  	"github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/proto/examplepb"
    11  	standalone "github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/proto/standalone"
    12  	gwruntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
    13  	_ "google.golang.org/genproto/googleapis/rpc/errdetails"
    14  	"google.golang.org/grpc"
    15  )
    16  
    17  // newGateway returns a new gateway server which translates HTTP into gRPC.
    18  func newGateway(ctx context.Context, conn *grpc.ClientConn, opts []gwruntime.ServeMuxOption) (http.Handler, error) {
    19  
    20  	mux := gwruntime.NewServeMux(opts...)
    21  
    22  	for _, f := range []func(context.Context, *gwruntime.ServeMux, *grpc.ClientConn) error{
    23  		examplepb.RegisterEchoServiceHandler,
    24  		standalone.RegisterUnannotatedEchoServiceHandler,
    25  		examplepb.RegisterStreamServiceHandler,
    26  		examplepb.RegisterABitOfEverythingServiceHandler,
    27  		examplepb.RegisterFlowCombinationHandler,
    28  		examplepb.RegisterNonStandardServiceHandler,
    29  		examplepb.RegisterResponseBodyServiceHandler,
    30  	} {
    31  		if err := f(ctx, mux, conn); err != nil {
    32  			return nil, err
    33  		}
    34  	}
    35  	return mux, nil
    36  }
    37  
    38  func dial(ctx context.Context, network, addr string) (*grpc.ClientConn, error) {
    39  	switch network {
    40  	case "tcp":
    41  		return dialTCP(ctx, addr)
    42  	case "unix":
    43  		return dialUnix(ctx, addr)
    44  	default:
    45  		return nil, fmt.Errorf("unsupported network type %q", network)
    46  	}
    47  }
    48  
    49  // dialTCP creates a client connection via TCP.
    50  // "addr" must be a valid TCP address with a port number.
    51  func dialTCP(ctx context.Context, addr string) (*grpc.ClientConn, error) {
    52  	return grpc.DialContext(ctx, addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
    53  }
    54  
    55  // dialUnix creates a client connection via a unix domain socket.
    56  // "addr" must be a valid path to the socket.
    57  func dialUnix(ctx context.Context, addr string) (*grpc.ClientConn, error) {
    58  	d := func(ctx context.Context, addr string) (net.Conn, error) {
    59  		return (&net.Dialer{}).DialContext(ctx, "unix", addr)
    60  	}
    61  	return grpc.DialContext(ctx, addr, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(d))
    62  }
    63  

View as plain text