-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponses.go
69 lines (58 loc) · 1.63 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 gotnet
import (
"encoding/json"
"net/http"
)
//Ok : HTTP 200 response
func Ok(w http.ResponseWriter, d interface{}) {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(d)
}
//Created : HTTP 201 response
func Created(w http.ResponseWriter, d interface{}, url string) {
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(d)
}
//Accepted : HTTP 202 Accepted
func Accepted(w http.ResponseWriter) {
w.WriteHeader(http.StatusAccepted)
}
//NoContent : HTTP 204 response
func NoContent(w http.ResponseWriter) {
w.WriteHeader(http.StatusNoContent)
w.Write([]byte{})
}
//BadRequest : HTTP 400 response
func BadRequest(w http.ResponseWriter, d interface{}) {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(d)
}
//Unauthorized : HTTP 401
func Unauthorized(w http.ResponseWriter, d interface{}) {
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(d)
}
//Forbidden : HTTP 403 response
func Forbidden(w http.ResponseWriter) {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte(`{"message" : "access denied"}`))
}
//NotFound : HTTP 404 response
func NotFound(w http.ResponseWriter, d interface{}) {
w.WriteHeader(http.StatusNotFound)
if d == nil {
w.Write([]byte(`{"message" : "requested data is not found"}`))
} else {
json.NewEncoder(w).Encode(d)
}
}
//PreconditionFailed : HTTP 412
func PreconditionFailed(w http.ResponseWriter, d interface{}) {
w.WriteHeader(http.StatusPreconditionFailed)
json.NewEncoder(w).Encode(d)
}
//Response : HTTP response with status code
func Response(w http.ResponseWriter, statusCode int, d interface{}) {
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(d)
}