download protoc-3.14.0-win64.zip
unzip, add to env variable
go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.26
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.1
helloworld.proto
syntax = "proto3"; option go_package = "./;helloworld"; // helloworld is the package name message HelloRequest { string name = 1; // 1是编号不是值 int32 age = 2; repeated string courses = 3; }
generate source code: cd to proto folder protoc --go_out=. helloworld.proto
helloworld.pb.go:
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.14.0 // source: helloworld.proto package helloworld
quick start and test the performance
package main import ( helloworld "GoProjects/helloworld/proto" "encoding/json" "fmt" "github.com/golang/protobuf/proto" ) type Hello struct { Name string `json:"name"` Age int32 `json:"age"` Courses []string `json:"courses"` } func main() { // compare the compression rate of proto with json req := helloworld.HelloRequest{Name: "bobby", Age: 12, Courses: []string{"miminan", "sss", "qqq"}} rsp, _ := proto.Marshal(&req) fmt.Println(len(rsp)) // test unmarshal newReq := helloworld.HelloRequest{} _ = proto.Unmarshal(rsp, &newReq) fmt.Println(newReq.Name) // json JsonStruct := Hello{Name: "zhuzhu", Age: 12, Courses: []string{"miminan", "sss", "qqq"}} JsonRsp, _ := json.Marshal(JsonStruct) fmt.Println(len(JsonRsp)) }