Skip to content

Commit

Permalink
feat: add method ShouldBindWidth/ShouldBindBodyWith/ShouldBindWithJSO…
Browse files Browse the repository at this point in the history
…N/ShouldBindBodyWithJSON; close #21
  • Loading branch information
tonny-zhang committed Sep 28, 2021
1 parent 028ce86 commit 010e194
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 0 deletions.
19 changes: 19 additions & 0 deletions binding/Binding.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package binding

import "net/http"

// IBinding Binding interface
type IBinding interface {
Bind(*http.Request, interface{}) error
}

// IBindingBody bind body
type IBindingBody interface {
IBinding
BindBody([]byte, interface{}) error
}

var (
// JSON json binding
JSON = jsonBinding{}
)
28 changes: 28 additions & 0 deletions binding/json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package binding

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)

type jsonBinding struct{}

func (jsonBinding) Bind(req *http.Request, obj interface{}) (err error) {
if req == nil || req.Body == nil {
err = fmt.Errorf("bad request")
} else {
err = decodeJSON(req.Body, obj)
}
return
}
func (jsonBinding) BindBody(b []byte, obj interface{}) error {
return decodeJSON(bytes.NewBuffer(b), obj)
}

func decodeJSON(r io.Reader, obj interface{}) error {
decoder := json.NewDecoder(r)
return decoder.Decode(obj)
}
43 changes: 43 additions & 0 deletions context_binding.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package cotton

import (
"io/ioutil"

"github.com/tonny-zhang/cotton/binding"
)

// ShouldBindWith bind
func (ctx *Context) ShouldBindWith(obj interface{}, b binding.IBinding) error {
return b.Bind(ctx.Request, obj)
}

// BodyBytesKey indicates a default body bytes key.
const BodyBytesKey = "cotton/bbk"

// ShouldBindBodyWith bind body
func (ctx *Context) ShouldBindBodyWith(obj interface{}, bb binding.IBindingBody) (err error) {
var body []byte
if v, ok := ctx.Get(BodyBytesKey); ok {
if vv, ok := v.([]byte); ok {
body = vv
}
}
if body == nil {
body, err = ioutil.ReadAll(ctx.Request.Body)
if err != nil {
return
}
ctx.Set(BodyBytesKey, body)
}
return bb.BindBody(body, obj)
}

// ShouldBindWithJSON bind with json
func (ctx *Context) ShouldBindWithJSON(obj interface{}) error {
return ctx.ShouldBindWith(obj, binding.JSON)
}

// ShouldBindBodyWithJSON bind body with json
func (ctx *Context) ShouldBindBodyWithJSON(obj interface{}) (err error) {
return ctx.ShouldBindBodyWith(obj, binding.JSON)
}

0 comments on commit 010e194

Please sign in to comment.