forked from nytimes/marvin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
83 lines (68 loc) · 2.44 KB
/
response.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package marvin
import (
"encoding/json"
"net/http"
"github.com/golang/protobuf/proto"
)
// NewProtoStatusResponse allows users to respond with a specific HTTP status code and
// a Protobuf or JSON serialized response.
func NewProtoStatusResponse(res proto.Message, code int) *ProtoStatusResponse {
return &ProtoStatusResponse{res: res, code: code}
}
// ProtoStatusResponse implements:
// `httptransport.StatusCoder` to allow users to respond with the given
// response with a non-200 status code.
// `proto.Marshaler` and proto.Message so it can wrap a proto Endpoint responses.
// `json.Marshaler` so it can wrap JSON Endpoint responses.
// `error` so it can be used to respond as an error within the go-kit stack.
type ProtoStatusResponse struct {
code int
res proto.Message
}
// to implement httptransport.StatusCoder
func (c *ProtoStatusResponse) StatusCode() int {
return c.code
}
// to implement proto.Marshaler
func (c *ProtoStatusResponse) Marshal() ([]byte, error) {
return proto.Marshal(c.res)
}
// to implement proto.Message
func (c *ProtoStatusResponse) Reset() { c.res.Reset() }
func (c *ProtoStatusResponse) String() string { return c.res.String() }
func (c *ProtoStatusResponse) ProtoMessage() { c.res.ProtoMessage() }
// to implement json.Marshaler
func (c *ProtoStatusResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(c.res)
}
var _ proto.Marshaler = &ProtoStatusResponse{}
// to implement error
func (c *ProtoStatusResponse) Error() string {
return http.StatusText(c.code)
}
// NewJSONStatusResponse allows users to respond with a specific HTTP status code and
// a JSON serialized response.
func NewJSONStatusResponse(res interface{}, code int) *JSONStatusResponse {
return &JSONStatusResponse{res: res, code: code}
}
// JSONStatusResponse implements:
// `httptransport.StatusCoder` to allow users to respond with the given
// response with a non-200 status code.
// `json.Marshaler` so it can wrap JSON Endpoint responses.
// `error` so it can be used to respond as an error within the go-kit stack.
type JSONStatusResponse struct {
code int
res interface{}
}
// StatusCode is to implement httptransport.StatusCoder
func (c *JSONStatusResponse) StatusCode() int {
return c.code
}
// MarshalJSON is to implement json.Marshaler
func (c *JSONStatusResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(c.res)
}
// Error is to implement error
func (c *JSONStatusResponse) Error() string {
return http.StatusText(c.code)
}