TA的每日心情 | 无聊 2019-6-2 14:11 |
---|
签到天数: 4 天 [LV.2]圆转纯熟

帖子管理员
  
- 积分
- 124347
|
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"
- }
- }
复制代码 到此这篇关于GO接收GET/POST参数及发送GET/POST请求的文章就介绍到这了,更多相关GO接收GET/POST参数内容请搜索咔叽论坛以前的文章或继续浏览下面的相关文章希望大家以后多多支持咔叽论坛!
原文地址:https://www.jb51.net/article/201529.htm |
|