This repository has been archived by the owner on May 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender.go
79 lines (67 loc) · 2.08 KB
/
render.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
package detour
import (
"bytes"
"encoding/json"
"net/http"
)
func writeJSONResponse(response http.ResponseWriter, statusCode int, content interface{}, contentType, indent string) {
writeContentType(response, contentType)
serialized, err := serializeJSON(content, indent)
writeResponse(response, statusCode, serialized, err)
}
func writeContentTypeAndStatusCode(response http.ResponseWriter, statusCode int, contentType string) {
writeContentType(response, contentType)
response.WriteHeader(orOK(statusCode))
}
func writeContentType(response http.ResponseWriter, contentType string) {
if len(contentType) > 0 {
response.Header().Set(contentTypeHeader, contentType) // doesn't get written unless status code is written last!
}
}
func serializeJSON(content interface{}, indent string) ([]byte, error) {
writer := new(bytes.Buffer)
encoder := json.NewEncoder(writer)
encoder.SetIndent("", indent)
if err := encoder.Encode(content); err != nil {
return nil, err
} else {
return writer.Bytes(), nil
}
}
func writeResponse(response http.ResponseWriter, statusCode int, content []byte, previous error) {
if previous == nil {
writeContent(response, statusCode, content)
} else {
writeInternalServerError(response)
}
}
func writeContent(response http.ResponseWriter, statusCode int, content []byte) {
response.WriteHeader(orOK(statusCode))
response.Write(content)
}
func writeInternalServerError(response http.ResponseWriter) {
response.WriteHeader(http.StatusInternalServerError)
errContent := make(Errors, 0).Append(SimpleInputError("Marshal failure", "HTTP Response"))
content, _ := serializeJSON(errContent, "")
response.Write(content)
}
func orOK(statusCode int) int {
if statusCode == 0 {
return http.StatusOK
}
return statusCode
}
func firstNonBlank(values ...string) string {
for _, value := range values {
if len(value) > 0 {
return value
}
}
return ""
}
const (
contentTypeHeader = "Content-Type"
jsonContentType = "application/json; charset=utf-8"
octetStreamContentType = "application/octet-stream"
plaintextContentType = "text/plain; charset=utf-8"
)