記錄一下,用golang實現一個靜態資源容器,膜拜下強人
http.Handle("/", http.FileServer(http.Dir(currentPath+"/static/")))
非常好用,有機會,試一下其他的框架
PS,Golang對於不同header的解析方法不一樣啊……
在這里做個總結記錄一下:
1. 普通的表單提交
// ParseForm populates r.Form and r.PostForm.
// For other HTTP methods, or when the Content-Type is not
// application/x-www-form-urlencoded, the request Body is not read, and
// r.PostForm is initialized to a non-nil, empty value.
func (r *Request) ParseForm() error
先使用 ParseForm()解析 request 后,再讀取參數(application/x-www-form-urlencoded)
2. 傳文件使用的表單提交
multipart/form-data
同樣是表單提交,解析 request 的方式和 application/x-www-form-urlencoded 完全不一樣,也是本次開發踩的印象最深的坑。
如果要獲取 form-data 中的參數,在已知 key 的情況下,
code = r.FormValue("code")
3. application/json
和1一樣是最常用,貼在這里做個記錄:
err := json.NewDecoder(r.Body).Decode(m)
if nil != err {
w.WriteHeader(400)
logs.Error("Illegal params: ", m)
}
定義出 json 串的結構體,一個key都不能少,就可以通過 Decoder 獲取參數了
4. 發表單請求比較優雅的方式:
param := url.Values{}
param.Set("client_id", clientId)
param.Set("client_secret", clientSecret)
param.Set("grant_type", grantType)
param.Set("code", code)
param.Set("response_type", "code")
param.Set("redirect_uri", redirectUri)
fmt.Println(param)
logs.Debug("The params is ", param)
req, err := http.NewRequest("POST", passportUrl, bytes.NewBufferString(param.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")