Skip to content

Commit

Permalink
feat: json data provider
Browse files Browse the repository at this point in the history
  • Loading branch information
Oudwins committed Sep 9, 2024
1 parent e794ae4 commit 2d10c92
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ func Init() {
}
```

**zhttp: helps parse http requests forms & query params**
**zhttp: helps parse http requests**

```go
import (
Expand All @@ -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
Expand Down
12 changes: 12 additions & 0 deletions zhttp/zhttp.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package zhttp

import (
"encoding/json"
"net/http"
"net/url"

Expand Down Expand Up @@ -30,10 +31,21 @@ 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 {
return urlDataProvider{}, err
}
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
}

0 comments on commit 2d10c92

Please sign in to comment.