SlideShare a Scribd company logo
Happy Programming with Go Compiler
GTG 12
poga
Gtg12
Today
• Tricks to write DSL in Go
• code generation with GO GENERATE
DSL in Go
s.Config(
LogLevel(WARN),
Backend(S3{
Key: "API_KEY",
Secret: "SUPER SECRET",
}),
AfterComplete(func() {
fmt.Println("service ready")
}),
)
Do(With{A: "foo", B: 123})
Ruby
• DSL!
• Slow



Ruby
• DSL!
• Slow
• Error-prone
DSL in Ruby
DSL in Ruby
validates :name, presence: true
validate :name, presence: true
validates :name, presense: true
Which is correct?
DSL in Ruby
validates :points, numericality: true
validates :points, numericality: { only: “integer” }
validates :points, numericality: { only_integer: true }
Which is correct?
DSL in Ruby
• String/symbol + Hash everywhere
• lack of “Syntax Error”
• everything is void*
• anything is ok for ruby interpreter
• Need a lot of GOOD documentation

DSL in Ruby
• String/symbol + Hash everywhere
• lack of “Syntax Error”
• everything is void*
• anything is ok for ruby interpreter
• Need a lot of GOOD documentation
• and memorization
Go
• Fast
• Small Footprint



















Go
• Fast
• Small Footprint
• Verbose
• sort
• if err != nil
• if err != nil
• if err != nil
Patterns
• http://www.godesignpatterns.com/
• https://blog.golang.org/errors-are-values
Named Parameter
type With struct {
A string
B int
}
func main() {
Do(With{A: "foo", B: 123})
}
func Do(p With) {
…
}
Named Parameter
• Error when
• mistype parameter name
• incorrect parameter type
Configuration
s.Config(
LogLevel(WARN),
Backend(S3{
Key: "API_KEY",
Secret: "SUPER SECRET",
}),
AfterComplete(func() {
fmt.Println("service ready")
}),
)
type Service struct {
ErrorLevel int
AWSKey string
AWSSecret string
AfterHook func()
}
https://gist.github.com/poga/bf0534486199c8e778cb
Configuration
• Self-referential Function



















type option func(*Service)
func (s *Service) Config(opts ...option) {
for _, opt := range opts {
opt(s)
}
}
func LogLevel(level int) option {
return func(s *Service) {
s.ErrorLevel = level
}
}
http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html
Struct Tag
type Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
MiddleName string `json:"middle_name,omitempty"`
}
Struct Tag
• Anti-Pattern
• String-typing
• No compile time checking
• 6 month old bug in KKTIX production, no one noticed
• based on reflect
• slow
• Don’t use it as DSL
Vanilla Go
• Sometimes it’s not enough
• We need to go deeper













Code Generation
WOW
So Rails
Much Magic
Error Handling in Go
• Extremely Verbose
• We already have 3 official error handling patterns
• https://blog.golang.org/errors-are-values
• checking error is fine. But I’m lazy to type
• Messy control flow
Error Handler Generation
• go get github.com/poga/autoerror
• just a demo, don’t use it in production
Auto Error
• Add error checking function
based on the name of error
variable
• Hide error checking from
control flow
//go:generate autoerror -i simple.go -t AutoError -o test.go
type AutoError error
var e AutoError
var e2 AutoError
func Test() {
e = doSomething()
e2 = doSomething()
}
func doSomething() error {
return errors.New("an error")
}
func handleError2(e2 error) {
if e2 != nil {
panic(e)
}
}
func handleError(e error) {
if e != nil {
panic(e)
}
}
//go:generate autoerror -i simple.go -t AutoError -o test.go
type AutoError error
var e AutoError
var e2 AutoError
func Test() {
e = doSomething()
e2 = doSomething()
}
func doSomething() error {
return errors.New("an error")
}
func handleError2(e2 error) {
if e2 != nil {
panic(e)
}
}
func handleError(e error) {
if e != nil {
panic(e)
}
}
//go:generate autoerror -i simple.go -t AutoError -o test.go
type AutoError error
var e AutoError
var e2 AutoError
func Test() {
e = doSomething()
e2 = doSomething()
handleError2(e2)
}
func doSomething() error {
return errors.New("an error")
}
func handleError2(e2 error) {
if e2 != nil {
panic(e)
}
}
func handleError(e error) {
if e != nil {
panic(e)
}
}
//go:generate autoerror -i simple.go -t AutoError -o test.go
type AutoError error
var e AutoError
var e2 AutoError
func Test() {
e = doSomething()
e2 = doSomething()
handleError2(e2)
}
func doSomething() error {
return errors.New("an error")
}
func handleError2(e2 error) {
if e2 != nil {
panic(e)
}
}
func handleError(e error) {
if e != nil {
panic(e)
}
}
//go:generate autoerror -i simple.go -t AutoError -o test.go
type AutoError error
var e AutoError
var e2 AutoError
func Test() {
e = doSomething()
handleError(e)
e2 = doSomething()
handleError2(e2)
}
func doSomething() error {
return errors.New("an error")
}
func handleError2(e2 error) {
if e2 != nil {
panic(e)
}
}
func handleError(e error) {
if e != nil {
panic(e)
}
}
What is Go Generate
• shell scripting in go









