38 lines
792 B
Go
38 lines
792 B
Go
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() {}
|