...
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
13
14
15
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