Protocol Buffers Request
Learn how to handle Protocol Buffers requests in Iris.
Basic Protobuf Handling
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.Post("/protobuf", func(ctx iris.Context) {
var person Person
if err := ctx.ReadProtobuf(&person); err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
ctx.Protobuf(iris.Map{
"received": &person,
})
})
app.Listen(":8080")
}
Protobuf Validation
go
func validatePerson(person *Person) error {
if person.Name == "" {
return fmt.Errorf("name is required")
}
if person.Age < 0 || person.Age > 130 {
return fmt.Errorf("age must be between 0 and 130")
}
if person.Email == "" {
return fmt.Errorf("email is required")
}
return nil
}
app.Post("/validate", func(ctx iris.Context) {
var person Person
if err := ctx.ReadProtobuf(&person); err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
if err := validatePerson(&person); err != nil {
ctx.StopWithProblem(iris.StatusBadRequest, iris.NewProblem().
Title("Validation Error").
DetailErr(err))
return
}
ctx.Protobuf(iris.Map{
"message": "Protobuf validated successfully",
"person": &person,
})
})
Custom Protobuf Handling
go
app.Post("/custom", func(ctx iris.Context) {
data, err := io.ReadAll(ctx.Request().Body)
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
var message MyMessage
if err := proto.Unmarshal(data, &message); err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
ctx.Protobuf(iris.Map{
"message": &message,
})
})
Best Practices
Schema:
- Define clear messages
- Use proper types
- Version messages
- Document fields
- Handle updates
Validation:
- Validate required fields
- Check types
- Handle defaults
- Set limits
- Document requirements
Performance:
- Use appropriate buffer
- Handle large messages
- Monitor memory
- Implement timeouts
- Clean resources
Error Handling:
- Handle parsing errors
- Validate messages
- Log issues
- Document errors
- Test edge cases