49 lines
1 KiB
Go
49 lines
1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"git.red-panda.pet/pandaware/house/backend/router"
|
|
)
|
|
|
|
func ParseJSONBody[T any](ctx *router.Context) error {
|
|
contentType := ctx.Request.Header.Get("Content-Type")
|
|
if contentType != "application/json" {
|
|
return ctx.GenericError(nil, http.StatusBadRequest)
|
|
}
|
|
|
|
var body T
|
|
|
|
dec := json.NewDecoder(ctx.Request.Body)
|
|
err := dec.Decode(&body)
|
|
if err != nil {
|
|
return ctx.GenericError(err, http.StatusBadRequest)
|
|
}
|
|
|
|
ctx.With(jsonBodyKey, body)
|
|
|
|
return nil
|
|
}
|
|
|
|
func ParseJSONBodyWithValidator[T any](
|
|
ctx *router.Context,
|
|
r router.ValidatedBodyRoute,
|
|
validator func(value T) error,
|
|
) error {
|
|
err := ParseJSONBody[T](ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
body := JSONBody[T](r, ctx)
|
|
return validator(body)
|
|
}
|
|
|
|
func JSONBody[T any](r router.ValidatedBodyRoute, ctx *router.Context) T {
|
|
body, ok := ctx.Value(jsonBodyKey).(T)
|
|
if !ok {
|
|
panic(errors.New("middleware.JSONBody cannot be used with a route that doesn't implement router.ValidatedBodyRoute"))
|
|
}
|
|
return body
|
|
}
|