Added: downloading and returning wikipedia articles
This commit is contained in:
38
api/httpio/request.go
Normal file
38
api/httpio/request.go
Normal file
@@ -0,0 +1,38 @@
|
||||
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
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user