gin/binding/binding.go

74 lines
1.7 KiB
Go
Raw Normal View History

2014-08-29 21:49:50 +04:00
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package binding
2019-04-17 17:10:21 +03:00
import (
"fmt"
2015-03-31 18:51:10 +03:00
2019-04-17 17:10:21 +03:00
"github.com/gin-gonic/gin/binding/common"
)
// These implement the Binding interface and can be used to bind the data
// present in the request to struct instances.
var (
Form = formBinding{}
Query = queryBinding{}
FormPost = formPostBinding{}
Uri = uriBinding{}
2019-04-17 17:10:21 +03:00
FormMultipart = formMultipartBinding{}
)
// Default returns the appropriate Binding instance based on the HTTP method
// and the content type.
2019-04-17 17:10:21 +03:00
func Default(method, contentType string) common.Binding {
2015-03-31 18:51:10 +03:00
if method == "GET" {
return Form
2017-06-13 05:36:37 +03:00
}
switch contentType {
2019-04-17 17:10:21 +03:00
case common.MIMEMultipartPOSTForm:
return FormMultipart
2019-04-17 17:10:21 +03:00
default:
b, ok := common.List[contentType]
if !ok {
return Form //Default to Form
}
return b
}
}
2015-04-09 13:15:02 +03:00
2019-04-17 17:10:21 +03:00
//YAML return the binding for yaml if loaded
func YAML() common.BindingBody {
return retBinding(common.MIMEYAML)
}
//JSON return the binding for json if loaded
func JSON() common.BindingBody {
return retBinding(common.MIMEJSON)
}
//XML return the binding for xml if loaded
func XML() common.BindingBody {
return retBinding(common.MIMEXML)
}
//ProtoBuf return the binding for ProtoBuf if loaded
func ProtoBuf() common.BindingBody {
return retBinding(common.MIMEPROTOBUF)
}
//MsgPack return the binding for MsgPack if loaded
func MsgPack() common.BindingBody {
return retBinding(common.MIMEMSGPACK)
}
//retBinding Search for a render and panic on not found
func retBinding(contentType string) common.BindingBody {
b, ok := common.List[contentType]
if !ok {
panic(fmt.Sprintf("Undefined binding %s", contentType))
2015-05-29 21:34:41 +03:00
}
2019-04-17 17:10:21 +03:00
return b
2015-05-29 21:34:41 +03:00
}