File: client.go

package info (click to toggle)
golang-github-go-kit-kit 0.13.0-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,784 kB
  • sloc: sh: 22; makefile: 11
file content (37 lines) | stat: -rw-r--r-- 998 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package proto

import (
	"bytes"
	"context"
	"errors"
	"io/ioutil"
	"net/http"

	httptransport "github.com/go-kit/kit/transport/http"
	"google.golang.org/protobuf/proto"
)

// EncodeProtoRequest is an EncodeRequestFunc that serializes the request as Protobuf.
// If the request implements Headerer, the provided headers will be applied
// to the request. If the given request does not implement proto.Message, an error will
// be returned.
func EncodeProtoRequest(_ context.Context, r *http.Request, preq interface{}) error {
	r.Header.Set("Content-Type", "application/x-protobuf")
	if headerer, ok := preq.(httptransport.Headerer); ok {
		for k := range headerer.Headers() {
			r.Header.Set(k, headerer.Headers().Get(k))
		}
	}
	req, ok := preq.(proto.Message)
	if !ok {
		return errors.New("response does not implement proto.Message")
	}

	b, err := proto.Marshal(req)
	if err != nil {
		return err
	}
	r.ContentLength = int64(len(b))
	r.Body = ioutil.NopCloser(bytes.NewReader(b))
	return nil
}