$ go generate
//go:generate echo 'hello from go generate'
hello from go generate
go generate
• execute a ruby script
• integrate with code gen tools
• yacc, protocol buffer,… etc
//go:generate ruby gen.rb
//go:generate codecgen -o values.generated.go file1.go file2.go file3.go
go generate
• go get won’t execute ‘go generate’ for you
• generate before publish
type checking placeholder
json.have(
pair{Key: “FirstName”, From: “first_name”},
pair{Key: “FirstName”, From: “first_name”},
pair{Key: “MiddleName”, From: “middle_name”, OmitEmpty: true})
type Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
MiddleName string `json:"middle_name,omitempty"`
}
person.have(
string{Key: “FirstName”, From: “first_name”},
string{Key: “FirstName”, From: “first_name”},
string{Key: “MiddleName”, From: “middle_name”, OmitEmpty: true})
type Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
MiddleName string `json:"middle_name,omitempty"`
}
func (p Person) have(pairs pair…) {
panic(“run go generate before use this file”)
}
Recap
• DSL
• Named Parameter
• Configuration
• Code Generation
• type checking placeholder
Thank you

More Related Content

PDF
Maintainable JavaScript
Nicholas Zakas
 
PDF
You do not need automation engineer - Sqa Days - 2015 - EN
Iakiv Kramarenko
 
PDF
Excellent
Marco Otte-Witte
 
PDF
Rails is not just Ruby
Marco Otte-Witte
 
PDF
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
Iakiv Kramarenko
 
PDF
Easy automation.py
Iakiv Kramarenko
 
ZIP
Automated Frontend Testing
Neil Crosby
 
Maintainable JavaScript
Nicholas Zakas
 
You do not need automation engineer - Sqa Days - 2015 - EN
Iakiv Kramarenko
 
Excellent
Marco Otte-Witte
 
Rails is not just Ruby
Marco Otte-Witte
 
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
Iakiv Kramarenko
 
Easy automation.py
Iakiv Kramarenko
 
Automated Frontend Testing
Neil Crosby
 

What's hot (20)

PDF
Nightwatch at Tilt
Dave King
 
PDF
Build a bot workshop async primer - php[tek]
Adam Englander
 
PDF
Angular Application Testing
Troy Miles
 
PDF
ZendCon 2017 - Build a Bot Workshop - Async Primer
Adam Englander
 
PPTX
Optimizing a large angular application (ng conf)
A K M Zahiduzzaman
 
PDF
20160905 - BrisJS - nightwatch testing
Vladimir Roudakov
 
PDF
CodePolitan Webinar: The Rise of PHP
Steeven Salim
 
PDF
Unit testing JavaScript using Mocha and Node
Josh Mock
 
PDF
Unit testing with mocha
Revath S Kumar
 
PDF
Python for AngularJS
Jeff Schenck
 
PDF
Lets make a better react form
Yao Nien Chung
 
KEY
I18n
soon
 
