Skip to content

Commit 6ecdfc8

Browse files
committed
Improve request binding documentation. See Echo pull request #1681 (labstack/echo#1681)
1 parent 9665f96 commit 6ecdfc8

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

website/content/guide/request.md

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,32 @@ description = "Handling HTTP request in Echo"
88

99
## Bind Data
1010

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.
1213
The default binder supports decoding application/json, application/xml and
1314
application/x-www-form-urlencoded data based on the Content-Type header.
1415

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+
1537
Example below binds the request payload into `User` struct based on tags:
1638

1739
```go
@@ -29,6 +51,15 @@ func(c echo.Context) (err error) {
2951
if err = c.Bind(u); err != nil {
3052
return
3153
}
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+
3263
return c.JSON(http.StatusOK, u)
3364
}
3465
```

0 commit comments

Comments
 (0)