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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
| // main.go
package main
import (
"bytes"
"fmt"
"log"
"net/http"
"proto/message"
"github.com/gin-gonic/gin"
"github.com/gogo/protobuf/jsonpb"
jsoniter "github.com/json-iterator/go"
"google.golang.org/protobuf/proto"
)
func main() {
msg := message.UserInfo{UserList: []*message.UserInfo_User{{Username: "test"}}}
msg.UserList = append(msg.UserList, &message.UserInfo_User{Username: "test1"})
// go message 可以直接序列化为 json byte
byt, err := jsoniter.Marshal(&msg)
if err != nil {
log.Fatal("cannot parse to json")
}
fmt.Println("json result: ", string(byt))
// 可以将 json 对象反序列化为 go message 对象
msg1 := &message.UserInfo{}
err = jsonpb.Unmarshal(bytes.NewReader(byt), msg1)
if err != nil {
log.Fatal("parse failed, ", err)
}
fmt.Printf("parsed: %+v
", msg1)
// protobuf 本身的字符串表征
msg1Str := msg1.String()
fmt.Println("msg1 string, ", msg1Str)
// protobuf 序列化
out, err := proto.Marshal(msg1)
fmt.Println("msg1 marshal result is, ", string(out))
msg2 := message.UserInfo{}
// 将序列化后的结果,反序列化为 message 对象
proto.Unmarshal(out, &msg2)
fmt.Printf("unmarshal result msg2 is: %+v
", &msg2)
engine := gin.Default()
engine.GET("check", func(c *gin.Context) {
// message 对象可以直接用来作为接口的返回值
c.JSON(http.StatusOK, &msg1)
})
srv := &http.Server{}
srv.Addr = "0.0.0.0:9988"
srv.Handler = engine
srv.ListenAndServe()
}
// proto/user.proto
syntax = "proto3";
package user_info;
// 对于 golang 的使用说,这里的 go_package 是必须的。表述的是编译后的模块名
option go_package = "./message";
message UserInfo{
message User{
string username = 1;
uint32 age = 2;
string graduate = 3;
}
repeated User user_list = 1;
}
|