/
encoder.go
58 lines (49 loc) · 1.67 KB
/
encoder.go
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package encoding
import (
"bytes"
"context"
"io"
"io/ioutil"
"net/http"
httptransport "github.com/go-kit/kit/transport/http"
)
// Encoder is anything that, given an interface, can store an encoding of the
// structure passed into Encode.
type Encoder interface {
// Encode takes an interface, and should be able to translate it within the
// given encoding, or it will fail with an error.
Encode(interface{}) error
}
// GenerateEncoder is a function which takes an io.Writer, and returns an
// Encoder
type GenerateEncoder func(w io.Writer) Encoder
// MakeRequestEncoder takes a GenerateEncoder and returns an
// httptransport.EncodeRequestFunc
func MakeRequestEncoder(gen GenerateEncoder) httptransport.EncodeRequestFunc {
return func(ctx context.Context, r *http.Request, request interface{}) error {
var buf bytes.Buffer
err := gen(&buf).Encode(request)
r.Body = ioutil.NopCloser(&buf)
return err
}
}
// MakeResponseEncoder takes a GenerateEncoder and returns an
// httpstransport.EncodeResponseFunc
func MakeResponseEncoder(gen GenerateEncoder) httptransport.EncodeResponseFunc {
return func(ctx context.Context, w http.ResponseWriter, response interface{}) error {
if e, ok := response.(error); ok {
// we have an error, we'll wrap it, to ensure it's transmission
// encode-ability
we := WrapError(e)
return gen(w).Encode(we)
}
return gen(w).Encode(response)
}
}
// MakeErrorEncoder will take a generic GenerateEncoder function and will
// return an ErrorEncoder
func MakeErrorEncoder(gen RequestResponseEncoding) httptransport.ErrorEncoder {
return func(ctx context.Context, err error, w http.ResponseWriter) {
gen.EncodeResponse()(ctx, w, err)
}
}