-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
48 lines (35 loc) · 976 Bytes
/
http.go
File metadata and controls
48 lines (35 loc) · 976 Bytes
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
package basehttp
import (
"encoding/json"
"net/http"
)
type Response struct {
Data interface{} `json:"data,omitempty"`
Error string `json:"error,omitempty"`
}
// httpError is a helper to tidy up setting a HTTP error for a JSON response
func httpError(w http.ResponseWriter, statusCode int, err error) {
setHeaderJSON(w, statusCode)
if err == nil {
return
}
response := Response{
Error: err.Error(),
}
json.NewEncoder(w).Encode(response)
}
// httpData is a helper to tidy up setting a HTTP OK reponse with data
func httpData(w http.ResponseWriter, statusCode int, data interface{}) {
setHeaderJSON(w, statusCode)
response := Response{
Data: data,
}
json.NewEncoder(w).Encode(response)
}
func setHeader(w http.ResponseWriter, contentType string, statusCode int) {
w.Header().Set("Content-Type", contentType)
w.WriteHeader(statusCode)
}
func setHeaderJSON(w http.ResponseWriter, statusCode int) {
setHeader(w, "text/json", statusCode)
}