Golang: 接收GET和POST引數
GET 和 POST 是我們最常用的兩種請求方式,今天講一講如何在 golang 服務中,正確接收這兩種請求的引數資訊,
處理GET請求
1.1 接收GET請求
//接收GET請求
func Get(writer http.ResponseWriter , request *http.Request) {
query := request.URL.Query()
// 第一種方式
// id := query["id"][0]
// 第二種方式
id := query.Get("id")
log.Printf("GET: id=%s\n", id)
fmt.Fprintf(writer, `{"code":0}`)
}
func main(){
http.HandleFunc("/get", Get)
log.Println("Running at port 9999 ...")
err := http.ListenAndServe(":9999", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
Postman 發起get請求

重新運行程式,請求Postman,服務端控制臺列印如下:
2020/12/04 11:33:55 Running at port 9999 ...
2020/12/04 11:34:09 GET: id=123
1.2 接收GET請求
func Get(writer http.ResponseWriter , request *http.Request) {
result := make(map[string]string)
keys := request.URL.Query()
for k, v := range keys {
result[k] = v[0]
}
log.Println(result)
}
func main(){
http.HandleFunc("/get", Get)
log.Println("Running at port 9999 ...")
err := http.ListenAndServe(":9999", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
重新運行程式,請求Postman,服務端控制臺列印如下:
2020/12/04 12:37:17 Running at port 9999 ...
2020/12/04 12:37:21 map[id:123 name:sina]
需要注意的是,這里的req.URL.Query()回傳的是陣列,因為go可以接收id=1&id=2這樣形式的引數并放到同一個key下
接收POST請求
在開發中,常用的 POST 請求有兩種,分別是 application/json 和 application/x-www-form-urlencoded,下面就來介紹一下這兩種型別的處理方式,
1.1 接收application/x-www-form-urlencoded型別的POST請求
func handlePostForm(writer http.ResponseWriter, request *http.Request) {
request.ParseForm()
// 第一種方式
// username := request.Form["username"][0]
// password := request.Form["password"][0]
// 第二種方式
username := request.Form.Get("username")
password := request.Form.Get("password")
fmt.Printf("POST form-urlencoded: username=%s, password=%s\n", username, password)
fmt.Fprintf(writer, `{"code":0}`)
}
func main(){
http.HandleFunc("/handlePostForm", handlePostForm)
log.Println("Running at port 9999 ...")
err := http.ListenAndServe(":9999", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
Postman 發起x-www-form-urlencoded請求

重新運行程式,請求Postman,服務端控制臺列印如下:
2020/12/04 12:44:32 Running at port 9999 ...
POST form-urlencoded: username=李四, password=12
1.2 接收application/x-www-form-urlencoded型別的POST請求
func PostForm(w http.ResponseWriter, r *http.Request) {
var result = make(map[string]string)
r.ParseForm()
for k,v := range r.PostForm {
if len(v) < 1 { continue }
result[k] = v[0]
}
log.Println(result)
}
func main(){
http.HandleFunc("/PostForm", PostForm)
log.Println("Running at port 9999 ...")
err := http.ListenAndServe(":9999", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
重新運行程式,請求Postman,服務端控制臺列印如下:
2020/12/04 12:49:40 Running at port 9999 ...
2020/12/04 12:49:45 map[password:12 username:李四]
2 處理 application/json 請求
實際開發中,往往是一些資料物件,我們需要將這些資料物件以 JSON 的形式回傳,下面我們就來添加一段代碼:
JSON 結構
比如,請求了手機歸屬地的介面,json 資料回傳如下:
{
"resultcode": "200",
"reason": "Return Successd!",
"result": {
"province": "浙江",
"city": "杭州",
"areacode": "0571",
"zip": "310000",
"company": "中國移動",
"card": ""
}
}
思路是這樣的:
1.先將 json 轉成 struct,
2.然后 json.Unmarshal() 即可,
json 轉 struct ,自己手寫就太麻煩了,有很多在線的工具可以直接用,我用的這個:
https://mholt.github.io/json-to-go/
在左邊貼上 json 后面就生成 struct 了,
用代碼實作下:
//AutoGenerated 結構體
type AutoGenerated struct {
Resultcode string `json:"resultcode"`
Reason string `json:"reason"`
Result struct {
Province string `json:"province"`
City string `json:"city"`
Areacode string `json:"areacode"`
Zip string `json:"zip"`
Company string `json:"company"`
Card string `json:"card"`
} `json:"result"`
}
func PostJson(w http.ResponseWriter, r *http.Request ) {
body ,err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println( err)
}
log.Printf("%s",body)
var data AutoGenerated
json.Unmarshal([]byte(body),&data)
//Json結構回傳
json,_ := json.Marshal(data)
w.Write(json)
}
func main(){
http.HandleFunc("/PostJson", PostJson)
log.Println("Running at port 9999 ...")
err := http.ListenAndServe(":9999", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
Postman 發起application/json 請求

重新運行程式,訪問頁面,服務端控制臺列印如下:
2020/12/04 12:57:01 {
"resultcode": "200",
"reason": "Return Successd!",
"a":"dd",
"result": {
"province": "浙江",
"city": "杭州",
"areacode": "0571",
"zip": "310000",
"company": "中國移動",
"card": "33"
}
}
歡迎轉載,轉載請注明出處,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/230316.html
標籤:其他
下一篇:html的行內元素與塊級元素總結
