forked from topfreegames/khan
/
helpers.go
187 lines (161 loc) · 4.9 KB
/
helpers.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// khan
// https://github.com/topfreegames/khan
//
// Licensed under the MIT license:
// http://www.opensource.org/licenses/mit-license
// Copyright © 2016 Top Free Games <backend@tfgco.com>
package api
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"strings"
"github.com/spf13/viper"
"github.com/labstack/echo"
"github.com/mailru/easyjson/jlexer"
"github.com/mailru/easyjson/jwriter"
newrelic "github.com/newrelic/go-agent"
"github.com/topfreegames/khan/log"
"github.com/topfreegames/khan/models"
"github.com/uber-go/zap"
)
//EasyJSONUnmarshaler describes a struct able to unmarshal json
type EasyJSONUnmarshaler interface {
UnmarshalEasyJSON(l *jlexer.Lexer)
}
//EasyJSONMarshaler describes a struct able to marshal json
type EasyJSONMarshaler interface {
MarshalEasyJSON(w *jwriter.Writer)
}
// FailWith fails with the specified message
func FailWith(status int, message string, c echo.Context) error {
payload := map[string]interface{}{
"success": false,
"reason": message,
}
return c.JSON(status, payload)
}
// FailWithError fails with the specified error
func FailWithError(err error, c echo.Context) error {
t := reflect.TypeOf(err)
status, ok := map[string]int{
"*models.ModelNotFoundError": http.StatusNotFound,
"*models.PlayerReachedMaxInvitesError": http.StatusBadRequest,
"*models.ForbiddenError": http.StatusForbidden,
"*models.PlayerCannotPerformMembershipActionError": http.StatusForbidden,
"*models.AlreadyHasValidMembershipError": http.StatusConflict,
"*models.CannotApproveOrDenyMembershipAlreadyProcessedError": http.StatusConflict,
"*models.CannotPromoteOrDemoteMemberLevelError": http.StatusConflict,
}[t.String()]
if !ok {
status = http.StatusInternalServerError
}
return FailWith(status, err.Error(), c)
}
// SucceedWith sends payload to user with status 200
func SucceedWith(payload map[string]interface{}, c echo.Context) error {
f := func() error {
payload["success"] = true
return c.JSON(http.StatusOK, payload)
}
tx := GetTX(c)
if tx == nil {
return f()
}
segment := newrelic.StartSegment(tx, "response-marshalling")
defer segment.End()
return f()
}
//LoadJSONPayload loads the JSON payload to the given struct validating all fields are not null
func LoadJSONPayload(payloadStruct interface{}, c echo.Context, l zap.Logger) error {
log.D(l, "Loading payload...")
data, err := GetRequestBody(c)
if err != nil {
log.E(l, "Loading payload failed.", func(cm log.CM) {
cm.Write(zap.Error(err))
})
return err
}
unmarshaler, ok := payloadStruct.(EasyJSONUnmarshaler)
if !ok {
err := fmt.Errorf("Can't unmarshal specified payload since it does not implement easyjson interface")
log.E(l, "Loading payload failed.", func(cm log.CM) {
cm.Write(zap.Error(err))
})
return err
}
lexer := jlexer.Lexer{Data: []byte(data)}
unmarshaler.UnmarshalEasyJSON(&lexer)
if err = lexer.Error(); err != nil {
log.E(l, "Loading payload failed.", func(cm log.CM) {
cm.Write(zap.Error(err))
})
return err
}
if validatable, ok := payloadStruct.(Validatable); ok {
missingFieldErrors := validatable.Validate()
if len(missingFieldErrors) != 0 {
err := errors.New(strings.Join(missingFieldErrors[:], ", "))
log.E(l, "Loading payload failed.", func(cm log.CM) {
cm.Write(zap.Error(err))
})
return err
}
}
log.D(l, "Payload loaded successfully.")
return nil
}
//GetRequestBody from echo context
func GetRequestBody(c echo.Context) ([]byte, error) {
bodyCache := c.Get("requestBody")
if bodyCache != nil {
return bodyCache.([]byte), nil
}
body := c.Request().Body()
b, err := ioutil.ReadAll(body)
if err != nil {
return nil, err
}
c.Set("requestBody", b)
return b, nil
}
//GetRequestJSON as the specified interface from echo context
func GetRequestJSON(payloadStruct interface{}, c echo.Context) error {
body, err := GetRequestBody(c)
if err != nil {
return err
}
err = json.Unmarshal(body, payloadStruct)
if err != nil {
return err
}
return nil
}
//GetTX returns new relic transaction
func GetTX(c echo.Context) newrelic.Transaction {
tx := c.Get("txn")
if tx == nil {
return nil
}
return tx.(newrelic.Transaction)
}
//WithSegment adds a segment to new relic transaction
func WithSegment(name string, c echo.Context, f func() error) error {
tx := GetTX(c)
if tx == nil {
return f()
}
segment := newrelic.StartSegment(tx, name)
defer segment.End()
return f()
}
// SetRetrieveClanHandlerConfigurationDefaults sets the default configs for RetrieveClanHandler
func SetRetrieveClanHandlerConfigurationDefaults(config *viper.Viper) {
config.SetDefault(models.MaxPendingApplicationsKey, 100)
config.SetDefault(models.MaxPendingInvitesKey, 100)
config.SetDefault(models.PendingApplicationsOrderKey, models.Newest)
config.SetDefault(models.PendingInvitesOrderKey, models.Newest)
}