/protoc-gen-go-http

A HTTP transport generator for gRPC

Primary LanguageGo

Description

protoc-gen-go-http generates HTTP-wrappers for gRPC servers generated by protoc-gen-go. It is implemented as a protoc plugin.

A typical use case is when you started using gRPC but there is legacy services that still use HTTP/1.1. protoc-gen-go-http generates fast wrappers that can be used as handler functions.

Suppose you have a simple service:

syntax = "proto3";

service Example {
    // Simple request/response.
    rpc GetPerson(Query) returns (Person) {}
    // Server streaming (ignored).
    rpc ListPeople(Query) returns (stream Person) {}
}

protoc-gen-go will generate the following interface:

type ExampleServer interface {
	// Simple request/response.
	GetPerson(context.Context, *Query) (*Person, error)
	// Server streaming (ignored).
	ListPeople(*Query, Example_ListPeopleServer) error
}

Then with protoc-gen-go-http you can get your HTTP handler functions:

type HTTPExampleServer struct {
	srv ExampleServer
	cdc codec.Codec
}

func NewHTTPExampleServer(srv ExampleServer, cdc codec.Codec) *HTTPExampleServer {
	return &HTTPExampleServer{
		srv: srv,
		cdc: cdc,
	}
}

func (wpr *HTTPExampleServer) GetPerson(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	arg := Query{}
	err := wpr.cdc.ReadRequest(r.Body, &arg)
	if err != nil {
		wpr.cdc.WriteError(w, err)
		return
	}
	grpcResp, err := wpr.srv.GetPerson(r.Context(), &arg)
	if err != nil {
		wpr.cdc.WriteError(w, err)
		return
	}
	wpr.cdc.WriteResponse(w, grpcResp)
}

A codec.Codec is used to read requests and write responses/errors. You can use the codec.DefaultCodec or implement a custom one.

protoc-gen-go-http relies heavily on grpc-gateway code, but it's faster because less time is spent on marshalling/unmarshalling. grpc-gateway first unmarshals POST body, then marshals it into a protobuf blob, then unmarshals a protobuf response, etc. protoc-gen-go-http just unmarshals POST body into a "native" gRPC struct, gets response struct and marshals it.

All stream-based gRPC methods are ignored.

Installation

go get -u github.com/lazada/protoc-gen-go-http

Usage

Add --go-http_out=. as a parameter to protoc, for example:

protoc --go_out=plugins=grpc:. --go-http_out=. example.proto