Golang如何接收前端的参数


当前第2页 返回上一页

一、Golang接收前端GET请求的参数

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

// 处理GET请求

func handleGet(writer http.ResponseWriter, request *http.Request) {

    query := request.URL.Query()

 

    // 第一种方式

    // id := query["id"][0]

 

    // 第二种方式

    id := query.Get("id")

 

    fmt.Printf("GET: id=%s\n", id)

 

    fmt.Fprintf(writer, `{"code":0}`)

}

 

func main() {

    // ...

 

    http.HandleFunc("/testGet", handleGet)

 

    // ...

}

服务端打印如下:

1

GET: id=1

二、Golang接收前端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

27

28

29

// 引入encoding/json包

import (

    // ...

    "encoding/json"

)

 

// 处理application/json类型的POST请求

func handlePostJson(writer http.ResponseWriter, request *http.Request) {

    // 根据请求body创建一个json解析器实例

    decoder := json.NewDecoder(request.Body)

 

    // 用于存放参数key=value数据

    var params map[string]string

 

    // 解析参数 存入map

    decoder.Decode(&params)

 

    fmt.Printf("POST json: username=%s, password=%s\n", params["username"], params["password"])

 

    fmt.Fprintf(writer, `{"code":0}`)

}

 

func main() {

    // ...

 

    http.HandleFunc("/testPostJson", handlePostJson)

 

    // ...

}

服务端打印如下:

1

POST json: username=admin, password=123

更多golang知识请关注PHP中文网golang教程栏目。

以上就是Golang如何接收前端的参数的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

golang有什么用途?

go语言学习(五):通道的用法

聊聊storagetapper的pipe

go实现ssh远程执行命令

go语言基础

golang 在 runtime 中的一些骚东西

常见的 go 处理字符串的技巧

涂鸦智能 dubbo-go 亿级流量的实践与探索

golang可以热更新吗

now扩展-go的时间工具箱

更多相关阅读请进入《golang》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...