...

Text file src/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/usage.md

Documentation: github.com/grpc-ecosystem/grpc-gateway/docs/_docs

     1---
     2category: documentation
     3---
     4
     5# How do I use this?
     6
     7## Installation
     8First, you need to install ProtocolBuffers 3.0.0-beta-3 or later.
     9
    10```sh
    11mkdir tmp
    12cd tmp
    13git clone https://github.com/google/protobuf
    14cd protobuf
    15./autogen.sh
    16./configure
    17make
    18make check
    19sudo make install
    20```
    21
    22Then, `go get -u` as usual the following packages:
    23
    24```sh
    25go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
    26go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
    27go get -u github.com/golang/protobuf/protoc-gen-go
    28```
    29 
    30## Usage
    31Make sure that your `$GOPATH/bin` is in your `$PATH`.
    32
    331. Define your service in gRPC
    34   
    35   your_service.proto:
    36   ```protobuf
    37   syntax = "proto3";
    38   package example;
    39   message StringMessage {
    40     string value = 1;
    41   }
    42   
    43   service YourService {
    44     rpc Echo(StringMessage) returns (StringMessage) {}
    45   }
    46   ```
    472. Add a [custom option](https://cloud.google.com/service-management/reference/rpc/google.api#http) to the .proto file
    48   
    49   your_service.proto:
    50   ```diff
    51    syntax = "proto3";
    52    package example;
    53   +
    54   +import "google/api/annotations.proto";
    55   +
    56    message StringMessage {
    57      string value = 1;
    58    }
    59    
    60    service YourService {
    61   -  rpc Echo(StringMessage) returns (StringMessage) {}
    62   +  rpc Echo(StringMessage) returns (StringMessage) {
    63   +    option (google.api.http) = {
    64   +      post: "/v1/example/echo"
    65   +      body: "*"
    66   +    };
    67   +  }
    68    }
    69   ```
    70
    71   See [a_bit_of_everything.proto](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/internal/proto/examplepb/a_bit_of_everything.proto)
    72   for examples of more annotations you can add to customize gateway behavior
    73   and generated Swagger output.
    74
    75   If you do not want to modify the proto file for use with grpc-gateway you can alternatively use an external [gRPC API Configuration](https://cloud.google.com/endpoints/docs/grpc/grpc-service-config) file. [Check our documentation](grpcapiconfiguration.html) for more information.
    76
    773. Generate gRPC stub
    78   
    79   ```sh
    80   protoc -I/usr/local/include -I. \
    81     -I$GOPATH/src \
    82     -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
    83     --go_out=plugins=grpc:. \
    84     path/to/your_service.proto
    85   ```
    86   
    87   It will generate a stub file `path/to/your_service.pb.go`.
    884. Implement your service in gRPC as usual
    89   1. (Optional) Generate gRPC stub in the language you want.
    90     
    91     e.g.
    92     ```sh
    93     protoc -I/usr/local/include -I. \
    94       -I$GOPATH/src \
    95       -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
    96       --ruby_out=. \
    97       path/to/your/service_proto
    98     
    99     protoc -I/usr/local/include -I. \
   100       -I$GOPATH/src \
   101       -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
   102       --plugin=protoc-gen-grpc=grpc_ruby_plugin \
   103       --grpc-ruby_out=. \
   104       path/to/your/service.proto
   105     ```
   106   2. Add the googleapis-common-protos gem (or your language equivalent) as a dependency to your project.
   107   3. Implement your service
   108   
   1095. Generate reverse-proxy
   110   
   111   ```sh
   112   protoc -I/usr/local/include -I. \
   113     -I$GOPATH/src \
   114     -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
   115     --grpc-gateway_out=logtostderr=true:. \
   116     path/to/your_service.proto
   117   ```
   118   
   119   It will generate a reverse proxy `path/to/your_service.pb.gw.go`.
   120
   121   Note: After generating the code for each of the stubs, to build the code, you will want to run ```go get .``` from the directory containing the stubs.
   122
   1236. Write an entry point
   124   
   125   Now you need to write an entry point of the proxy server.
   126   ```go
   127   package main
   128
   129   import (
   130     "flag"
   131     "net/http"
   132   
   133     "github.com/golang/glog"
   134     "golang.org/x/net/context"
   135     "github.com/grpc-ecosystem/grpc-gateway/runtime"
   136     "google.golang.org/grpc"
   137   	
   138     gw "path/to/your_service_package"
   139   )
   140   
   141   var (
   142     echoEndpoint = flag.String("echo_endpoint", "localhost:9090", "endpoint of YourService")
   143   )
   144   
   145   func run() error {
   146     ctx := context.Background()
   147     ctx, cancel := context.WithCancel(ctx)
   148     defer cancel()
   149   
   150     mux := runtime.NewServeMux()
   151     opts := []grpc.DialOption{grpc.WithInsecure()}
   152     err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, *echoEndpoint, opts)
   153     if err != nil {
   154       return err
   155     }
   156   
   157     return http.ListenAndServe(":8080", mux)
   158   }
   159   
   160   func main() {
   161     flag.Parse()
   162     defer glog.Flush()
   163   
   164     if err := run(); err != nil {
   165       glog.Fatal(err)
   166     }
   167   }
   168   ```
   169
   1707. (Optional) Generate swagger definitions
   171
   172   ```sh
   173   protoc -I/usr/local/include -I. \
   174     -I$GOPATH/src \
   175     -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
   176     --swagger_out=logtostderr=true:. \
   177     path/to/your_service.proto
   178   ```
   179
   180## Parameters and flags
   181
   182During code generation with `protoc`, flags to grpc-gateway tools must be passed
   183through protoc using the `--<tool_suffix>_out=<flags>:<path>` pattern, for
   184example:
   185
   186```sh
   187--grpc-gateway_out=logtostderr=true,repeated_path_param_separator=ssv:.
   188--swagger_out=logtostderr=true,repeated_path_param_separator=ssv:.
   189```
   190
   191`protoc-gen-grpc-gateway` supports custom mapping from Protobuf `import` to Golang import path.
   192They are compatible with [the parameters with the same names in `protoc-gen-go`](https://github.com/golang/protobuf#parameters).
   193
   194Besides we also support the `request_context` parameter to use the `http.Request`'s Context (only for Go 1.7 and above).
   195This parameter can be useful to pass the request-scoped context between the gateway and the gRPC service.
   196
   197`protoc-gen-grpc-gateway` also supports some more command line flags to control logging. You can give these flags together with the parameters above. Run `protoc-gen-grpc-gateway --help` for more details about the flags.
   198
   199Similarly, `protoc-gen-swagger` supports command-line flags to control Swagger
   200output (for example, `json_names_for_fields` to output JSON names for fields
   201instead of protobuf names). Run `protoc-gen-swagger --help` for more flag
   202details. Further Swagger customization is possible by annotating your `.proto`
   203files with options from
   204[openapiv2.proto](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/protoc-gen-swagger/options/openapiv2.proto) - see
   205[a_bit_of_everything.proto](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/internal/proto/examplepb/a_bit_of_everything.proto)
   206for examples.
   207
   208# Mapping gRPC to HTTP
   209
   210* [How gRPC error codes map to HTTP status codes in the response](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/runtime/errors.go#L15)
   211* HTTP request source IP is added as `X-Forwarded-For` gRPC request header
   212* HTTP request-host is added as `X-Forwarded-Host` gRPC request header
   213* HTTP `Authorization` header is added as `authorization` gRPC request header
   214* Remaining Permanent HTTP header keys (as specified by the IANA [here](http://www.iana.org/assignments/message-headers/message-headers.xhtml) are prefixed with `grpcgateway-` and added with their values to gRPC request header
   215* HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata (after removing prefix 'Grpc-Metadata-')
   216* While configurable, the default {un,}marshaling uses [jsonpb](https://godoc.org/github.com/golang/protobuf/jsonpb) with `OrigName: true`.

View as plain text