Protocol Buffers
Content-Type: "application/x-protobuf"
Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages. https://developers.google.com/protocol-buffers​
The Context.Protobuf(proto.Message) is the method which sends protos to the client. It accepts a proto.Message value.
Note: Iris is using the newest version of the Go protocol buffers implementation. Read more about it at The Go Blog: A new Go API for Protocol Buffers.
The methods you need to know when working with Protocol Buffers are the following:
1
// Protobuf writes a proto message to the client,
2
// which should be able to read and parse protos too.
3
Protobuf(v proto.Message) (int, error)
4
// ReadProtobuf binds the request body
5
// to the proto message.
6
ReadProtobuf(ptr proto.Message) error
Copied!
1
// JSON renders a proto.Message compatible value as JSON.
2
JSON(v interface{}, options ...JSON) (int, error)
3
// ReadJSONProtobuf reads a JSON body request
4
// into the given "ptr" proto.Message.
5
ReadJSONProtobuf(ptr proto.Message, opts ...protojson.UnmarshalOptions) error
Copied!
1
type JSON struct {
2
// [...other fields]
3
Proto ProtoMarshalOptions
4
}
5
​
6
type ProtoMarshalOptions struct {
7
// Multiline specifies whether the marshaler
8
// should format the output in
9
// indented-form with every textual element
10
// on a new line.
11
// If Indent is an empty string,
12
// then an arbitrary indent is chosen.
13
Multiline bool
14
​
15
// Indent specifies the set of indentation
16
// characters to use in a multiline
17
// formatted output such that every entry
18
// is preceded by Indent and
19
// terminated by a newline. If non-empty,
20
// then Multiline is treated as true.
21
// Indent can only be composed of space or tab characters.
22
Indent string
23
​
24
// AllowPartial allows messages that have
25
// missing required fields to marshal
26
// without returning an error.
27
// If AllowPartial is false (the default),
28
// Marshal will return error if there are
29
// any missing required fields.
30
AllowPartial bool
31
​
32
// UseProtoNames uses proto field name
33
// instead of lowerCamelCase name in JSON
34
// field names.
35
UseProtoNames bool
36
​
37
// UseEnumNumbers emits enum values as numbers.
38
UseEnumNumbers bool
39
​
40
// EmitUnpopulated specifies whether to emit unpopulated fields.
41
// It does not emit unpopulated oneof fields
42
// or unpopulated extension fields.
43
// The JSON value emitted for unpopulated fields are as follows:
44
// ╔═══════╀════════════════════════════
45
// β•‘ JSON β”‚ Protobuf field
46
// ╠═══════β•ͺ════════════════════════════
47
// β•‘ false β”‚ proto3 boolean fields
48
// β•‘ 0 β”‚ proto3 numeric fields
49
// β•‘ "" β”‚ proto3 string/bytes fields
50
// β•‘ null β”‚ proto2 scalar fields
51
// β•‘ null β”‚ message fields
52
// β•‘ [] β”‚ list fields
53
// β•‘ {} β”‚ map fields
54
// β•šβ•β•β•β•β•β•β•β•§β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
55
EmitUnpopulated bool
56
}
Copied!

Example

Let's create a simple application that showcases the use case of all of the above methods.
1
β”‚ main.go
2
β”‚ go.mod
3
β”‚ go.sum
4
└───protos
5
β”‚ hello.proto
6
β”‚ hello.pb.go
Copied!
Navigate to the project's directory, create your go module: $ go mod init app.
The protos/hello.proto contents should look like that:
1
syntax = "proto3";
2
​
3
package protos;
4
​
5
option go_package = "./protos";
6
​
7
message HelloRequest {
8
string name = 1;
9
}
10
​
11
message HelloReply {
12
string message = 1;
13
}
Copied!
To generate the protos/hello.pb.go file follow the commands below:
    1.
    Install the protoc-gen-go tool.
1
$ go get -u google.golang.org/protobuf/cmd/[email protected]
Copied!
    1.
    Generate proto
1
$ protoc -I protos/ protos/hello.proto --go_out=.
Copied!
Now, create the main.go file and copy-paste the following code:
1
package main
2
​
3
import (
4
"app/protos"
5
​
6
"github.com/kataras/iris/v12"
7
)
8
​
9
func main() {
10
app := iris.New()
11
​
12
app.Get("/", send)
13
app.Get("/json", sendAsJSON)
14
app.Post("/read", read)
15
app.Post("/read_json", readFromJSON)
16
​
17
app.Listen(":8080")
18
}
19
​
20
func send(ctx iris.Context) {
21
response := &protos.HelloReply{Message: "Hello, World!"}
22
ctx.Protobuf(response)
23
}
24
​
25
func sendAsJSON(ctx iris.Context) {
26
response := &protos.HelloReply{Message: "Hello, World!"}
27
options := iris.JSON{
28
Proto: iris.ProtoMarshalOptions{
29
AllowPartial: true,
30
Multiline: true,
31
Indent: " ",
32
},
33
}
34
​
35
ctx.JSON(response, options)
36
}
37
​
38
func read(ctx iris.Context) {
39
var request protos.HelloRequest
40
​
41
err := ctx.ReadProtobuf(&request)
42
if err != nil {
43
ctx.StopWithError(iris.StatusBadRequest, err)
44
return
45
}
46
​
47
ctx.Writef("HelloRequest.Name = %s", request.Name)
48
}
49
​
50
func readFromJSON(ctx iris.Context) {
51
var request protos.HelloRequest
52
​
53
err := ctx.ReadJSONProtobuf(&request)
54
if err != nil {
55
ctx.StopWithError(iris.StatusBadRequest, err)
56
return
57
}
58
​
59
ctx.Writef("HelloRequest.Name = %s", request.Name)
60
}
Copied!
If you want to learn about Iris gRPC support, please navigate through the mvc/grpc section instead.
Last modified 1yr ago
Export as PDF
Copy link
Contents
Example