在沒有任何框架的加持下,如果客戶端(前端)傳遞過來的數據類型是:text/plain 。
// 請求頭
Content-Type: text/plain;charset=UTF-8
Go 的解析方式是:
import (
"io/ioutil"
...
)
func apiHandler(w http.ResponseWriter, r *http.Request) {
content, _ := ioutil.ReadAll(r.Body)
...
}
使用 io/ioutil 包的好處在於,你不需要知道 content 長度爲多少。否則處理方式爲:
content := make([]byte, r.ContentLength)
r.Body.Read(content)
代碼多了一丟丟。