正在學習go語言,看了一段時間的文檔,想自己寫個服務器,在獲取接口數據的時候發現獲取數據,格式爲"form-data"的數據最簡單,</span>
傳入post json數據:{"username":"","password":"123456"}
<span style="font-family: Arial, Helvetica, sans-serif;">req.PostForm</span>
req.Header.Get("Content-Type")
req.Host
req.Form
req.FormValue("username")
req.FormValue("password")
獲取"application/json"的時候,需要處理一下(以下只獲取string):
package utils
import (
"bytes"
"io/ioutil"
"net/http"
)
/**
獲取body的data(json)轉換爲string
*字節數據轉string
*/
func GetDataString(req *http.Request) string {
result, err := ioutil.ReadAll(req.Body)
if err != nil {
return "{\"code\": 1,\"msg\": \"failed\"}"
} else {
return bytes.NewBuffer(result).String()
}
}
獲取"application/json"的時候,需要處理一下(以下只獲取json到map):
需要引入的包,"io/ioutil","net/http","encoding/json"
var user map[string]interface{}
body, _ := ioutil.ReadAll(req.Body)
json.Unmarshal(body, &user)
fmt.Println("獲取json中的username:", user["username"])
fmt.Println("獲取json中的password:", user["password"].(string)) //轉字符串通過len(password)!=0判斷長度
獲取的數據對比:
byte[]
[123 34 117 115 101 114 110 97 109 101 34 58 34 115 121 115 116 101 109 34 44 34 112 97 115 115 119 111 114 100 34 58 34 49 50 51 52 53 54 34 125]
string{"username":"system","password":"123456"}
map
map[username:system password:123456]