@@ -31,6 +31,7 @@ import (
3131
3232 "github.com/unknwon/com"
3333 "gopkg.in/macaron.v1"
34+ "gopkg.in/yaml.v3"
3435)
3536
3637func bind (ctx * macaron.Context , obj interface {}, ifacePtr ... interface {}) {
@@ -43,6 +44,8 @@ func bind(ctx *macaron.Context, obj interface{}, ifacePtr ...interface{}) {
4344 _ , _ = ctx .Invoke (MultipartForm (obj , ifacePtr ... ))
4445 case strings .Contains (contentType , "json" ):
4546 _ , _ = ctx .Invoke (Json (obj , ifacePtr ... ))
47+ case strings .Contains (contentType , "yaml" ):
48+ _ , _ = ctx .Invoke (Yaml (obj , ifacePtr ... ))
4649 default :
4750 var errors Errors
4851 if contentType == "" {
@@ -60,6 +63,7 @@ func bind(ctx *macaron.Context, obj interface{}, ifacePtr ...interface{}) {
6063
6164const (
6265 _JSON_CONTENT_TYPE = "application/json; charset=utf-8"
66+ _YAML_CONTENT_TYPE = "text/yaml; charset=utf-8"
6367 STATUS_UNPROCESSABLE_ENTITY = 422
6468)
6569
@@ -207,10 +211,39 @@ func Json(jsonStruct interface{}, ifacePtr ...interface{}) macaron.Handler {
207211 errors .Add ([]string {}, ERR_DESERIALIZATION , err .Error ())
208212 }
209213 }
214+ if errors != nil {
215+ ctx .Map (errors )
216+ return
217+ }
210218 validateAndMap (jsonStruct , ctx , errors , ifacePtr ... )
211219 }
212220}
213221
222+ // Yaml is middleware to deserialize a YAML payload from the request
223+ // into the struct that is passed in. The resulting struct is then
224+ // validated, but no error handling is actually performed here.
225+ // An interface pointer can be added as a second argument in order
226+ // to map the struct to a specific interface.
227+ func Yaml (yamlStruct interface {}, ifacePtr ... interface {}) macaron.Handler {
228+ return func (ctx * macaron.Context ) {
229+ var errors Errors
230+ ensureNotPointer (yamlStruct )
231+ yamlStruct := reflect .New (reflect .TypeOf (yamlStruct ))
232+ if ctx .Req .Request .Body != nil {
233+ defer ctx .Req .Request .Body .Close ()
234+ err := yaml .NewDecoder (ctx .Req .Request .Body ).Decode (yamlStruct .Interface ())
235+ if err != nil && err != io .EOF {
236+ errors .Add ([]string {}, ERR_DESERIALIZATION , err .Error ())
237+ }
238+ }
239+ if errors != nil {
240+ ctx .Map (errors )
241+ return
242+ }
243+ validateAndMap (yamlStruct , ctx , errors , ifacePtr ... )
244+ }
245+ }
246+
214247// URL is the middleware to parse URL parameters into struct fields.
215248func URL (obj interface {}, ifacePtr ... interface {}) macaron.Handler {
216249 return func (ctx * macaron.Context ) {
0 commit comments