SlideShare a Scribd company logo
PROTOBUF & CODE GENERATION
2016, BY MANFRED TOURON (@MOUL)
OVERVIEW
> go-kit is an amazing framework to develop strong
micro services
> but it requires a lot of boilerplate code
> return on experience on go-kit boilerplate code
generation
PROTOBUF?
> limited to exchanges (methods and models)
> extendable with plugins
> contract-based
> universal
CODE GENERATION?
> the good old ./generate.sh bash script
> go:generate
> make
> protobuf + protoc-gen-gotemplate
GO-KIT
> protobuf-first, rpc-first service framework in Golang
> abstract services, endpoints, transports
> requires a lot of boilerplate code in multiple packages
EXAMPLE: session.proto
syntax = "proto3";
package session;
service SessionService {
rpc Login(LoginRequest) returns (LoginResponse) {}
}
message LoginRequest {
string username = 1;
string password = 2;
}
message LoginResponse {
string token = 1;
string err_msg = 2;
}
EXAMPLE: session.go
package sessionsvc
import (
"fmt"
"golang.org/x/net/context"
pb "github.com/moul/protoc-gen-gotemplate/examples/go-kit/services/session/gen/pb"
)
type Service struct{}
func New() pb.SessionServiceServer {
return &Service{}
}
func (svc *Service) Login(ctx context.Context, in *pb.LoginRequest) (*pb.LoginResponse, error) {
// custon code here
return nil, fmt.Errorf("not implemented")
}
EXAMPLE: {{.File.Package}}/gen/transports/http/http.go.tmpl
// source: templates/{{.File.Package}}/gen/transports/http/http.go.tmpl
package {{.File.Package}}_httptransport
import (
gokit_endpoint "github.com/go-kit/kit/endpoint"
httptransport "github.com/go-kit/kit/transport/http"
endpoints "github.com/moul/protoc-gen-gotemplate/examples/go-kit/services/{{.File.Package}}/gen/endpoints"
pb "github.com/moul/protoc-gen-gotemplate/examples/go-kit/services/{{.File.Package}}/gen/pb"
)
// result: services/user/gen/transports/http/http.go
package user_httptransport
import (
gokit_endpoint "github.com/go-kit/kit/endpoint"
httptransport "github.com/go-kit/kit/transport/http"
endpoints "github.com/moul/protoc-gen-gotemplate/examples/go-kit/services/user/gen/endpoints"
pb "github.com/moul/protoc-gen-gotemplate/examples/go-kit/services/user/gen/pb"
)
EXAMPLE: {{.File.Package}}/gen/transports/http/http.go.tmpl
// source: templates/{{.File.Package}}/gen/transports/http/http.go.tmpl
{{range .Service.Method}}
func Make{{.Name}}Handler(ctx context.Context, svc pb.{{$file.Package | title}}ServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server {
return httptransport.NewServer(
ctx,
endpoint,
decode{{.Name}}Request,
encode{{.Name}}Response,
[]httptransport.ServerOption{}...,
)
}
{{end}}
// result: services/user/gen/transports/http/http.go
func MakeGetUserHandler(ctx context.Context, svc pb.UserServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server {
return httptransport.NewServer(
ctx,
endpoint,
decodeGetUserRequest,
encodeGetUserResponse,
[]httptransport.ServerOption{}...,
)
}
EXAMPLE: {{.File.Package}}/gen/transports/http/http.go.tmpl
// source: templates/{{.File.Package}}/gen/transports/http/http.go.tmpl
func RegisterHandlers(ctx context.Context, svc pb.{{$file.Package | title}}ServiceServer, mux *http.ServeMux, endpoints endpoints.Endpoints) error {
{{range .Service.Method}}
log.Println("new HTTP endpoint: "/{{.Name}}" (service={{$file.Package | title}})")
mux.Handle("/{{.Name}}", Make{{.Name}}Handler(ctx, svc, endpoints.{{.Name}}Endpoint))
{{end}}
return nil
}
// result: services/user/gen/transports/http/http.go
func RegisterHandlers(ctx context.Context, svc pb.UserServiceServer, mux *http.ServeMux, endpoints endpoints.Endpoints) error {
log.Println("new HTTP endpoint: "/CreateUser" (service=User)")
mux.Handle("/CreateUser", MakeCreateUserHandler(ctx, svc, endpoints.CreateUserEndpoint))
log.Println("new HTTP endpoint: "/GetUser" (service=User)")
mux.Handle("/GetUser", MakeGetUserHandler(ctx, svc, endpoints.GetUserEndpoint))
return nil
}
protoc --gogo_out=plugins=grpc:. ./services/*/*.proto
protoc --gotemplate_out=template_dir=./templates:services ./
services/*/*.proto
Protobuf & Code Generation + Go-Kit
3 SERVICES
6 METHODS
149 CUSTOM LINES
1429 GENERATED LINES
BUSINESS FOCUS
GENERATION USAGES
> go-kit boilerplate (see examples/go-kit)
> k8s configuration
> Dockerfile
> documentation
> unit-tests
> fun
PROS
> small custom codebase
> templates shipped with code
> hardly typed, no reflects
> genericity
> contrat terms (protobuf) respected
> not limited to a language
CONS
> the author needs to write its own templates
> sometimes difficult to generate valid code
> not enough helpers around the code generation yet
IMPROVEMENT IDEAS
> Support protobufs extensions (i.e, annotations.probo)
> Generate one file from multiple services
> Add more helpers around the code generation
CONCLUSION
> Useful to keep everything standard
> The awesomeness of go-kit without the hassle of
writing boilerplate code
> Always up-to-date with the contracts
QUESTIONS?GITHUB.COM/MOUL/PROTOC-GEN-
GOTEMPLATE
@MOUL

More Related Content

PDF
用 Go 語言打造多台機器 Scale 架構
PDF
SVN Hook
PDF
Android Libs - Retrofit
KEY
Study2study#4 nginx conf_1_24
PDF
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
DOCX
Oop lab report
PDF
OpenResty TCP 服务代理和动态路由
PDF
多要素認証やSMSマーケティングを支えるテレフォニーAPI活用入門
用 Go 語言打造多台機器 Scale 架構
SVN Hook
Android Libs - Retrofit
Study2study#4 nginx conf_1_24
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
Oop lab report
OpenResty TCP 服务代理和动态路由
多要素認証やSMSマーケティングを支えるテレフォニーAPI活用入門

What's hot (20)

PDF
Profiling and optimizing go programs
PDF
Tomáš Čorej - OpenSSH
PDF
How to make a large C++-code base manageable
ODP
Perl - laziness, impatience, hubris, and one liners
PPT
Владимир Мигуро "Дао Node.js"
PDF
Quicli - From zero to a full CLI application in a few lines of Rust
KEY
Streams are Awesome - (Node.js) TimesOpen Sep 2012
PDF
3 rd animation
PDF
WebSockets, Unity3D, and Clojure
PDF
XoxzoテレフォニーAPI入門2017
PDF
初心者のためのPythonによるWebAPI活用方入門
PDF
Let's Go-lang
PDF
Node.js Stream API
PDF
Go破壊
PDF
ClojureScript interfaces to React
PDF
Nessus scan report using microsoft patchs scan policy - Tareq Hanaysha
PDF
TOROS: Python Framework for Recommender System
PPTX
Highload осень 2012 лекция 1
PDF
Linux fundamental - Chap 14 shell script
ODP
Hackerspace PostgreSQL Atolyesi - 3
Profiling and optimizing go programs
Tomáš Čorej - OpenSSH
How to make a large C++-code base manageable
Perl - laziness, impatience, hubris, and one liners
Владимир Мигуро "Дао Node.js"
Quicli - From zero to a full CLI application in a few lines of Rust
Streams are Awesome - (Node.js) TimesOpen Sep 2012
3 rd animation
WebSockets, Unity3D, and Clojure
XoxzoテレフォニーAPI入門2017
初心者のためのPythonによるWebAPI活用方入門
Let's Go-lang
Node.js Stream API
Go破壊
ClojureScript interfaces to React
Nessus scan report using microsoft patchs scan policy - Tareq Hanaysha
TOROS: Python Framework for Recommender System
Highload осень 2012 лекция 1
Linux fundamental - Chap 14 shell script
Hackerspace PostgreSQL Atolyesi - 3
Ad

Viewers also liked (20)

PPTX
排队排队--kafka
PDF
"Clean" Architecture
PDF
iOS Zagreb Meetup #02 - Clean architecture in iOS apps (Leonard Beus @ Five)
PPTX
PDF
Infinum iOS Talks #4 - Making our VIPER more reactive
PDF
맛만 보자 Finagle이란
PPTX
java thrift
PPTX
Microservices in the Enterprise
PPTX
Avro - More Than Just a Serialization Framework - CHUG - 20120416
PDF
RPC protocols
PDF
OpenFest 2016 - Open Microservice Architecture
PDF
3 avro hug-2010-07-21
PPTX
G rpc lection1
PPTX
G rpc lection1_theory_bkp2
PDF
JSONSchema with golang
PPTX
New and cool in OSGi R7 - David Bosschaert & Carsten Ziegeler
PPTX
RPC: Remote procedure call
PPTX
Microservices and OSGi: Better together?
PPTX
HTTP2 and gRPC
PDF
Moved to https://slidr.io/azzazzel/osgi-for-outsiders
排队排队--kafka
"Clean" Architecture
iOS Zagreb Meetup #02 - Clean architecture in iOS apps (Leonard Beus @ Five)
Infinum iOS Talks #4 - Making our VIPER more reactive
맛만 보자 Finagle이란
java thrift
Microservices in the Enterprise
Avro - More Than Just a Serialization Framework - CHUG - 20120416
RPC protocols
OpenFest 2016 - Open Microservice Architecture
3 avro hug-2010-07-21
G rpc lection1
G rpc lection1_theory_bkp2
JSONSchema with golang
New and cool in OSGi R7 - David Bosschaert & Carsten Ziegeler
RPC: Remote procedure call
Microservices and OSGi: Better together?
HTTP2 and gRPC
Moved to https://slidr.io/azzazzel/osgi-for-outsiders
Ad

Similar to Protobuf & Code Generation + Go-Kit (20)

PDF
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
PDF
如何透過 Go-kit 快速搭建微服務架構應用程式實戰
PPTX
Modern webservices using gRPC and Protocol Buffers in Golang
PDF
GDG Cloud Taipei meetup #50 - Build go kit microservices at kubernetes with ...
PDF
gRPC and Microservices
PDF
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
PDF
Build microservice with gRPC in golang
PDF
Import golang; struct microservice
PDF
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
PPTX
Go to gRPC
PPTX
Managing gRPC Services using Kong KONNECT and the KONG API Gateway
PDF
gRPC in Go
PPTX
Building gRPC services
PDF
Usable APIs at Scale
PDF
Networking and Go: An Epic Journey
PDF
Building Go Web Apps
PPTX
Graph ql api gateway
PPTX
Graph ql api gateway
PDF
An Introduction to Go
PPTX
Net/http and the http.handler interface
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
如何透過 Go-kit 快速搭建微服務架構應用程式實戰
Modern webservices using gRPC and Protocol Buffers in Golang
GDG Cloud Taipei meetup #50 - Build go kit microservices at kubernetes with ...
gRPC and Microservices
Microservices in Go_Dessi_Massimiliano_Codemotion_2017_Rome
Build microservice with gRPC in golang
Import golang; struct microservice
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
Go to gRPC
Managing gRPC Services using Kong KONNECT and the KONG API Gateway
gRPC in Go
Building gRPC services
Usable APIs at Scale
Networking and Go: An Epic Journey
Building Go Web Apps
Graph ql api gateway
Graph ql api gateway
An Introduction to Go
Net/http and the http.handler interface

Recently uploaded (20)

PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
Introduction to Artificial Intelligence
PPTX
ai tools demonstartion for schools and inter college
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Transform Your Business with a Software ERP System
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
top salesforce developer skills in 2025.pdf
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
System and Network Administration Chapter 2
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
System and Network Administraation Chapter 3
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Which alternative to Crystal Reports is best for small or large businesses.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Introduction to Artificial Intelligence
ai tools demonstartion for schools and inter college
Odoo Companies in India – Driving Business Transformation.pdf
Design an Analysis of Algorithms II-SECS-1021-03
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
L1 - Introduction to python Backend.pptx
Transform Your Business with a Software ERP System
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
top salesforce developer skills in 2025.pdf
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
System and Network Administration Chapter 2
Understanding Forklifts - TECH EHS Solution
Wondershare Filmora 15 Crack With Activation Key [2025
System and Network Administraation Chapter 3
How Creative Agencies Leverage Project Management Software.pdf
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Upgrade and Innovation Strategies for SAP ERP Customers
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...

Protobuf & Code Generation + Go-Kit

  • 1. PROTOBUF & CODE GENERATION 2016, BY MANFRED TOURON (@MOUL)
  • 2. OVERVIEW > go-kit is an amazing framework to develop strong micro services > but it requires a lot of boilerplate code > return on experience on go-kit boilerplate code generation
  • 3. PROTOBUF? > limited to exchanges (methods and models) > extendable with plugins > contract-based > universal
  • 4. CODE GENERATION? > the good old ./generate.sh bash script > go:generate > make > protobuf + protoc-gen-gotemplate
  • 5. GO-KIT > protobuf-first, rpc-first service framework in Golang > abstract services, endpoints, transports > requires a lot of boilerplate code in multiple packages
  • 6. EXAMPLE: session.proto syntax = "proto3"; package session; service SessionService { rpc Login(LoginRequest) returns (LoginResponse) {} } message LoginRequest { string username = 1; string password = 2; } message LoginResponse { string token = 1; string err_msg = 2; }
  • 7. EXAMPLE: session.go package sessionsvc import ( "fmt" "golang.org/x/net/context" pb "github.com/moul/protoc-gen-gotemplate/examples/go-kit/services/session/gen/pb" ) type Service struct{} func New() pb.SessionServiceServer { return &Service{} } func (svc *Service) Login(ctx context.Context, in *pb.LoginRequest) (*pb.LoginResponse, error) { // custon code here return nil, fmt.Errorf("not implemented") }
  • 8. EXAMPLE: {{.File.Package}}/gen/transports/http/http.go.tmpl // source: templates/{{.File.Package}}/gen/transports/http/http.go.tmpl package {{.File.Package}}_httptransport import ( gokit_endpoint "github.com/go-kit/kit/endpoint" httptransport "github.com/go-kit/kit/transport/http" endpoints "github.com/moul/protoc-gen-gotemplate/examples/go-kit/services/{{.File.Package}}/gen/endpoints" pb "github.com/moul/protoc-gen-gotemplate/examples/go-kit/services/{{.File.Package}}/gen/pb" ) // result: services/user/gen/transports/http/http.go package user_httptransport import ( gokit_endpoint "github.com/go-kit/kit/endpoint" httptransport "github.com/go-kit/kit/transport/http" endpoints "github.com/moul/protoc-gen-gotemplate/examples/go-kit/services/user/gen/endpoints" pb "github.com/moul/protoc-gen-gotemplate/examples/go-kit/services/user/gen/pb" )
  • 9. EXAMPLE: {{.File.Package}}/gen/transports/http/http.go.tmpl // source: templates/{{.File.Package}}/gen/transports/http/http.go.tmpl {{range .Service.Method}} func Make{{.Name}}Handler(ctx context.Context, svc pb.{{$file.Package | title}}ServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server { return httptransport.NewServer( ctx, endpoint, decode{{.Name}}Request, encode{{.Name}}Response, []httptransport.ServerOption{}..., ) } {{end}} // result: services/user/gen/transports/http/http.go func MakeGetUserHandler(ctx context.Context, svc pb.UserServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server { return httptransport.NewServer( ctx, endpoint, decodeGetUserRequest, encodeGetUserResponse, []httptransport.ServerOption{}..., ) }
  • 10. EXAMPLE: {{.File.Package}}/gen/transports/http/http.go.tmpl // source: templates/{{.File.Package}}/gen/transports/http/http.go.tmpl func RegisterHandlers(ctx context.Context, svc pb.{{$file.Package | title}}ServiceServer, mux *http.ServeMux, endpoints endpoints.Endpoints) error { {{range .Service.Method}} log.Println("new HTTP endpoint: "/{{.Name}}" (service={{$file.Package | title}})") mux.Handle("/{{.Name}}", Make{{.Name}}Handler(ctx, svc, endpoints.{{.Name}}Endpoint)) {{end}} return nil } // result: services/user/gen/transports/http/http.go func RegisterHandlers(ctx context.Context, svc pb.UserServiceServer, mux *http.ServeMux, endpoints endpoints.Endpoints) error { log.Println("new HTTP endpoint: "/CreateUser" (service=User)") mux.Handle("/CreateUser", MakeCreateUserHandler(ctx, svc, endpoints.CreateUserEndpoint)) log.Println("new HTTP endpoint: "/GetUser" (service=User)") mux.Handle("/GetUser", MakeGetUserHandler(ctx, svc, endpoints.GetUserEndpoint)) return nil }
  • 14. 3 SERVICES 6 METHODS 149 CUSTOM LINES 1429 GENERATED LINES BUSINESS FOCUS
  • 15. GENERATION USAGES > go-kit boilerplate (see examples/go-kit) > k8s configuration > Dockerfile > documentation > unit-tests > fun
  • 16. PROS > small custom codebase > templates shipped with code > hardly typed, no reflects > genericity > contrat terms (protobuf) respected > not limited to a language
  • 17. CONS > the author needs to write its own templates > sometimes difficult to generate valid code > not enough helpers around the code generation yet
  • 18. IMPROVEMENT IDEAS > Support protobufs extensions (i.e, annotations.probo) > Generate one file from multiple services > Add more helpers around the code generation
  • 19. CONCLUSION > Useful to keep everything standard > The awesomeness of go-kit without the hassle of writing boilerplate code > Always up-to-date with the contracts