1
0
Fork 0
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:
andres-portainer 2023-09-01 19:27:02 -03:00 committed by GitHub
parent 090fa4aeb3
commit 8cc5e0796c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
249 changed files with 1059 additions and 639 deletions

View 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
}