Files
scrap/api/httpio/request.go
2025-10-04 23:14:41 +02:00

39 lines
669 B
Go

package httpio
import (
"encoding/json"
"errors"
"io"
"log"
"net/http"
)
type IRequestIO interface {
// Validates the received request.
Validate() *HTTPError
}
// Parses request body into the provided struct.
// Throws an error if the body could not be parsed.
func ParseRequestBody[T IRequestIO](r *http.Request) (*T, error) {
requestBytes, err := io.ReadAll(r.Body)
if err != nil {
log.Println(err.Error())
return nil, err
}
if !json.Valid(requestBytes) {
return nil, errors.New("invalid JSON format")
}
var req T
err = json.Unmarshal(requestBytes, &req)
if err != nil {
log.Println(err.Error())
return nil, err
}
return &req, nil
}