GO接收GET/POST参数及发送GET/POST请求的实例详解
作者:qq_27312939 时间:2024-02-08 10:27:49
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://blog.csdn.net/qq_27312939/article/details/110632297
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python实现的数据结构与算法之队列详解
![](https://img.aspxhome.com/file/2023/2/88872_0s.png)
图文详解Go中的channel
![](https://img.aspxhome.com/file/2023/6/134386_0s.jpg)
详解如何通过Mysql的二进制日志恢复数据库数据
![](https://img.aspxhome.com/file/2023/8/79998_0s.png)
python用字典统计单词或汉字词个数示例
如何用Anaconda搭建虚拟环境并创建Django项目
![](https://img.aspxhome.com/file/2023/0/80800_0s.png)
Python中re.findall()用法详解
![](https://img.aspxhome.com/file/2023/1/61191_0s.png)
关于PyTorch环境配置及安装教程(Windows10)
![](https://img.aspxhome.com/file/2023/8/133368_0s.png)
go项目打包部署的完整步骤
![](https://img.aspxhome.com/file/2023/8/127338_0s.png)
XML编程实例: ASP+XML打造留言本
一文搞懂python 中的迭代器和生成器
在Python的框架中为MySQL实现restful接口的教程
![](https://img.aspxhome.com/file/2023/0/107100_0s.png)
利用python爬取m3u8格式视频的具体实现
![](https://img.aspxhome.com/file/2023/7/103177_0s.jpg)
Python机器学习性能度量利用鸢尾花数据绘制P-R曲线
![](https://img.aspxhome.com/file/2023/5/82905_0s.png)
如何对PHP程序中的常见漏洞进行攻击
sql无效字符 执行sql语句报错解决方案
Python+OpenCV实现在图像上绘制矩形
![](https://img.aspxhome.com/file/2023/4/66894_0s.jpg)
mysql表分区的使用与底层原理详解
Tensorflow全局设置可见GPU编号操作
vue中的 $slot 获取插槽的节点实例
![](https://img.aspxhome.com/file/2023/5/130205_0s.jpg)