diff --git a/README.md b/README.md index d71f9f8..c9e4042 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,7 @@ func Init() { } ``` -**zhttp: helps parse http requests forms & query params** +**zhttp: helps parse http requests** ```go import ( @@ -205,8 +205,10 @@ func handlePostRequest(w http.ResponseWriter, r *http.Request) { Name string Age int } - // Parse the request into the user struct from the query params or the form data + // if using query params or form data: errs := userSchema.Parse(zhttp.NewRequestDataProvider(r), &user) + // if using json: + errs := userSchema.Parse(zhttp.NewJsonDataProvider(r), &user) if errs != nil { } user.Name // defined diff --git a/zhttp/zhttp.go b/zhttp/zhttp.go index 84e295b..10c86a5 100644 --- a/zhttp/zhttp.go +++ b/zhttp/zhttp.go @@ -1,6 +1,7 @@ package zhttp import ( + "encoding/json" "net/http" "net/url" @@ -30,6 +31,7 @@ func (u urlDataProvider) GetNestedProvider(key string) p.DataProvider { return u } +// Only supports form data & query parms func NewRequestDataProvider(r *http.Request) (urlDataProvider, error) { err := r.ParseForm() if err != nil { @@ -37,3 +39,13 @@ func NewRequestDataProvider(r *http.Request) (urlDataProvider, error) { } return urlDataProvider{Data: r.Form}, nil } + +func NewJsonDataProvider(r *http.Request) (p.DataProvider, error) { + var data map[string]any + decod := json.NewDecoder(r.Body) + err := decod.Decode(&data) + if err != nil { + return nil, err + } + return p.NewMapDataProvider(data), nil +}