-
Notifications
You must be signed in to change notification settings - Fork 1
/
responses.go
69 lines (54 loc) · 1.73 KB
/
responses.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
package main
import (
"encoding/json"
"net/http"
)
type apiResponse interface {
WriteResponse(http.ResponseWriter)
}
type genericErrorResponse struct {
Code int
Message string
}
func (r genericErrorResponse) WriteResponse(w http.ResponseWriter) {
msg := make(map[string]string)
msg["status"] = "error"
msg["message"] = r.Message
writeJsonResponse(w, msg, r.Code)
}
func writeJsonResponse(w http.ResponseWriter, body interface{}, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
content, _ := json.MarshalIndent(body, "", " ")
w.Write(content)
}
func notFoundResponse() genericErrorResponse {
return genericErrorResponse{http.StatusNotFound, "Not found"}
}
func forbiddenResponse() genericErrorResponse {
return genericErrorResponse{http.StatusForbidden, "Forbidden"}
}
func internalServerError() genericErrorResponse {
return genericErrorResponse{http.StatusInternalServerError, "Internal Server Error"}
}
func badRequestResponse(message string) genericErrorResponse {
return genericErrorResponse{http.StatusBadRequest, message}
}
func invalidDataResponse(message string) genericErrorResponse {
return genericErrorResponse{http.StatusUnprocessableEntity, message}
}
func conflictResponse(message string) genericErrorResponse {
return genericErrorResponse{http.StatusConflict, message}
}
type methodNotAllowedResponse struct {
allow string
}
func (r methodNotAllowedResponse) WriteResponse(w http.ResponseWriter) {
w.Header().Set("Allow", r.allow)
genericErrorResponse{http.StatusMethodNotAllowed, "Method not allowed"}.WriteResponse(w)
}
type noContentResponse struct {
}
func (r noContentResponse) WriteResponse(w http.ResponseWriter) {
w.WriteHeader(http.StatusNoContent)
}