-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
56 lines (47 loc) · 1.46 KB
/
response.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
package ctx
import (
"encoding/json"
"fmt"
"net/http"
)
func Success(rw http.ResponseWriter, statusCode int, response interface{}) error {
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(statusCode)
jsonResponse, err := json.Marshal(response)
if err != nil {
return err
}
rw.Write(jsonResponse)
return nil
}
func Errorf(rw http.ResponseWriter, statusCode int, message string, args ...interface{}) error {
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(statusCode)
response := map[string]string{
"error": fmt.Sprintf(message, args...),
}
jsonResponse, err := json.Marshal(response)
if err != nil {
return err
}
rw.Write(jsonResponse)
return nil
}
func OK(rw http.ResponseWriter, response interface{}) error {
return Success(rw, http.StatusOK, response)
}
func Created(rw http.ResponseWriter, response interface{}) error {
return Success(rw, http.StatusCreated, response)
}
func NoContent(rw http.ResponseWriter) error {
return Success(rw, http.StatusNoContent, "")
}
func BadRequest(rw http.ResponseWriter, message string, args ...interface{}) error {
return Errorf(rw, http.StatusBadRequest, message, args...)
}
func InternalServerError(rw http.ResponseWriter, message string, args ...interface{}) error {
return Errorf(rw, http.StatusInternalServerError, message, args...)
}
func NotFound(rw http.ResponseWriter, message string, args ...interface{}) error {
return Errorf(rw, http.StatusNotFound, message, args...)
}