-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
66 lines (54 loc) · 1.38 KB
/
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package http
import (
"context"
"encoding/json"
"errors"
"net/http"
"github.com/bhankey/pharmacy-automatization/internal/apperror"
"github.com/bhankey/pharmacy-automatization/internal/delivery/http/v1/models"
"github.com/bhankey/pharmacy-automatization/internal/entities"
"github.com/bhankey/pharmacy-automatization/pkg/logger"
"github.com/sirupsen/logrus"
)
type BaseHandler struct {
Logger logger.Logger
}
func NewHandler(l logger.Logger) *BaseHandler {
h := &BaseHandler{
Logger: l,
}
return h
}
func (h *BaseHandler) WriteErrorResponse(ctx context.Context, w http.ResponseWriter, err error) {
h.Logger.WithFields(logrus.Fields{
"error": err,
"request_id": ctx.Value(entities.RequestID),
}).Errorf("response.error")
var resp models.BaseResponse
var clientError apperror.ClientError
if errors.As(err, &clientError) {
w.WriteHeader(clientError.Code)
resp = models.BaseResponse{
Error: clientError.Message,
Success: false,
}
} else {
w.WriteHeader(http.StatusInternalServerError)
resp = models.BaseResponse{
Error: "Something went wrong",
Success: false,
}
}
err = json.NewEncoder(w).Encode(resp)
if err != nil {
return
}
}
func WriteResponse(w http.ResponseWriter, resp interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
err := json.NewEncoder(w).Encode(resp)
if err != nil {
return
}
}