sync from project
This commit is contained in:
37
magic/autodecode.go
Normal file
37
magic/autodecode.go
Normal 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() {}
|
Reference in New Issue
Block a user