-
Notifications
You must be signed in to change notification settings - Fork 0
/
response_handler.go
45 lines (33 loc) · 1006 Bytes
/
response_handler.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
package app
import (
"encoding/json"
"log"
"net/http"
"github.com/dmitriivoitovich/test-assignment-sliide/app/request"
"github.com/dmitriivoitovich/test-assignment-sliide/app/response"
)
func handleError(w http.ResponseWriter, req *http.Request, err error) {
status := http.StatusInternalServerError
if err == request.ErrInvalidParameterValue {
status = http.StatusBadRequest
}
w.WriteHeader(status)
logRequest(req, status, err)
}
func handleSuccess(w http.ResponseWriter, req *http.Request, resp response.Response) {
status := http.StatusOK
w.WriteHeader(status)
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(resp); err != nil {
logRequest(req, status, err)
return
}
logRequest(req, status, nil)
}
func logRequest(req *http.Request, status int, err error) {
if err != nil {
log.Printf("%s %s %d %s", req.Method, req.URL.String(), status, err.Error())
return
}
log.Printf("%s %s %d", req.Method, req.URL.String(), status)
}