initial commit
This commit is contained in:
commit
d40b69f1f9
58 changed files with 7919 additions and 0 deletions
49
backend/middleware/json.go
Normal file
49
backend/middleware/json.go
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
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
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue