nf/req.go
2024-01-11 22:29:30 +08:00

46 lines
810 B
Go

package nf
import (
"bytes"
"encoding/json"
"errors"
"io"
"log"
"strings"
)
func (c *Ctx) Form(key string) string {
return c.Request.FormValue(key)
}
func (c *Ctx) Query(key string) string {
return c.Request.URL.Query().Get(key)
}
func (c *Ctx) BodyParser(out interface{}) error {
ctype := strings.ToLower(c.Request.Header.Get("Content-Type"))
log.Printf("BodyParser: Content-Type=%s", ctype)
ctype = parseVendorSpecificContentType(ctype)
ctypeEnd := strings.IndexByte(ctype, ';')
if ctypeEnd != -1 {
ctype = ctype[:ctypeEnd]
}
if strings.HasSuffix(ctype, "json") {
bs, err := io.ReadAll(c.Request.Body)
if err != nil {
return err
}
c.Request.Body = io.NopCloser(bytes.NewReader(bs))
return json.Unmarshal(bs, out)
}
return errors.New("422 Unprocessable Content")
}