-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
40 lines (33 loc) · 1.05 KB
/
utils.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
package handler
import (
"encoding/json"
"errors"
"net/http"
"github.com/dragonator/rental-service/module/rental/internal/http/contract"
"github.com/dragonator/rental-service/module/rental/internal/http/service/svc"
)
const (
_contentTypeHeaderName = "Content-Type"
_contentTypeJSON = "application/json"
_xContentTypeOptions = "X-Content-Type-Options"
_noSniff = "nosniff"
)
func errorResponse(w http.ResponseWriter, err error) {
er := &contract.ErrorResponse{Message: err.Error()}
w.Header().Set(_contentTypeHeaderName, _contentTypeJSON)
w.Header().Set(_xContentTypeOptions, _noSniff)
var e *svc.Error
if errors.As(err, &e) {
w.WriteHeader(e.StatusCode)
json.NewEncoder(w).Encode(er)
return
}
w.WriteHeader(http.StatusInternalServerError)
er.Message = http.StatusText(http.StatusInternalServerError)
json.NewEncoder(w).Encode(er)
}
func successResponse(w http.ResponseWriter, resp interface{}) {
w.Header().Set(_contentTypeHeaderName, _contentTypeJSON)
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(resp)
}