GO接收GET/POST参数及发送GET/POST请求的实例详解

目录

Golang: 接收GETPOST参数

GET 和 POST 是我们最常用的两种请求方式,今天讲一讲如何在 golang 服务中,正确接收这两种请求的参数信息。

处理GET请求

1.1 接收GET请求

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

//接收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,服务端控制台打印如下:

1.2 接收GET请求

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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,服务端控制台打印如下:

需要注意的是,这里的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请求

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

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,服务端控制台打印如下:

1.2 接收application/x-www-form-urlencoded类型的POST请求

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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,服务端控制台打印如下:

2 处理 application/json 请求

实际开发中,往往是一些数据对象,我们需要将这些数据对象以 JSON 的形式返回,下面我们就来添加一段代码:

JSON 结构
比如,请求了手机归属地的接口,json 数据返回如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

{

"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 了。

用代码实现下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

//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"`

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

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 请求

重新运行程序,访问页面,服务端控制台打印如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

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://blog.csdn.net/qq_27312939/article/details/110632297

本文链接:https://my.lmcjl.com/post/15159.html

展开阅读全文

4 评论

留下您的评论.