This repository was archived by the owner on May 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathresponse_functions.go
More file actions
51 lines (42 loc) · 1.5 KB
/
response_functions.go
File metadata and controls
51 lines (42 loc) · 1.5 KB
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
package httpx
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httputil"
)
func WriteResult(response http.ResponseWriter, statusCode int) {
WriteErrorMessage(response, http.StatusText(statusCode), statusCode)
}
func WriteResponse(response http.ResponseWriter, err error) {
if err != nil {
WriteError(response, err, http.StatusInternalServerError)
} else {
response.Header().Set(ContentTypeHeader, MIMEApplicationJSON)
}
}
func WriteError(response http.ResponseWriter, err error, statusCode int) {
WriteErrorMessage(response, err.Error(), statusCode)
}
func WriteErrorMessage(response http.ResponseWriter, message string, statusCode int) {
http.Error(response, message, statusCode)
}
func WriteRequest(response http.ResponseWriter, request *http.Request, message string, status int) {
dump, _ := httputil.DumpRequest(request, false)
http.Error(response, fmt.Sprintf("%d %s\n\nRaw Request:\n\n%s", status, message, string(dump)), status)
}
func WriteJSON(contents interface{}, response http.ResponseWriter) {
response.Header().Set(ContentTypeHeader, MIMEApplicationJSON)
json.NewEncoder(response).Encode(contents)
}
func WritePrettyJSON(contents interface{}, response http.ResponseWriter) {
response.Header().Set(ContentTypeHeader, MIMEApplicationJSON)
encoder := json.NewEncoder(response)
encoder.SetIndent("", "\t")
encoder.Encode(contents)
}
const (
ContentTypeHeader = "Content-Type"
MIMEApplicationJSON = "application/json; charset=utf-8"
MIMETextPlain = "text/plain; charset=utf-8"
)