-
Notifications
You must be signed in to change notification settings - Fork 0
/
communicator.go
94 lines (77 loc) · 1.83 KB
/
communicator.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
84
85
86
87
88
89
90
91
92
93
94
// Package communicator is a system for reading and writing to http responses
package communicator
import (
"encoding/json"
"fmt"
"net/http"
)
func New(w http.ResponseWriter) *Communicator {
return NewCommunicatorWithCtx(w, nil)
}
func NewCommunicatorWithCtx(w http.ResponseWriter, ctx interface{}) *Communicator {
return &Communicator{
e: json.NewEncoder(w),
w: w,
context: ctx,
}
}
type Communicator struct {
e *json.Encoder
w http.ResponseWriter
context interface{}
}
func (c *Communicator) With(d interface{}) *Communicator {
return NewCommunicatorWithCtx(c.w, d)
}
func (c *Communicator) OKf(form string, s ...interface{}) {
c.OK(fmt.Sprintf(form, s...))
}
func (c *Communicator) OK(s ...interface{}) {
c.write(response{
Message: format(s...),
Error: false,
Code: http.StatusOK,
Data: c.context,
})
}
func (c *Communicator) Failf(form string, s ...interface{}) {
c.Fail(fmt.Sprintf(form, s...))
}
func (c *Communicator) Fail(s ...interface{}) {
c.write(response{
Message: format(s...),
Error: true,
Code: http.StatusConflict,
Data: c.context,
})
}
func (c *Communicator) Errorf(form string, s ...interface{}) {
c.Error(fmt.Sprintf(form, s...))
}
func (c *Communicator) Error(s ...interface{}) {
c.write(response{
Message: format(s...),
Error: true,
Code: http.StatusInternalServerError,
Data: c.context,
})
}
func (c *Communicator) write(r response) {
c.w.WriteHeader(r.Code)
if err := c.e.Encode(r); err != nil {
c.e.Encode("Error encoding data")
}
}
type response struct {
Message string `json:"message"`
Error bool `json:"error"`
Code int `json:"code"`
Data interface{} `json:"data"`
}
func format(s ...interface{}) string {
var message string
if len(s) != 0 {
message = fmt.Sprint(s...)
}
return message
}