# 請求
其實在[流程](../chaptero1/0101_flow.md) 中就有講到。
在請求來到服務器后,Context對象會生成用來串流程:
和請求有關的字段包括:
```
// context.go:40
type Context struct {
// ServeHTTP的第二個參數: request
Request *http.Request
// URL里面的參數,比如:/xx/:id
Params Params
}
```
### 獲取restful接口的參數
在路由解析時會初始化 `Params`
提供Get函數:
```
Param(key string) string
```
### 獲取請求數據:
```
// Header
GetHeader(key string) string
// c.Request.Body
GetRawData() ([]byte, error)
// Cookie
Cookie(name string) (string, error)
//從GET參數中拿值,比如 /path?id=john
// 實現原理:調用系統庫:*http.Request.URL.Query()
GetQueryArray(key string) ([]string, bool)
GetQuery(key string)(string, bool)
Query(key string) string
DefaultQuery(key, defaultValue string) string
GetQueryArray(key string) ([]string, bool)
QueryArray(key string) []string
//從POST中拿數據
// 實現原理:調用系統庫:*http.Request.PostForm() 和 *http.Request.MultipartForm.Value
GetPostFormArray(key string) ([]string, bool)
PostFormArray(key string) []string
GetPostForm(key string) (string, bool)
PostForm(key string) string
DefaultPostForm(key, defaultValue string) string
// 文件
// 實現原理:調用系統庫:*http.Request.FormFile()
FormFile(name string) (*multipart.FileHeader, error)
MultipartForm() (*multipart.Form, error)
SaveUploadedFile(file *multipart.FileHeader, dst string) error
```
### 數據對象化
```
Bind(obj interface{}) error //根據Content-Type綁定數據
BindJSON(obj interface{}) error
BindQuery(obj interface{}) error
//--- Should ok, else return error
ShouldBindJSON(obj interface{}) error
ShouldBind(obj interface{}) error
ShouldBindJSON(obj interface{}) error
ShouldBindQuery(obj interface{}) error
//--- Must ok, else SetError
MustBindJSON(obj interface{}) error
```
我們仔細看看實現邏輯
```
// 首先有一個Binding接口,
//binding/binding.go:27
type Binding interface {
// 綁定器的名稱
Name() string
// 進行數據綁定
Bind(*http.Request, interface{}) error
}
// 然后有一個矩陣得到binding對象
//binding/binding.go:70
method content-type binding
-----------------------------------------------
GET * Form
* application/json JSON
* application/xml XML
* text/xml XML
* application/x-protobuf ProtoBuf
* application/x-msgpack MsgPack
* application/msgpack MsgPack
* 其他 Form
// 最后還有數據校驗,使用的是 `go-playground/validator.v8`
```
### 其他工具方法
```
ClientIP() string
ContentType() string
IsWebsocket() bool
```