Protocol Buffers Response
Learn how to send Protocol Buffers responses in Iris.
Basic Protobuf Response
go
package main
import (
"github.com/kataras/iris/v12"
"google.golang.org/protobuf/proto"
)
// person.proto
message Person {
string name = 1;
int32 age = 2;
string email = 3;
}
func main() {
app := iris.New()
app.Get("/protobuf", func(ctx iris.Context) {
person := &Person{
Name: "John Doe",
Age: 25,
Email: "john@example.com",
}
ctx.Protobuf(person)
})
app.Listen(":8080")
}
Custom Protobuf Encoding
go
app.Get("/custom", func(ctx iris.Context) {
data := &MyMessage{
Field1: "value1",
Field2: 42,
}
// Marshal manually
bytes, err := proto.Marshal(data)
if err != nil {
ctx.StopWithError(iris.StatusInternalServerError, err)
return
}
ctx.ContentType("application/x-protobuf")
ctx.Write(bytes)
})
Protobuf Collection
go
// people.proto
message People {
repeated Person people = 1;
}
app.Get("/people", func(ctx iris.Context) {
people := &People{
People: []*Person{
{Name: "John", Age: 25},
{Name: "Jane", Age: 30},
},
}
ctx.Protobuf(people)
})
Best Practices
Structure:
- Define schemas
- Use proper types
- Document messages
- Handle versions
- Validate output
Performance:
- Enable compression
- Cache responses
- Monitor size
- Handle timeouts
- Optimize encoding
Security:
- Validate input
- Set headers
- Handle errors
- Monitor usage
- Control access
Maintenance:
- Document schemas
- Update messages
- Monitor changes
- Regular testing
- Review security