在go语言gin框架中如何处理JSON、ProtoBuf数据格式示例代码
Go  /  管理员 发布于 2个月前   124
现在不管是什么语言处理前后端数据交互大多数都是以json格式了,本文中go语言也一样,
我们知道GRPC的数据交互是以ProtoBuf格式的,下面我们来看看!
Go是如何处理json格式数据?如何处理ProtoBuf格式数据的?
代码示例:
package main
import (
"net/http"
"StudyGin/HolleGin/ch07/proto"
"github.com/gin-gonic/gin"
)
func moreJSON(c *gin.Context) {
var msg struct {
Nmae string `json:"UserName"`
Message string
Number int
}
msg.Nmae = "zongscan.com"
msg.Message = "This is a test of JSOM"
msg.Number = 1
c.JSON(http.StatusOK, msg)
}
//使用ProtoBuf
func returnProto(c *gin.Context) {
course := []string{"python", "golang", "php", "c++"}
user := &proto.Teacher{
Name: "ice_moss",
Course: course,
}
//返回protobuf
c.ProtoBuf(http.StatusOK, user)
}
//使用结构体和JSON对结构体字段进行标签,使用protobuf返回值
func main() {
router := gin.Default()
router.GET("/moreJSON", moreJSON)
router.GET("/someProtoBuf", returnProto)
router.Run(":8083")
}
测试一下
访问1:
http://localhost:8083/moreJSON
返回:
{"UserName":"zongscan.com","Message":"This is a test of JSOM","Number":1}
访问2:
http://localhost:8083//someProtoBuf
返回:会将someProtoBuf返回的数据下载
如果是使用GRPC的话,直接使用GRPC中的方法将数据接收解析出来就ok了
路人 在
php中使用hyperf框架调用讯飞星火大模型实现国内版chatgpt功能示例中评论 教程很详细,如果加个前端chatgpt对话页面就完美了..博主 在
科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 @ mashrdn 多切换几个节点测试,免费ssr是没那么稳..mashrdn 在
科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 V2rayn免费节点添加上去了,youtobe无法打开网页,是怎么回事..张伟 在
科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 3q!有用,不过免费节点隔天就要去git上复制新的导进去..博主 在
科学上网翻墙访问Google , 上外网神器佛跳墙VPN(永久免费)使用流程步骤中评论 该篇教程已不能用了,告知大家,免的老有老铁问我!..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号