PDF
Callbacks, promises, generators - asynchronous javascript
Łukasz Kużyński
 
PDF
第26回PHP勉強会
Kenichi Yonekawa
 
PDF
Your code are my tests
Michelangelo van Dam
 
PDF
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
James Titcumb
 
PPT
You promise?
IT Weekend
 
PDF
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
James Titcumb
 
PDF
High Performance web apps in Om, React and ClojureScript
Leonardo Borges
 
PDF
Enhance react app with patterns - part 1: higher order component
Yao Nien Chung
 
Nightwatch at Tilt
Dave King
 
Build a bot workshop async primer - php[tek]
Adam Englander
 
Angular Application Testing
Troy Miles
 
ZendCon 2017 - Build a Bot Workshop - Async Primer
Adam Englander
 
Optimizing a large angular application (ng conf)
A K M Zahiduzzaman
 
20160905 - BrisJS - nightwatch testing
Vladimir Roudakov
 
CodePolitan Webinar: The Rise of PHP
Steeven Salim
 
Unit testing JavaScript using Mocha and Node
Josh Mock
 
Unit testing with mocha
Revath S Kumar
 
Python for AngularJS
Jeff Schenck
 
Lets make a better react form
Yao Nien Chung
 
I18n
soon
 
Callbacks, promises, generators - asynchronous javascript
Łukasz Kużyński
 
第26回PHP勉強会
Kenichi Yonekawa
 
Your code are my tests
Michelangelo van Dam
 
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
James Titcumb
 
You promise?
IT Weekend
 
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
James Titcumb
 
High Performance web apps in Om, React and ClojureScript
Leonardo Borges
 
Enhance react app with patterns - part 1: higher order component
Yao Nien Chung
 
Ad

Viewers also liked (7)

PDF
Wtt#20
Poga Po
 
PDF
萬事萬物皆是 LOG - 系統架構也來點科普
Poga Po
 
PDF
聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015
Poga Po
 
PDF
Full-stack go with GopherJS
Poga Po
 
PDF
OSDC.TW - Gutscript for PHP haters
Lin Yo-An
 
ODP
Goqt
宥瑞 曾
 
PDF
Use go channel to write a disk queue
Evan Lin
 
Wtt#20
Poga Po
 
萬事萬物皆是 LOG - 系統架構也來點科普
Poga Po
 
聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015
Poga Po
 
Full-stack go with GopherJS
Poga Po
 
OSDC.TW - Gutscript for PHP haters
Lin Yo-An
 
Use go channel to write a disk queue
Evan Lin
 
Ad

Similar to Gtg12 (20)

PDF
Exception Handling: Designing Robust Software in Ruby
Wen-Tien Chang
 
PDF
Efficient JavaScript Development
wolframkriesing
 
PDF
JavaScript in 2015
Igor Laborie
 
PDF
All things that are not code
Mobile Delivery Days
 
PDF
Lecture 03 - JQuery.pdf
Lê Thưởng
 
PPTX
Reducing Bugs With Static Code Analysis php tek 2025
Scott Keck-Warren
 
PDF
Angularjs Test Driven Development (TDD)
Anis Bouhachem Djer
 
PPTX
Compatibility Detector Tool of Chrome extensions
Kai Cui
 
PDF
Go 1.10 Release Party - PDX Go
Rodolfo Carvalho
 
PDF
Test-Driven Development of AngularJS Applications
FITC
 
PDF
How Testability Inspires AngularJS Design / Ran Mizrahi
Ran Mizrahi
 
KEY
Djangocon
Jeff Balogh
 
PDF
ECMAScript.Next ECMAScipt 6
Kevin DeRudder
 
PDF
Es.next
kevinsson
 
PDF
What's up with Prototype and script.aculo.us?
Christophe Porteneuve
 
PDF
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Holger Grosse-Plankermann
 
PDF
Efficient JavaScript Development
wolframkriesing
 
PDF
Everything-as-code. A polyglot adventure. #DevoxxPL
Mario-Leander Reimer
 
PDF
Everything-as-code - A polyglot adventure
QAware GmbH
 
PDF
.gradle 파일 정독해보기
경주 전
 
Exception Handling: Designing Robust Software in Ruby
Wen-Tien Chang
 
Efficient JavaScript Development
wolframkriesing
 
JavaScript in 2015
Igor Laborie
 
All things that are not code
Mobile Delivery Days
 
Lecture 03 - JQuery.pdf
Lê Thưởng
 
Reducing Bugs With Static Code Analysis php tek 2025
Scott Keck-Warren
 
Angularjs Test Driven Development (TDD)
Anis Bouhachem Djer
 
Compatibility Detector Tool of Chrome extensions
Kai Cui
 
Go 1.10 Release Party - PDX Go
Rodolfo Carvalho
 
Test-Driven Development of AngularJS Applications
FITC
 
How Testability Inspires AngularJS Design / Ran Mizrahi
Ran Mizrahi
 
Djangocon
Jeff Balogh
 
ECMAScript.Next ECMAScipt 6
Kevin DeRudder
 
Es.next
kevinsson
 
What's up with Prototype and script.aculo.us?
Christophe Porteneuve
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Holger Grosse-Plankermann
 
Efficient JavaScript Development
wolframkriesing
 
Everything-as-code. A polyglot adventure. #DevoxxPL
Mario-Leander Reimer
 
Everything-as-code - A polyglot adventure
QAware GmbH
 
.gradle 파일 정독해보기
경주 전
 

Recently uploaded (20)

PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
PDF
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PDF
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
PDF
Immersive experiences: what Pharo users do!
ESUG
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PPT
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
PPTX
Presentation about Database and Database Administrator
abhishekchauhan86963
 
PDF
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
PDF
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
Exploring AI Agents in Process Industries
amoreira6
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
Immersive experiences: what Pharo users do!
ESUG
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
Presentation about Database and Database Administrator
abhishekchauhan86963
 
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
Protecting the Digital World Cyber Securit
dnthakkar16
 

Gtg12

  • 1. Happy Programming with Go Compiler GTG 12 poga
  • 3. Today • Tricks to write DSL in Go • code generation with GO GENERATE
  • 4. DSL in Go s.Config( LogLevel(WARN), Backend(S3{ Key: "API_KEY", Secret: "SUPER SECRET", }), AfterComplete(func() { fmt.Println("service ready") }), ) Do(With{A: "foo", B: 123})
  • 8. DSL in Ruby validates :name, presence: true validate :name, presence: true validates :name, presense: true Which is correct?
  • 9. DSL in Ruby validates :points, numericality: true validates :points, numericality: { only: “integer” } validates :points, numericality: { only_integer: true } Which is correct?
  • 10. DSL in Ruby • String/symbol + Hash everywhere • lack of “Syntax Error” • everything is void* • anything is ok for ruby interpreter • Need a lot of GOOD documentation

  • 11. DSL in Ruby • String/symbol + Hash everywhere • lack of “Syntax Error” • everything is void* • anything is ok for ruby interpreter • Need a lot of GOOD documentation • and memorization
  • 12. Go • Fast • Small Footprint
 
 
 
 
 
 
 
 
 

  • 13. Go • Fast • Small Footprint • Verbose • sort • if err != nil • if err != nil • if err != nil
  • 15. Named Parameter type With struct { A string B int } func main() { Do(With{A: "foo", B: 123}) } func Do(p With) { … }
  • 16. Named Parameter • Error when • mistype parameter name • incorrect parameter type
  • 17. Configuration s.Config( LogLevel(WARN), Backend(S3{ Key: "API_KEY", Secret: "SUPER SECRET", }), AfterComplete(func() { fmt.Println("service ready") }), ) type Service struct { ErrorLevel int AWSKey string AWSSecret string AfterHook func() } https://gist.github.com/poga/bf0534486199c8e778cb
  • 18. Configuration • Self-referential Function
 
 
 
 
 
 
 
 
 
 type option func(*Service) func (s *Service) Config(opts ...option) { for _, opt := range opts { opt(s) } } func LogLevel(level int) option { return func(s *Service) { s.ErrorLevel = level } } http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html
  • 19. Struct Tag type Person struct { FirstName string `json:"first_name"` LastName string `json:"last_name"` MiddleName string `json:"middle_name,omitempty"` }
  • 20. Struct Tag • Anti-Pattern • String-typing • No compile time checking • 6 month old bug in KKTIX production, no one noticed • based on reflect • slow • Don’t use it as DSL
  • 21. Vanilla Go • Sometimes it’s not enough • We need to go deeper
 
 
 
 
 
 

  • 23. Error Handling in Go • Extremely Verbose • We already have 3 official error handling patterns • https://blog.golang.org/errors-are-values • checking error is fine. But I’m lazy to type • Messy control flow
  • 24. Error Handler Generation • go get github.com/poga/autoerror • just a demo, don’t use it in production
  • 25. Auto Error • Add error checking function based on the name of error variable • Hide error checking from control flow
  • 26. //go:generate autoerror -i simple.go -t AutoError -o test.go type AutoError error var e AutoError var e2 AutoError func Test() { e = doSomething() e2 = doSomething() } func doSomething() error { return errors.New("an error") } func handleError2(e2 error) { if e2 != nil { panic(e) } } func handleError(e error) { if e != nil { panic(e) } }
  • 27. //go:generate autoerror -i simple.go -t AutoError -o test.go type AutoError error var e AutoError var e2 AutoError func Test() { e = doSomething() e2 = doSomething() } func doSomething() error { return errors.New("an error") } func handleError2(e2 error) { if e2 != nil { panic(e) } } func handleError(e error) { if e != nil { panic(e) } }
  • 28. //go:generate autoerror -i simple.go -t AutoError -o test.go type AutoError error var e AutoError var e2 AutoError func Test() { e = doSomething() e2 = doSomething() handleError2(e2) } func doSomething() error { return errors.New("an error") } func handleError2(e2 error) { if e2 != nil { panic(e) } } func handleError(e error) { if e != nil { panic(e) } }
  • 29. //go:generate autoerror -i simple.go -t AutoError -o test.go type AutoError error var e AutoError var e2 AutoError func Test() { e = doSomething() e2 = doSomething() handleError2(e2) } func doSomething() error { return errors.New("an error") } func handleError2(e2 error) { if e2 != nil { panic(e) } } func handleError(e error) { if e != nil { panic(e) } }
  • 30. //go:generate autoerror -i simple.go -t AutoError -o test.go type AutoError error var e AutoError var e2 AutoError func Test() { e = doSomething() handleError(e) e2 = doSomething() handleError2(e2) } func doSomething() error { return errors.New("an error") } func handleError2(e2 error) { if e2 != nil { panic(e) } } func handleError(e error) { if e != nil { panic(e) } }
  • 31. What is Go Generate • shell scripting in go
 
 
 
 
 $ go generate //go:generate echo 'hello from go generate' hello from go generate
  • 32. go generate • execute a ruby script • integrate with code gen tools • yacc, protocol buffer,… etc //go:generate ruby gen.rb //go:generate codecgen -o values.generated.go file1.go file2.go file3.go
  • 33. go generate • go get won’t execute ‘go generate’ for you • generate before publish
  • 34. type checking placeholder json.have( pair{Key: “FirstName”, From: “first_name”}, pair{Key: “FirstName”, From: “first_name”}, pair{Key: “MiddleName”, From: “middle_name”, OmitEmpty: true}) type Person struct { FirstName string `json:"first_name"` LastName string `json:"last_name"` MiddleName string `json:"middle_name,omitempty"` }
  • 35. person.have( string{Key: “FirstName”, From: “first_name”}, string{Key: “FirstName”, From: “first_name”}, string{Key: “MiddleName”, From: “middle_name”, OmitEmpty: true}) type Person struct { FirstName string `json:"first_name"` LastName string `json:"last_name"` MiddleName string `json:"middle_name,omitempty"` } func (p Person) have(pairs pair…) { panic(“run go generate before use this file”) }
  • 36. Recap • DSL • Named Parameter • Configuration • Code Generation • type checking placeholder