May 15, 2021 Revel
Revel makes it as easy as possible for parameters from the client to be converted to data types in the Go language. This conversion from string to another type is called "data binding."
All request parameters are collected into a
Params
object.
Including:
Params objects are defined in ( godoc ):
type Params struct {
url.Values
Files map[string][]*multipart.FileHeader
}
Embedded
url.Values
(godoc) provides
query support for simple values, but developers can more easily use Revel's data binding support to extract parameters to any data type.
Parameters can be bound directly to controller methods, such as:
func (c AppController) Action(name string, ids []int, user User, img []byte) revel.Result {
...
}
Before the controller method is executed, Revel resolves the argument to the specified data type through the variable name biner, and if the resolution parameter fails, the parameter is parsed to the initial value of the target data type.
Use Revel's binder to bind a parameter to the specified data type (godoc), which integrates the Params object. For example:
func (c SomeController) Action() revel.Result {
var ids []int
c.Params.Bind(&ids, "ids")
...
}
The types of data supported are:
The syntax of data type binding is described below, and the detailed description can also refer to the source code.
The strings "true," "on," and "1" are bound to true, while the others are false .
Slice binding has two syntaxes: ordered and out of order
Ordered:
?ids[0]=1
&ids[1]=2
&ids[3]=4
The binding result
[]int{1, 2, 0, 4}
Disordered:
?ids[]=1
&ids[]=2
&ids[]=3
The binding result
[]int{1, 2, 3}
Note: Only ordered slices can be bound to a struct:
?user[0].Id=1
&user[0].Name=rob
&user[1].Id=2
&user[1].Name=jenny
Struct simply uses a . To bind:
?user.Id=1
&user.Name=rob
&user.Friends[]=2
&user.Friends[]=3
&user.Father.Id=5
&user.Father.Name=Hermes
Binding to the following struct type:
type User struct {
Id int
Name string
Friends []int
Father User
}
Note: The fields in struct must be exported (capital letters).
Built-in SQL Standard Time Format ("2006-01-02", "2006-01-02 15:04")
Use
Revel Official Mode to
simply add a time format to the
TimeFormats
variable:
func init() {
revel.TimeFormats = append(revel.TimeFormats, "01/02/2006")
}
File upload parameters can be bound to the following types:
It's a wrapper for Go's multipart package. The file is kept in memory, and if the file size exceeds 10MB (the default), it is saved to a temporary file.
Note:
Binding
os.File
type, which is saved to a temporary file (if not), is inefficient.
The application can define biners.
The custom binder needs to implement the binder interface and register the custom type:
var myBinder = revel.Binder{
Bind: func(params *revel.Params, name string, typ reflect.Type) reflect.Value {...},
Unbind: func(output map[string]string, name string, val interface{}) {...},
}
func init() {
revel.TypeBinders[reflect.TypeOf(MyType{})] = myBinder