Archived
2
0
This repository has been archived on 2024-06-24. You can view files and clone it, but cannot push or open issues or pull requests.
neko-custom/server/internal/http/endpoint/endpoint.go

103 lines
2.2 KiB
Go
Raw Normal View History

2020-01-13 21:05:38 +13:00
package endpoint
import (
2020-01-19 12:30:09 +13:00
"encoding/json"
"fmt"
"net/http"
"runtime/debug"
2020-01-13 21:05:38 +13:00
2020-01-19 12:30:09 +13:00
"github.com/go-chi/chi/middleware"
"github.com/rs/zerolog/log"
2020-01-13 21:05:38 +13:00
)
type (
2020-01-19 12:30:09 +13:00
Endpoint func(http.ResponseWriter, *http.Request) error
ErrResponse struct {
Status int `json:"status,omitempty"`
Err string `json:"error,omitempty"`
Message string `json:"message,omitempty"`
Details string `json:"details,omitempty"`
Code string `json:"code,omitempty"`
RequestID string `json:"request,omitempty"`
}
2020-01-13 21:05:38 +13:00
)
func Handle(handler Endpoint) http.HandlerFunc {
2020-01-19 12:30:09 +13:00
fn := func(w http.ResponseWriter, r *http.Request) {
if err := handler(w, r); err != nil {
WriteError(w, r, err)
}
}
2020-01-13 21:05:38 +13:00
2020-01-19 12:30:09 +13:00
return http.HandlerFunc(fn)
2020-01-13 21:05:38 +13:00
}
var nonErrorsCodes = map[int]bool{
2020-01-19 12:30:09 +13:00
404: true,
2020-01-13 21:05:38 +13:00
}
func errResponse(input interface{}) *ErrResponse {
2020-01-19 12:30:09 +13:00
var res *ErrResponse
var err interface{}
switch input.(type) {
case *HandlerError:
e := input.(*HandlerError)
res = &ErrResponse{
Status: e.Status,
Err: http.StatusText(e.Status),
Message: e.Message,
}
err = e.Err
default:
res = &ErrResponse{
Status: http.StatusInternalServerError,
Err: http.StatusText(http.StatusInternalServerError),
}
err = input
}
if err != nil {
switch err.(type) {
case *error:
e := err.(error)
res.Details = e.Error()
break
default:
res.Details = fmt.Sprintf("%+v", err)
break
}
}
return res
2020-01-13 21:05:38 +13:00
}
func WriteError(w http.ResponseWriter, r *http.Request, err interface{}) {
2020-01-19 12:30:09 +13:00
hlog := log.With().
Str("module", "http").
Logger()
res := errResponse(err)
if reqID := middleware.GetReqID(r.Context()); reqID != "" {
res.RequestID = reqID
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(res.Status)
if err := json.NewEncoder(w).Encode(res); err != nil {
hlog.Warn().Err(err).Msg("Failed writing json error response")
}
if !nonErrorsCodes[res.Status] {
logEntry := middleware.GetLogEntry(r)
if logEntry != nil {
logEntry.Panic(err, debug.Stack())
} else {
hlog.Error().Str("stack", string(debug.Stack())).Msgf("%+v", err)
}
}
2020-01-13 21:05:38 +13:00
}