php接受go返回数据,Golang: 接收GET和POST参数(示例代码)
GET 和 POST 是我们最常用的两种请求方式,今天结合前端 axios 请求库来讲一讲,如何在 golang 服务中,正确接收这两种请求的参数信息。
一、搭建一个简单的服务
首先,我们来创建一个最简单的静态页面,将 axios 引进来:
GET & POST
接下来,我们写一个简单的 golang 服务程序,在浏览器端访问这个服务时,将上面的静态页面内容返回给浏览器:
package main
import (
"log"
"fmt"
"net/http"
"html/template"
)
// 返回静态页面
func handleIndex(writer http.ResponseWriter, request *http.Request) {
t, _ := template.ParseFiles("index.html")
t.Execute(writer, nil)
}
func main() {
http.HandleFunc("/", handleIndex)
fmt.Println("Running at port 3000 ...")
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
运行上面程序,然后在浏览器中访问 localhost:3000,就可以看到一个简单的静态页面了。
二、处理 GET 请求
接下来,我们就在静态页面中添加一个 GET 请求:
axios.get('/testGet', {
params: {
id: 1,
}
}).then((response) => {
console.log(response);
});
对应地,服务端也要添加这个请求路径的处理函数:
// 处理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
", id)
fmt.Fprintf(writer, `{"code":0}`)
}
func main() {
// ...
http.HandleFunc("/testGet", handleGet)
// ...
}
重新运行程序,访问页面,服务端控制台打印如下:
GET: id=1
在接收到请求参数后,我们会返回一个 {"code":0} 的响应结果,浏览器端收到响应后,会将其转为 JS 对象,控制台打印如下:
三、处理 POST 请求
在开发中,常用的 POST 请求有两种,分别是 application/json 和 application/x-www-form-urlencoded,下面就来介绍一下这两种类型的处理方式。
先说第一种,在使用 axios 发起请求时,默认就是 application/json 类型,我们来添加一个这样的请求:
// POST数据
const postData = {
username: 'admin',
password: '123',
};
axios.post('/testPostJson', postData).then((response) => {
console.log(response);
});
同样地,我们需要在 golang 服务中添加处理函数:
// 引入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(¶ms)
fmt.Printf("POST json: username=%s, password=%s
", params["username"], params["password"])
fmt.Fprintf(writer, `{"code":0}`)
}
func main() {
// ...
http.HandleFunc("/testPostJson", handlePostJson)
// ...
}
再次运行程序,访问页面,服务端控制台打印如下:
POST json: username=admin, password=123
如果我们使用 application/x-www-form-urlencoded 这样的请求类型,就需要在发送请求时,额外添加一些配置信息:
// POST数据
const postData = {
username: 'admin',
password: '123',
};
axios.post('/testPostForm', postData, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
transformRequest: [(data) => {
const pairs = [];
Object.keys(data).forEach(key => {
pairs.push(`${key}=${data[key]}`);
});
return pairs.join('&');
}]
}).then((response) => {
console.log(response);
});
对应的服务端 golang 处理函数如下:
// 处理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
", username, password)
fmt.Fprintf(writer, `{"code":0}`)
}
func main() {
// ...
http.HandleFunc("/testPostForm", handlePostForm)
// ...
}
最后运行程序并访问,服务端控制台打印如下:
POST form-urlencoded: username=admin, password=123
四、返回JSON对象数据
前面我们的处理函数中,都返回了一个简单的 JSON 字符串,实际开发中,往往是一些数据对象,我们需要将这些数据对象以 JSON 的形式返回,下面我们就来添加一段代码:
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data Person `json:"data"`
}
// 返回数据对象的JSON数据
func handleResponseJson(writer http.ResponseWriter, request *http.Request) {
res := Response{
0,
"success",
Person{
"Jack",
20,
},
}
json.NewEncoder(writer).Encode(res)
}
func main() {
// ...
http.HandleFunc("/handleResponseJson", handleResponseJson)
// ...
}
接着,我们使用 axios 测试一下这个服务:
axios.get('/handleResponseJson').then((response) => {
console.log(response);
});
访问页面,浏览器控制台打印结果如下:
php接受go返回数据,Golang: 接收GET和POST参数(示例代码)相关推荐
- python 更新数据库历史_python 实现数据库中数据添加、查询与更新的示例代码
一.前言 最近做web网站的测试,遇到很多需要批量造数据的功能:比如某个页面展示数据条数需要达到10000条进行测试,此时手动构造数据肯定是不可能的,此时只能通过python脚本进行自动构造数据:本次 ...
- python查询数据库后更新_python 实现数据库中数据添加、查询与更新的示例代码...
一.前言 最近做web网站的测试,遇到很多需要批量造数据的功能:比如某个页面展示数据条数需要达到10000条进行测试,此时手动构造数据肯定是不可能的,此时只能通过python脚本进行自动构造数据:本次 ...
- python代码中怎么增加数据_python 实现数据库中数据添加、查询与更新的示例代码...
一.前言 最近做web网站的测试,遇到很多需要批量造数据的功能:比如某个页面展示数据条数需要达到10000条进行测试,此时手动构造数据肯定是不可能的,此时只能通过python脚本进行自动构造数据:本次 ...
- android activity之间跳转和数据传递参数,Activity跳转(有返回数据跳转)以及传递参数和回传参数...
使用Bundle在Activity之间传递数据 Bundle类是一个key-value对,是一个final类 两个Activity之间通信可以用Bundle类实现步骤: 新建一个Bundle类 Bun ...
- 足球数据【文字直播】API调用示例代码
分享[文字直播]接口调用的示例代码 import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import java ...
- 后端返回数据ios接收精度丢失问题
问题描述,通过postman调用接口返回信息拿到的BigDecimal类型的数据是正常的,后端返回给ios丢失了小数后面的值 正常应该是"price":"100.00&q ...
- html数据摘要算法,Hash函数和消息摘要算法(示例代码)
一.Hash函数 哈希函数就是能将任意长度的数据映射为固定长度的数据的函数.哈希函数返回的值被叫做哈希值.哈希码.散列,或者直接叫做哈希. 二.消息摘要 将长度不固定的消息(message)作为输入参 ...
- 足球数据【图文直播】API调用示例代码
野子电竞数据官网改版https://www.xxe.io/全新登场 import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshal ...
- vue 实现数据滚动显示_vue实现动态添加数据滚动条自动滚动到底部的示例代码...
在使用vue实现聊天页面的时候,聊天数据动态加到页面中,需要实现滚动条也自动滚动到底部.这时我找到网上有个插件 vue-chat-scroll 但是安装后发现是用不了的,报错信息如下: VM14383 ...
最新文章
- 不再写死,SpringBoot实现动态增删启停定时任务
- 数字货币 分层确定性钱包(HD Wallets)
- android 中国通信乱码问题
- MySQL无法修改字段
- 计算机主机箱外部介绍图,电脑的主机结构是怎样的 电脑主机结构图【图文】...
- 【渝粤题库】广东开放大学 电子商务安全与支付 形成性考核
- Python中矩阵库Numpy基本操作
- Silverlight使用DataGrid的模板列(DataGridTemplateColumn)实现类似TreeListView控件的效果
- H5炫酷特效系列3——瀑布流水特效
- If-Modified-Since If-None-Match
- Open3d之点云可视化
- 无名接口.php,李无名
- Android动态警示线,Android平台上辅助安全驾驶之线道侦测与偏离警示系统
- 最新版计算机知识超全题库,超全的计算机基础知识题库.doc
- python 抓取微博评论破亿_利用python实现爬取微博评论的方法
- win7网上邻居_win7系统网上邻居在哪
- ROC阳性结果还是阴性结果?
- 微信小程录制视频上传服务器,微信小程序-从相册获取图片,视频使用相机拍照,录像上传+服务器nodejs版接收-微信小程序视频上传功能-微信小程序视频上传...
- PowerPoint演示文档大瘦身
- 真空灾难:物理学最著名的未解难题之一