mirror of
https://github.com/portainer/portainer.git
synced 2025-07-24 07:49:41 +02:00
feat(libhttp): move into the Portainer repository EE-5475 (#10231)
This commit is contained in:
parent
090fa4aeb3
commit
8cc5e0796c
249 changed files with 1059 additions and 639 deletions
37
pkg/libhttp/request/payload.go
Normal file
37
pkg/libhttp/request/payload.go
Normal file
|
@ -0,0 +1,37 @@
|
|||
package request
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// PayloadValidation is an interface used to validate the payload of a request.
|
||||
type PayloadValidation interface {
|
||||
Validate(request *http.Request) error
|
||||
}
|
||||
|
||||
// DecodeAndValidateJSONPayload decodes the body of the request into an object
|
||||
// implementing the PayloadValidation interface.
|
||||
// It also triggers a validation of object content.
|
||||
func DecodeAndValidateJSONPayload(request *http.Request, v PayloadValidation) error {
|
||||
if err := json.NewDecoder(request.Body).Decode(v); err != nil {
|
||||
return err
|
||||
}
|
||||
return v.Validate(request)
|
||||
}
|
||||
|
||||
// GetPayload decodes the body of the request into an object implementing the PayloadValidation interface.
|
||||
func GetPayload[T any, PT interface {
|
||||
*T
|
||||
Validate(request *http.Request) error
|
||||
}](r *http.Request) (PT, error) {
|
||||
p := PT(new(T))
|
||||
|
||||
err := DecodeAndValidateJSONPayload(r, p)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "Invalid request payload")
|
||||
}
|
||||
return p, nil
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue