This repository has been archived by the owner on Feb 24, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 579
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
- Loading branch information
Showing
2 changed files
with
69 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
package buffalo | ||
|
||
import ( | ||
"encoding/json" | ||
"encoding/xml" | ||
"net/http" | ||
"reflect" | ||
"sync" | ||
|
||
"github.com/gorilla/schema" | ||
"github.com/markbates/pop/nulls" | ||
"github.com/pkg/errors" | ||
) | ||
|
||
var binderLock = &sync.Mutex{} | ||
var binders = map[string]BinderFunc{} | ||
var schemaDecoder *schema.Decoder | ||
|
||
type BinderFunc func(*http.Request, interface{}) error | ||
|
||
func RegisterBinder(contentType string, fn BinderFunc) { | ||
binderLock.Lock() | ||
defer binderLock.Unlock() | ||
binders[contentType] = fn | ||
} | ||
|
||
func init() { | ||
schemaDecoder = schema.NewDecoder() | ||
schemaDecoder.IgnoreUnknownKeys(true) | ||
schemaDecoder.ZeroEmpty(true) | ||
|
||
// register the types in the nulls package with the decoder | ||
nulls.RegisterWithSchema(func(i interface{}, fn func(s string) reflect.Value) { | ||
schemaDecoder.RegisterConverter(i, fn) | ||
}) | ||
|
||
sb := func(req *http.Request, value interface{}) error { | ||
err := req.ParseForm() | ||
if err != nil { | ||
return errors.WithStack(err) | ||
} | ||
return schemaDecoder.Decode(value, req.PostForm) | ||
} | ||
binders["application/html"] = sb | ||
binders["text/html"] = sb | ||
binders["application/x-www-form-urlencoded"] = sb | ||
} | ||
|
||
func init() { | ||
jb := func(req *http.Request, value interface{}) error { | ||
return json.NewDecoder(req.Body).Decode(value) | ||
} | ||
binders["application/json"] = jb | ||
binders["text/json"] = jb | ||
binders["json"] = jb | ||
} | ||
|
||
func init() { | ||
xb := func(req *http.Request, value interface{}) error { | ||
return xml.NewDecoder(req.Body).Decode(value) | ||
} | ||
binders["application/xml"] = xb | ||
binders["text/xml"] = xb | ||
binders["xml"] = xb | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters