mirror of
https://github.com/hay-kot/homebox.git
synced 2025-06-30 15:48:36 +00:00
chore: refactor api endpoints (#339)
* move typegen code * update taskfile to fix code-gen caches and use 'dir' attribute * enable dumping stack traces for errors * log request start and stop * set zerolog stack handler * fix routes function * refactor context adapters to use requests directly * change some method signatures to support GID * start requiring validation tags * first pass on updating handlers to use adapters * add errs package * code gen * tidy * rework API to use external server package
This commit is contained in:
parent
184b494fc3
commit
db80f8a159
56 changed files with 806 additions and 1947 deletions
|
@ -3,7 +3,8 @@ package adapters
|
|||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/hay-kot/safeserve/errchain"
|
||||
"github.com/hay-kot/safeserve/server"
|
||||
)
|
||||
|
||||
// Action is a function that adapts a function to the server.Handler interface.
|
||||
|
@ -16,25 +17,25 @@ import (
|
|||
// Foo string `json:"foo"`
|
||||
// }
|
||||
//
|
||||
// fn := func(ctx context.Context, b Body) (any, error) {
|
||||
// fn := func(r *http.Request, b Body) (any, error) {
|
||||
// // do something with b
|
||||
// return nil, nil
|
||||
// }
|
||||
//
|
||||
// r.Post("/foo", adapters.Action(fn, http.StatusCreated))
|
||||
func Action[T any, Y any](f AdapterFunc[T, Y], ok int) server.HandlerFunc {
|
||||
func Action[T any, Y any](f AdapterFunc[T, Y], ok int) errchain.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
v, err := decode[T](r)
|
||||
v, err := DecodeBody[T](r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
res, err := f(r.Context(), v)
|
||||
res, err := f(r, v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return server.Respond(w, ok, res)
|
||||
return server.JSON(w, ok, res)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -46,29 +47,29 @@ func Action[T any, Y any](f AdapterFunc[T, Y], ok int) server.HandlerFunc {
|
|||
// Foo string `json:"foo"`
|
||||
// }
|
||||
//
|
||||
// fn := func(ctx context.Context, ID uuid.UUID, b Body) (any, error) {
|
||||
// fn := func(r *http.Request, ID uuid.UUID, b Body) (any, error) {
|
||||
// // do something with ID and b
|
||||
// return nil, nil
|
||||
// }
|
||||
//
|
||||
// r.Post("/foo/{id}", adapters.ActionID(fn, http.StatusCreated))
|
||||
func ActionID[T any, Y any](param string, f IDFunc[T, Y], ok int) server.HandlerFunc {
|
||||
func ActionID[T any, Y any](param string, f IDFunc[T, Y], ok int) errchain.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ID, err := routeUUID(r, param)
|
||||
ID, err := RouteUUID(r, param)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
v, err := decode[T](r)
|
||||
v, err := DecodeBody[T](r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
res, err := f(r.Context(), ID, v)
|
||||
res, err := f(r, ID, v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return server.Respond(w, ok, res)
|
||||
return server.JSON(w, ok, res)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
package adapters
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type AdapterFunc[T any, Y any] func(context.Context, T) (Y, error)
|
||||
type IDFunc[T any, Y any] func(context.Context, uuid.UUID, T) (Y, error)
|
||||
type AdapterFunc[T any, Y any] func(*http.Request, T) (Y, error)
|
||||
type IDFunc[T any, Y any] func(*http.Request, uuid.UUID, T) (Y, error)
|
||||
|
|
|
@ -1,36 +1,36 @@
|
|||
package adapters
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/hay-kot/safeserve/errchain"
|
||||
"github.com/hay-kot/safeserve/server"
|
||||
)
|
||||
|
||||
type CommandFunc[T any] func(context.Context) (T, error)
|
||||
type CommandIDFunc[T any] func(context.Context, uuid.UUID) (T, error)
|
||||
type CommandFunc[T any] func(*http.Request) (T, error)
|
||||
type CommandIDFunc[T any] func(*http.Request, uuid.UUID) (T, error)
|
||||
|
||||
// Command is an HandlerAdapter that returns a server.HandlerFunc that
|
||||
// Command is an HandlerAdapter that returns a errchain.HandlerFunc that
|
||||
// The command adapters are used to handle commands that do not accept a body
|
||||
// or a query. You can think of them as a way to handle RPC style Rest Endpoints.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// fn := func(ctx context.Context) (interface{}, error) {
|
||||
// // do something
|
||||
// return nil, nil
|
||||
// }
|
||||
// fn := func(r *http.Request) (interface{}, error) {
|
||||
// // do something
|
||||
// return nil, nil
|
||||
// }
|
||||
//
|
||||
// r.Get("/foo", adapters.Command(fn, http.NoContent))
|
||||
func Command[T any](f CommandFunc[T], ok int) server.HandlerFunc {
|
||||
// r.Get("/foo", adapters.Command(fn, http.NoContent))
|
||||
func Command[T any](f CommandFunc[T], ok int) errchain.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
res, err := f(r.Context())
|
||||
res, err := f(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return server.Respond(w, ok, res)
|
||||
return server.JSON(w, ok, res)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -39,24 +39,24 @@ func Command[T any](f CommandFunc[T], ok int) server.HandlerFunc {
|
|||
//
|
||||
// Example:
|
||||
//
|
||||
// fn := func(ctx context.Context, id uuid.UUID) (interface{}, error) {
|
||||
// fn := func(r *http.Request, id uuid.UUID) (interface{}, error) {
|
||||
// // do something
|
||||
// return nil, nil
|
||||
// }
|
||||
//
|
||||
// r.Get("/foo/{id}", adapters.CommandID("id", fn, http.NoContent))
|
||||
func CommandID[T any](param string, f CommandIDFunc[T], ok int) server.HandlerFunc {
|
||||
func CommandID[T any](param string, f CommandIDFunc[T], ok int) errchain.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ID, err := routeUUID(r, param)
|
||||
ID, err := RouteUUID(r, param)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
res, err := f(r.Context(), ID)
|
||||
res, err := f(r, ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return server.Respond(w, ok, res)
|
||||
return server.JSON(w, ok, res)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,47 +3,49 @@ package adapters
|
|||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/schema"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/hay-kot/safeserve/server"
|
||||
)
|
||||
|
||||
var queryDecoder = schema.NewDecoder()
|
||||
|
||||
func decodeQuery[T any](r *http.Request) (T, error) {
|
||||
func DecodeQuery[T any](r *http.Request) (T, error) {
|
||||
var v T
|
||||
err := queryDecoder.Decode(&v, r.URL.Query())
|
||||
if err != nil {
|
||||
return v, err
|
||||
return v, errors.Wrap(err, "decoding error")
|
||||
}
|
||||
|
||||
err = validate.Check(v)
|
||||
if err != nil {
|
||||
return v, err
|
||||
return v, errors.Wrap(err, "validation error")
|
||||
}
|
||||
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func decode[T any](r *http.Request) (T, error) {
|
||||
func DecodeBody[T any](r *http.Request) (T, error) {
|
||||
var v T
|
||||
|
||||
err := server.Decode(r, &v)
|
||||
if err != nil {
|
||||
return v, err
|
||||
return v, errors.Wrap(err, "body decoding error")
|
||||
}
|
||||
|
||||
err = validate.Check(v)
|
||||
if err != nil {
|
||||
return v, err
|
||||
return v, errors.Wrap(err, "validation error")
|
||||
}
|
||||
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func routeUUID(r *http.Request, key string) (uuid.UUID, error) {
|
||||
func RouteUUID(r *http.Request, key string) (uuid.UUID, error) {
|
||||
ID, err := uuid.Parse(chi.URLParam(r, key))
|
||||
if err != nil {
|
||||
return uuid.Nil, validate.NewRouteKeyError(key)
|
||||
|
|
|
@ -3,7 +3,8 @@ package adapters
|
|||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/hay-kot/safeserve/errchain"
|
||||
"github.com/hay-kot/safeserve/server"
|
||||
)
|
||||
|
||||
// Query is a server.Handler that decodes a query from the request and calls the provided function.
|
||||
|
@ -14,25 +15,25 @@ import (
|
|||
// Foo string `schema:"foo"`
|
||||
// }
|
||||
//
|
||||
// fn := func(ctx context.Context, q Query) (any, error) {
|
||||
// fn := func(r *http.Request, q Query) (any, error) {
|
||||
// // do something with q
|
||||
// return nil, nil
|
||||
// }
|
||||
//
|
||||
// r.Get("/foo", adapters.Query(fn, http.StatusOK))
|
||||
func Query[T any, Y any](f AdapterFunc[T, Y], ok int) server.HandlerFunc {
|
||||
func Query[T any, Y any](f AdapterFunc[T, Y], ok int) errchain.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
q, err := decodeQuery[T](r)
|
||||
q, err := DecodeQuery[T](r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
res, err := f(r.Context(), q)
|
||||
res, err := f(r, q)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return server.Respond(w, ok, res)
|
||||
return server.JSON(w, ok, res)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -44,29 +45,29 @@ func Query[T any, Y any](f AdapterFunc[T, Y], ok int) server.HandlerFunc {
|
|||
// Foo string `schema:"foo"`
|
||||
// }
|
||||
//
|
||||
// fn := func(ctx context.Context, ID uuid.UUID, q Query) (any, error) {
|
||||
// fn := func(r *http.Request, ID uuid.UUID, q Query) (any, error) {
|
||||
// // do something with ID and q
|
||||
// return nil, nil
|
||||
// }
|
||||
//
|
||||
// r.Get("/foo/{id}", adapters.QueryID(fn, http.StatusOK))
|
||||
func QueryID[T any, Y any](param string, f IDFunc[T, Y], ok int) server.HandlerFunc {
|
||||
func QueryID[T any, Y any](param string, f IDFunc[T, Y], ok int) errchain.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) error {
|
||||
ID, err := routeUUID(r, param)
|
||||
ID, err := RouteUUID(r, param)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
q, err := decodeQuery[T](r)
|
||||
q, err := DecodeQuery[T](r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
res, err := f(r.Context(), ID, q)
|
||||
res, err := f(r, ID, q)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return server.Respond(w, ok, res)
|
||||
return server.JSON(w, ok, res)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,33 +3,42 @@ package mid
|
|||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/hay-kot/homebox/backend/internal/data/ent"
|
||||
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/hay-kot/safeserve/errchain"
|
||||
"github.com/hay-kot/safeserve/server"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func Errors(log zerolog.Logger) server.Middleware {
|
||||
return func(h server.Handler) server.Handler {
|
||||
return server.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
|
||||
type ErrorResponse struct {
|
||||
Error string `json:"error"`
|
||||
Fields map[string]string `json:"fields,omitempty"`
|
||||
}
|
||||
|
||||
func Errors(svr *server.Server, log zerolog.Logger) errchain.ErrorHandler {
|
||||
return func(h errchain.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
err := h.ServeHTTP(w, r)
|
||||
if err != nil {
|
||||
var resp server.ErrorResponse
|
||||
var resp ErrorResponse
|
||||
var code int
|
||||
|
||||
traceID := r.Context().Value(middleware.RequestIDKey).(string)
|
||||
log.Err(err).
|
||||
Str("trace_id", server.GetTraceID(r.Context())).
|
||||
Stack().
|
||||
Str("req_id", traceID).
|
||||
Msg("ERROR occurred")
|
||||
|
||||
switch {
|
||||
case validate.IsUnauthorizedError(err):
|
||||
code = http.StatusUnauthorized
|
||||
resp = server.ErrorResponse{
|
||||
resp = ErrorResponse{
|
||||
Error: "unauthorized",
|
||||
}
|
||||
case validate.IsInvalidRouteKeyError(err):
|
||||
code = http.StatusBadRequest
|
||||
resp = server.ErrorResponse{
|
||||
resp = ErrorResponse{
|
||||
Error: err.Error(),
|
||||
}
|
||||
case validate.IsFieldError(err):
|
||||
|
@ -59,17 +68,18 @@ func Errors(log zerolog.Logger) server.Middleware {
|
|||
code = http.StatusInternalServerError
|
||||
}
|
||||
|
||||
if err := server.Respond(w, code, resp); err != nil {
|
||||
return err
|
||||
if err := server.JSON(w, code, resp); err != nil {
|
||||
log.Err(err).Msg("failed to write response")
|
||||
}
|
||||
|
||||
// If Showdown error, return error
|
||||
if server.IsShutdownError(err) {
|
||||
return err
|
||||
err := svr.Shutdown(err.Error())
|
||||
if err != nil {
|
||||
log.Err(err).Msg("failed to shutdown server")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,96 +1,33 @@
|
|||
package mid
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
type statusRecorder struct {
|
||||
type spy struct {
|
||||
http.ResponseWriter
|
||||
Status int
|
||||
status int
|
||||
}
|
||||
|
||||
func (r *statusRecorder) WriteHeader(status int) {
|
||||
r.Status = status
|
||||
r.ResponseWriter.WriteHeader(status)
|
||||
func (s *spy) WriteHeader(status int) {
|
||||
s.status = status
|
||||
s.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func Logger(log zerolog.Logger) server.Middleware {
|
||||
return func(next server.Handler) server.Handler {
|
||||
return server.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
|
||||
traceId := server.GetTraceID(r.Context())
|
||||
func Logger(l zerolog.Logger) func(http.Handler) http.Handler {
|
||||
return func(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := r.Context().Value(middleware.RequestIDKey).(string)
|
||||
|
||||
log.Info().
|
||||
Str("trace_id", traceId).
|
||||
Str("method", r.Method).
|
||||
Str("path", r.URL.Path).
|
||||
Str("remove_address", r.RemoteAddr).
|
||||
Msg("request started")
|
||||
l.Info().Str("method", r.Method).Str("path", r.URL.Path).Str("rid", reqID).Msg("request received")
|
||||
|
||||
record := &statusRecorder{ResponseWriter: w, Status: http.StatusOK}
|
||||
s := &spy{ResponseWriter: w}
|
||||
h.ServeHTTP(s, r)
|
||||
|
||||
err := next.ServeHTTP(record, r)
|
||||
|
||||
log.Info().
|
||||
Str("trace_id", traceId).
|
||||
Str("method", r.Method).
|
||||
Str("url", r.URL.Path).
|
||||
Str("remote_address", r.RemoteAddr).
|
||||
Int("status_code", record.Status).
|
||||
Msg("request completed")
|
||||
|
||||
return err
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func SugarLogger(log zerolog.Logger) server.Middleware {
|
||||
orange := func(s string) string { return "\033[33m" + s + "\033[0m" }
|
||||
aqua := func(s string) string { return "\033[36m" + s + "\033[0m" }
|
||||
red := func(s string) string { return "\033[31m" + s + "\033[0m" }
|
||||
green := func(s string) string { return "\033[32m" + s + "\033[0m" }
|
||||
|
||||
fmtCode := func(code int) string {
|
||||
switch {
|
||||
case code >= 500:
|
||||
return red(fmt.Sprintf("%d", code))
|
||||
case code >= 400:
|
||||
return orange(fmt.Sprintf("%d", code))
|
||||
case code >= 300:
|
||||
return aqua(fmt.Sprintf("%d", code))
|
||||
default:
|
||||
return green(fmt.Sprintf("%d", code))
|
||||
}
|
||||
}
|
||||
bold := func(s string) string { return "\033[1m" + s + "\033[0m" }
|
||||
|
||||
atLeast6 := func(s string) string {
|
||||
for len(s) <= 6 {
|
||||
s += " "
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
return func(next server.Handler) server.Handler {
|
||||
return server.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
|
||||
record := &statusRecorder{ResponseWriter: w, Status: http.StatusOK}
|
||||
|
||||
err := next.ServeHTTP(record, r) // Blocks until the next handler returns.
|
||||
|
||||
url := fmt.Sprintf("%s %s", r.RequestURI, r.Proto)
|
||||
|
||||
log.Info().
|
||||
Str("trace_id", server.GetTraceID(r.Context())).
|
||||
Msgf("%s %s %s",
|
||||
bold(fmtCode(record.Status)),
|
||||
bold(orange(atLeast6(r.Method))),
|
||||
aqua(url),
|
||||
)
|
||||
|
||||
return err
|
||||
l.Info().Str("method", r.Method).Str("path", r.URL.Path).Int("status", s.status).Str("rid", reqID).Msg("request finished")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,33 +0,0 @@
|
|||
package mid
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/hay-kot/homebox/backend/pkgs/server"
|
||||
)
|
||||
|
||||
// Panic is a middleware that recovers from panics anywhere in the chain and wraps the error.
|
||||
// and returns it up the middleware chain.
|
||||
func Panic(develop bool) server.Middleware {
|
||||
return func(h server.Handler) server.Handler {
|
||||
return server.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (err error) {
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
trace := debug.Stack()
|
||||
|
||||
if develop {
|
||||
err = fmt.Errorf("PANIC [%v]", rec)
|
||||
fmt.Printf("%s", string(trace))
|
||||
} else {
|
||||
err = fmt.Errorf("PANIC [%v] TRACE[%s]", rec, string(trace))
|
||||
}
|
||||
|
||||
}
|
||||
}()
|
||||
|
||||
return h.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue