-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
37 lines (30 loc) · 858 Bytes
/
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
package server
import (
"encoding/json"
"errors"
"net/http"
"github.com/go-chi/httplog"
)
type contextKey string
var (
tokenKey contextKey = "tokenKey"
)
type Handler func(w http.ResponseWriter, r *http.Request) error
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
oplog := httplog.LogEntry(r.Context())
w.Header().Set("Content-Type", "application/json")
if err := h(w, r); err != nil {
var errResponse ErrorResponse
ok := errors.As(err, &errResponse)
if !ok {
oplog.Err(err).Msg("error in ServeHTTP handler")
errResponse.Status = http.StatusInternalServerError
errResponse.Err = err
}
w.WriteHeader(errResponse.Status)
if err := json.NewEncoder(w).Encode(map[string]interface{}{"error": errResponse.Error()}); err != nil {
oplog.Err(err).Msg("unable to encode error response")
return
}
}
}