1.Gin返回Json
我们在开发是传送给前端的数据往往是以
json
格式发送的,具体的方法是有一下两种 (map
和结构体)
结构体返回json
// 我们可以定义一个结构体,里面定义了我们需要通过 gin web服务器返回给客户端需要的字段
type UserInfo struct {
Id uint64
Username string
Password string
Nickname string
}
当我们实例化一个结构体,并且返回的时候,可以使用context.Json
直接将结构体实例变量返回,内部会通过序列化后,返回给客户端,客户端在进行反序列化为Json
数据
r.GET("/resJson", func(c *gin.Context) {
userinfo := UserInfo{
Id: 1,
Username: "codeHope123",
Password: "qwer123",
Nickname: "CodeHope",
}
c.JSON(http.StatusOK, &userinfo)
})
curl http://127.0.0.1:8888/resJson
{"Id":1,"Username":"codeHope123","Password":"qwer123","Nickname":"CodeHope"}%
结构体json tag
配置序列化结果
定义结构体的时候,必须要保证需要序列号的字段为大写
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type UserInfo struct {
Id uint64
Username string
Password string
nickname string
}
func main() {
r := gin.Default()
r.GET("/resJson", func(c *gin.Context) {
userinfo := UserInfo{
Id: 1,
Username: "codeHope123",
Password: "qwer123",
nickname: "CodeHope",
}
c.JSON(http.StatusOK, &userinfo)
})
r.Run(":8888")
}
curl http://127.0.0.1:8888/resJson
{"Id":1,"Username":"codeHope123","Password":"qwer123"}% # 可以发现小写的并没有被序列化,因为其他包使用字段要大写导出
可以通过
json:"xx"
,定义序列化后的字段别名,比如上面返回出去的json
字段都是大些我们一半都是用小写的,就可以用这个方法去改一下!
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type UserInfo struct {
Id uint64 `json:"id"`
Username string `json:"username"`
Password string `json:"password"`
Nickname string `json:"nickname"`
}
func main() {
r := gin.Default()
r.GET("/resJson", func(c *gin.Context) {
userinfo := UserInfo{
Id: 1,
Username: "codeHope123",
Password: "qwer123",
Nickname: "CodeHope",
}
c.JSON(http.StatusOK, &userinfo)
})
r.Run(":8888")
}
curl http://127.0.0.1:8888/resJson
{"id":1,"username":"codeHope123","password":"qwer123","nickname":"CodeHope"}%
Map
返回JSON
r.GET("/resJson", func(c *gin.Context) {
c.JSON(http.StatusOK, map[string]interface{}{
"id": 1,
"username": "codeHope123",
"password": "qwer123",
"nickname": "CodeHope",
})
})
curl http://127.0.0.1:8888/resJson
{"Id":1,"Nickname":"CodeHope","Password":"qwer123","Username":"codeHope123"}%
Gin 内部为我们封装了一个
gin.H
// H is a shortcut for map[string]interface{}
type H map[string]interface{}
2.Gin返回protocol buffer
准备 protocol 相关文件
首先我们准备一个proto
文件 user.proto
// 这是protobuf的版本
syntax = "proto3";
//定义包名
option go_package="proto/user";
// 定义数据结构,message 类似golang中的struct
message User {
string name = 1; // 定义一个string类型的字段name, 序号为1
int32 age = 2; // 定义一个int32类型的字段age, 序号为2
}
~/Desktop/Markdown文档/Golang/microservice-learning-notes/test-code/gin master ± tree
.
├── go.mod
├── go.sum
├── main.go
├── tmp
│ ├── build-errors.log
│ └── main
└── user.proto
编译为go
文件
~/Desktop/Markdown文档/Golang/microservice-learning-notes/test-code/gin master ± protoc -I=. --go_out=./ user.proto
~/Desktop/Markdown文档/Golang/microservice-learning-notes/test-code/gin master ± tree
.
├── go.mod
├── go.sum
├── main.go
├── proto
│ └── user
│ └── user.pb.go
├── tmp
│ ├── build-errors.log
│ └── main
└── user.proto
3 directories, 7 files
user.pb.go
// 这是protobuf的版本
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.27.1
// protoc v3.6.1
// source: user.proto
package user
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// 定义数据结构,message 类似golang中的struct
type User struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // 定义一个string类型的字段name, 序号为1
Age int32 `protobuf:"varint,2,opt,name=age,proto3" json:"age,omitempty"` // 定义一个int32类型的字段age, 序号为2
}
func (x *User) Reset() {
*x = User{}
if protoimpl.UnsafeEnabled {
mi := &file_user_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *User) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*User) ProtoMessage() {}
func (x *User) ProtoReflect() protoreflect.Message {
mi := &file_user_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use User.ProtoReflect.Descriptor instead.
func (*User) Descriptor() ([]byte, []int) {
return file_user_proto_rawDescGZIP(), []int{0}
}
func (x *User) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *User) GetAge() int32 {
if x != nil {
return x.Age
}
return 0
}
var File_user_proto protoreflect.FileDescriptor
var file_user_proto_rawDesc = []byte{
0x0a, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x2c, 0x0a, 0x04,
0x55, 0x73, 0x65, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01,
0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x61, 0x67, 0x65, 0x18,
0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x61, 0x67, 0x65, 0x42, 0x0c, 0x5a, 0x0a, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x2f, 0x75, 0x73, 0x65, 0x72, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_user_proto_rawDescOnce sync.Once
file_user_proto_rawDescData = file_user_proto_rawDesc
)
func file_user_proto_rawDescGZIP() []byte {
file_user_proto_rawDescOnce.Do(func() {
file_user_proto_rawDescData = protoimpl.X.CompressGZIP(file_user_proto_rawDescData)
})
return file_user_proto_rawDescData
}
var file_user_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_user_proto_goTypes = []interface{}{
(*User)(nil), // 0: User
}
var file_user_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_user_proto_init() }
func file_user_proto_init() {
if File_user_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_user_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*User); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_user_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_user_proto_goTypes,
DependencyIndexes: file_user_proto_depIdxs,
MessageInfos: file_user_proto_msgTypes,
}.Build()
File_user_proto = out.File
file_user_proto_rawDesc = nil
file_user_proto_goTypes = nil
file_user_proto_depIdxs = nil
}
服务端返回 protocol
这里根据 protocol生成的代码,根据内部的结构体生成一些数据,通过
c.ProtoBuf
将数据以protocol buffer
的数据协议序列化!
package main
import (
"gin-st/proto/user"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/userProtobuffer", func(c *gin.Context) {
user := user.User{
Name: "CODEHOPE",
Age: 1222,
}
c.ProtoBuf(http.StatusOK, &user)
})
r.Run(":8888")
}
curl http://127.0.0.1:8888/userProtobuffer
CODEHOPE� % # 返回了一些无法解析的二进制代码,可以在客户端用protocol一些包去反序列化出来
客户端请求我们的接口就会拿到一些,序列化后的
protocol
协议的数据
r.GET("/parse", func(c *gin.Context) {
resp, err := http.Get("http://localhost:8888/userProtobuffer") //请求获取 protocol 协议的 二进制数据
if err != nil {
fmt.Println(err)
} else {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) //将数据读取出来放入一个 []byte切片
fmt.Println(body) // [10 8 67 79 68 69 72 79 80 69 16 198 9]
if err != nil {
fmt.Println(err)
} else {
user := user.User{}
proto.UnmarshalMerge(body, &user) // "github.com/golang/protobuf/proto" protocol 协议的反序列化方法!
c.JSON(http.StatusOK, &user)
}
}
})
这里呢!我就在同一个web
服务里面去演示解析了
看看调用反序列化结果:可以看到已经被解析出来!
curl http://127.0.0.1:8888/parse
{"name":"CODEHOPE","age":1222}%
3. Pure.JSON 原样返回html标签
可能会有需求,要我们帮忙返回一些
html
样式,标签这些,如果直接使用 JSON的话或者 map会被转译成其他字符,例如下面的案例
r.GET("/htmlTag", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"title": "<h1>标题</h1>",
"subtitle": "<h2>副标题</h2>",
"text": "<p>哈哈哈哈哈哈哈</p>",
})
})
url http://127.0.0.1:8888/htmlTag
{"subtitle":"\u003ch2\u003e副标题\u003c/h2\u003e","text":"\u003cp\u003e哈哈哈哈哈哈哈\u003c/p\u003e","title":"\u003ch1\u003e标题\u003c/h1\u003e"}%
上面的返回内容,前端web页面可能没有办法很好的去解析,这个时候就可以使用Pure.JSON
返回
r.GET("/htmlTag", func(c *gin.Context) {
c.PureJSON(http.StatusOK, gin.H{
"title": "<h1>标题</h1>",
"subtitle": "<h2>副标题</h2>",
"text": "<p>哈哈哈哈哈哈哈</p>",
})
})
curl http://127.0.0.1:8888/htmlTag
{"subtitle":"<h2>副标题</h2>","text":"<p>哈哈哈哈哈哈哈</p>","title":"<h1>标题</h1>"}