...

Source file src/github.com/go-kit/kit/transport/http/proto/server.go

Documentation: github.com/go-kit/kit/transport/http/proto

     1  package proto
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"net/http"
     7  
     8  	httptransport "github.com/go-kit/kit/transport/http"
     9  	"google.golang.org/protobuf/proto"
    10  )
    11  
    12  // EncodeProtoResponse is an EncodeResponseFunc that serializes the response as Protobuf.
    13  // Many Proto-over-HTTP services can use it as a sensible default. If the response
    14  // implements Headerer, the provided headers will be applied to the response. If the
    15  // response implements StatusCoder, the provided StatusCode will be used instead of 200.
    16  func EncodeProtoResponse(ctx context.Context, w http.ResponseWriter, pres interface{}) error {
    17  	res, ok := pres.(proto.Message)
    18  	if !ok {
    19  		return errors.New("response does not implement proto.Message")
    20  	}
    21  	w.Header().Set("Content-Type", "application/x-protobuf")
    22  	if headerer, ok := w.(httptransport.Headerer); ok {
    23  		for k := range headerer.Headers() {
    24  			w.Header().Set(k, headerer.Headers().Get(k))
    25  		}
    26  	}
    27  	code := http.StatusOK
    28  	if sc, ok := pres.(httptransport.StatusCoder); ok {
    29  		code = sc.StatusCode()
    30  	}
    31  	w.WriteHeader(code)
    32  	if code == http.StatusNoContent {
    33  		return nil
    34  	}
    35  	if res == nil {
    36  		return nil
    37  	}
    38  	b, err := proto.Marshal(res)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	_, err = w.Write(b)
    43  	if err != nil {
    44  		return err
    45  	}
    46  	return nil
    47  }
    48  

View as plain text