2025-06-16 22:19:00 +05:30
|
|
|
// Copyright 2024 Patial Tech (Ankit Patial).
|
2025-06-16 22:26:47 +05:30
|
|
|
//
|
|
|
|
// This file is part of code.patial.tech/go/appcore, which is MIT licensed.
|
|
|
|
// See http://opensource.org/licenses/MIT
|
2025-06-16 22:19:00 +05:30
|
|
|
|
|
|
|
package request
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"code.patial.tech/go/appcore/validate"
|
|
|
|
)
|
|
|
|
|
|
|
|
func FormField(r *http.Request, key string) (string, error) {
|
|
|
|
f, err := Payload[map[string]any](r)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return fmt.Sprintf("%v", f[key]), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func PayloadMap(r *http.Request) (map[string]any, error) {
|
|
|
|
return Payload[map[string]any](r)
|
|
|
|
}
|
|
|
|
|
|
|
|
func PayloadWithValidate[T any](r *http.Request) (T, error) {
|
|
|
|
p, err := Payload[T](r)
|
|
|
|
if err != nil {
|
|
|
|
return p, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := validate.Struct(p); err != nil {
|
|
|
|
return p, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return p, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func Payload[T any](r *http.Request) (T, error) {
|
|
|
|
var p T
|
|
|
|
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
|
|
|
|
return p, err
|
|
|
|
}
|
|
|
|
return p, nil
|
|
|
|
}
|