-
Notifications
You must be signed in to change notification settings - Fork 10
/
control.go
256 lines (219 loc) · 6.3 KB
/
control.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
// Copyright 2015 Igor Dolzhikov. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package router
import (
"compress/gzip"
"context"
"encoding/json"
"net/http"
"strings"
"time"
)
// Default content types
const (
// MIMEJSON - "Content-type" for JSON
MIMEJSON = "application/json"
// MIMETEXT - "Content-type" for TEXT
MIMETEXT = "text/plain"
)
// Control allows us to pass variables between middleware,
// assign Http codes and render a Body.
type Control struct {
// Context embedded
context.Context
// Request is an adapter which allows the usage of a http.Request as standard request
Request *http.Request
// Writer is an adapter which allows the usage of a http.ResponseWriter as standard writer
Writer http.ResponseWriter
// User content type
ContentType string
// Code of HTTP status
code int
// compactJSON propery defines JSON output format (default is not compact)
compactJSON bool
// if used, json header shows meta data
useMetaData bool
// header with metadata
header Header
// errors
errorHeader ErrorHeader
// params is set of key/value parameters
params []Param
// timer used to calculate a elapsed time for handler and writing it in a response
timer time.Time
}
// Param is a URL parameter which represents as key and value.
type Param struct {
Key string `json:"key,omitempty"`
Value string `json:"value,omitempty"`
}
// Header is used to prepare a JSON header with meta data
type Header struct {
Duration time.Duration `json:"duration,omitempty"`
Took string `json:"took,omitempty"`
APIVersion string `json:"apiVersion,omitempty"`
Context string `json:"context,omitempty"`
ID string `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params interface{} `json:"params,omitempty"`
Data interface{} `json:"data,omitempty"`
Error interface{} `json:"error,omitempty"`
}
// ErrorHeader contains error code, message and array of specified error reports
type ErrorHeader struct {
Code uint16 `json:"code,omitempty"`
Message string `json:"message,omitempty"`
Errors []Error `json:"errors,omitempty"`
}
// Error report format
type Error struct {
Domain string `json:"domain,omitempty"`
Reason string `json:"reason,omitempty"`
Message string `json:"message,omitempty"`
Location string `json:"location,omitempty"`
LocationType string `json:"locationType,omitempty"`
ExtendedHelp string `json:"extendedHelp,omitempty"`
SendReport string `json:"sendReport,omitempty"`
}
// Get returns the first value associated with the given name.
// If there are no values associated with the key, an empty string is returned.
func (c *Control) Get(name string) string {
for idx := range c.params {
if c.params[idx].Key == name {
return c.params[idx].Value
}
}
return c.Request.URL.Query().Get(name)
}
// Set adds new parameters which represents as set of key/value.
func (c *Control) Set(params ...Param) *Control {
c.params = append(c.params, params...)
return c
}
// Code assigns http status code, which returns on http request
func (c *Control) Code(code int) *Control {
if code >= 200 && code < 600 {
c.code = code
}
return c
}
// GetCode returns status code
func (c *Control) GetCode() int {
return c.code
}
// CompactJSON changes JSON output format (default mode is false)
func (c *Control) CompactJSON(mode bool) *Control {
c.compactJSON = mode
return c
}
// UseMetaData shows meta data in JSON Header
func (c *Control) UseMetaData() *Control {
c.useMetaData = true
return c
}
// APIVersion adds API version meta data
func (c *Control) APIVersion(version string) *Control {
c.useMetaData = true
c.header.APIVersion = version
return c
}
// HeaderContext adds context meta data
func (c *Control) HeaderContext(context string) *Control {
c.useMetaData = true
c.header.Context = context
return c
}
// ID adds id meta data
func (c *Control) ID(id string) *Control {
c.useMetaData = true
c.header.ID = id
return c
}
// Method adds method meta data
func (c *Control) Method(method string) *Control {
c.useMetaData = true
c.header.Method = method
return c
}
// SetParams adds params meta data in alternative format
func (c *Control) SetParams(params interface{}) *Control {
c.useMetaData = true
c.header.Params = params
return c
}
// SetError sets error code and error message
func (c *Control) SetError(code uint16, message string) *Control {
c.useMetaData = true
c.errorHeader.Code = code
c.errorHeader.Message = message
return c
}
// AddError adds new error
func (c *Control) AddError(errors ...Error) *Control {
c.useMetaData = true
c.errorHeader.Errors = append(c.errorHeader.Errors, errors...)
return c
}
// UseTimer allows caalculate elapsed time of request handling
func (c *Control) UseTimer() {
c.useMetaData = true
c.timer = time.Now()
}
// GetTimer returns timer state
func (c *Control) GetTimer() time.Time {
return c.timer
}
// Body renders the given data into the response body
func (c *Control) Body(data interface{}) {
var content []byte
if str, ok := data.(string); ok {
content = []byte(str)
if c.ContentType != "" {
c.Writer.Header().Add("Content-type", c.ContentType)
} else {
c.Writer.Header().Add("Content-type", MIMETEXT)
}
} else {
if c.useMetaData {
c.header.Data = data
if !c.timer.IsZero() {
took := time.Now()
c.header.Duration = took.Sub(c.timer)
c.header.Took = took.Sub(c.timer).String()
}
if c.header.Params == nil && len(c.params) > 0 {
c.header.Params = c.params
}
if c.errorHeader.Code != 0 || c.errorHeader.Message != "" || len(c.errorHeader.Errors) > 0 {
c.header.Error = c.errorHeader
}
data = c.header
}
var err error
if c.compactJSON {
content, err = json.Marshal(data)
} else {
content, err = json.MarshalIndent(data, "", " ")
}
if err != nil {
c.Writer.WriteHeader(http.StatusInternalServerError)
return
}
c.Writer.Header().Add("Content-type", MIMEJSON)
}
if strings.Contains(c.Request.Header.Get("Accept-Encoding"), "gzip") {
c.Writer.Header().Add("Content-Encoding", "gzip")
if c.code > 0 {
c.Writer.WriteHeader(c.code)
}
gz := gzip.NewWriter(c.Writer)
gz.Write(content)
gz.Close()
} else {
if c.code > 0 {
c.Writer.WriteHeader(c.code)
}
c.Writer.Write(content)
}
}