@@ -8,10 +8,32 @@ description = "Handling HTTP request in Echo"
8
8
9
9
## Bind Data
10
10
11
- To bind request body into a Go type use ` Context#Bind(i interface{}) ` .
11
+ Echo provides following method to bind data from different sources (route params, query params, request body) to structure
12
+ ` Context#Bind(i interface{}) ` method.
12
13
The default binder supports decoding application/json, application/xml and
13
14
application/x-www-form-urlencoded data based on the Content-Type header.
14
15
16
+ Request data is binded to the struct in given order:
17
+
18
+ 1 . Route parameters
19
+ 2 . Query parameters
20
+ 3 . Request body
21
+
22
+ Notes:
23
+
24
+ * Each step can overwrite binded fields from the previous step. This means if your json request has query param
25
+ ` &name=query ` and body is ` {"name": "body"} ` then the result will be ` User{Name: "body"} ` .
26
+ * To avoid security flaws try to avoid passing binded structs directly to other methods if
27
+ these structs contain fields that should not be bindable. It is advisable to have separate struct for binding and map it
28
+ explicitly to your business struct. Consider what will happen if your binded struct has public
29
+ field ` IsAdmin bool ` and request body would contain ` {IsAdmin: true, Name: "hacker"} ` .
30
+ * To bind data only from request body use following code
31
+ ``` go
32
+ if err := (&DefaultBinder{}).BindBody (c, &payload); err != nil {
33
+ return err
34
+ }
35
+ ```
36
+
15
37
Example below binds the request payload into ` User ` struct based on tags:
16
38
17
39
``` go
@@ -29,6 +51,15 @@ func(c echo.Context) (err error) {
29
51
if err = c.Bind (u); err != nil {
30
52
return
31
53
}
54
+ // To avoid security flaws try to avoid passing binded structs directly to other methods
55
+ // if these structs contain fields that should not be bindable.
56
+ user := UserDTO{
57
+ Name: u.Name ,
58
+ Email: u.Email ,
59
+ IsAdmin: false // because you could accidentally expose fields that should not be bind
60
+ }
61
+ executeSomeBusinessLogic (user)
62
+
32
63
return c.JSON (http.StatusOK , u)
33
64
}
34
65
```
0 commit comments