Full API implementation

This commit is contained in:
2025-09-09 07:03:32 -04:00
parent 5a63c5939a
commit 94f5802498
3 changed files with 54 additions and 57 deletions

View File

@@ -6,7 +6,7 @@ import (
"fmt"
"mime/multipart"
"net/http"
"strconv"
"net/url"
"strings"
)
@@ -16,36 +16,44 @@ type Request struct {
}
func (req Request) Param(key string) (any, error) {
value, ok := req.params[key]
if ok {
if value, ok := req.params[key]; ok {
return value, nil
}
return nil, fmt.Errorf("param %s not found", key)
}
func (req Request) ParamInt64(key string) (int64, error) {
param, err := req.Param(key)
func (req Request) Query(key string) (any, error) {
values, err := url.ParseQuery(req.Request.URL.RawQuery)
if err != nil {
return 0, err
return nil, err
}
i, err := strconv.Atoi(param.(string))
if err != nil {
return 0, err
value, ok := values[key]
if !ok {
return nil, fmt.Errorf("query string parameter %s not found", key)
}
return int64(i), nil
if len(value) > 1 {
return value, nil
}
return value[0], nil
}
// Bind Binds the request body to the struct pointer v using the Content-Type header to select a binder. This function panics if v cannot be bound.
// Bind Binds the request body to the struct pointer v using the Content-Type header to select a binder.
func (req Request) Bind(v any) error {
body, err := req.Request.GetBody()
if err != nil {
return err
}
mime := req.Header.Get("Content-Type")
mime = strings.Split(mime, ";")[0]
switch mime {
case "application/json":
err := json.NewDecoder(req.Body).Decode(&v)
err := json.NewDecoder(body).Decode(&v)
if err != nil {
return fmt.Errorf("error while decoding http request body as json: %w", err)
}
@@ -57,13 +65,13 @@ func (req Request) Bind(v any) error {
return nil
}
func (req Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error) {
func (req Request) File(key string) (multipart.File, *multipart.FileHeader, error) {
maxMegs, err := config.GetInt64("uploads.maxMegabytes")
if err != nil {
maxMegs = 8000000
}
if err := req.ParseMultipartForm(maxMegs << 20); err != nil {
if err = req.ParseMultipartForm(maxMegs << 20); err != nil {
return nil, nil, err
}