sync from project

This commit is contained in:
2025-06-18 10:12:19 +08:00
parent 61ffeeb3b8
commit fb579e8689
20 changed files with 1332 additions and 103 deletions

37
magic/autodecode.go Normal file
View File

@ -0,0 +1,37 @@
package magic
import (
"net/http"
"strings"
)
type ErrUknownContentType string
func (err ErrUknownContentType) Error() string {
return "unknown content-type: " + string(err)
}
type AutoDecode[T any] struct {
Data T
}
func (d *AutoDecode[T]) FromRequest(r *http.Request) error {
contentType, _, _ := strings.Cut(r.Header.Get("Content-Type"), ";")
switch contentType {
case "application/json":
decoder := &Json[T]{}
if err := decoder.FromRequest(r); err != nil {
return err
}
d.Data = decoder.Data
case "multipart/form-data", "application/x-www-form-urlencoded":
decoder := &Form[T]{}
if err := decoder.FromRequest(r); err != nil {
return err
}
d.Data = decoder.Data
}
return ErrUknownContentType(contentType)
}
func (d AutoDecode[T]) TakeRequestBody() {}