SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Happy Programming with Go Compiler
GTG 12
poga
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

Weitere ähnliche Inhalte

Was ist angesagt?

Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
Josh Mock
 
I18n
I18nI18n
I18n
soon
 

Was ist angesagt? (20)

Nightwatch at Tilt
Nightwatch at TiltNightwatch at Tilt
Nightwatch at Tilt
 
Build a bot workshop async primer - php[tek]
Build a bot workshop  async primer - php[tek]Build a bot workshop  async primer - php[tek]
Build a bot workshop async primer - php[tek]
 
Angular Application Testing
Angular Application TestingAngular Application Testing
Angular Application Testing
 
ZendCon 2017 - Build a Bot Workshop - Async Primer
ZendCon 2017 - Build a Bot Workshop - Async PrimerZendCon 2017 - Build a Bot Workshop - Async Primer
ZendCon 2017 - Build a Bot Workshop - Async Primer
 
Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)
 
20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing
 
CodePolitan Webinar: The Rise of PHP
CodePolitan Webinar: The Rise of PHPCodePolitan Webinar: The Rise of PHP
CodePolitan Webinar: The Rise of PHP
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mocha
 
Python for AngularJS
Python for AngularJSPython for AngularJS
Python for AngularJS
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
I18n
I18nI18n
I18n
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
第26回PHP勉強会
第26回PHP勉強会第26回PHP勉強会
第26回PHP勉強会
 
Your code are my tests
Your code are my testsYour code are my tests
Your code are my tests
 
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
 
You promise?
You promise?You promise?
You promise?
 
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScript
 
Enhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentEnhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order component
 

Andere mochten auch (7)

Wtt#20
Wtt#20Wtt#20
Wtt#20
 
萬事萬物皆是 LOG - 系統架構也來點科普
萬事萬物皆是 LOG - 系統架構也來點科普萬事萬物皆是 LOG - 系統架構也來點科普
萬事萬物皆是 LOG - 系統架構也來點科普
 
聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015
聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015
聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015
 
Full-stack go with GopherJS
Full-stack go with GopherJSFull-stack go with GopherJS
Full-stack go with GopherJS
 
OSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP haters
 
Goqt
GoqtGoqt
Goqt
 
Use go channel to write a disk queue
Use go channel to write a disk queueUse go channel to write a disk queue
Use go channel to write a disk queue
 

Ähnlich wie Gtg12

Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
Wen-Tien Chang
 
Compatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensionsCompatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensions
Kai Cui
 

Ähnlich wie Gtg12 (20)

Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Development
 
JavaScript in 2015
JavaScript in 2015JavaScript in 2015
JavaScript in 2015
 
All things that are not code
All things that are not codeAll things that are not code
All things that are not code
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
 
Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)
 
Compatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensionsCompatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensions
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran Mizrahi
 
Djangocon
DjangoconDjangocon
Djangocon
 
ECMAScript.Next ECMAScipt 6
ECMAScript.Next ECMAScipt 6ECMAScript.Next ECMAScipt 6
ECMAScript.Next ECMAScipt 6
 
Es.next
Es.nextEs.next
Es.next
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWJest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRW
 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Development
 
Everything-as-code. A polyglot adventure. #DevoxxPL
Everything-as-code. A polyglot adventure. #DevoxxPLEverything-as-code. A polyglot adventure. #DevoxxPL
Everything-as-code. A polyglot adventure. #DevoxxPL
 
Everything-as-code - A polyglot adventure
Everything-as-code - A polyglot adventureEverything-as-code - A polyglot adventure
Everything-as-code - A polyglot adventure
 
.gradle 파일 정독해보기
.gradle 파일 정독해보기.gradle 파일 정독해보기
.gradle 파일 정독해보기
 
An Introduction To jQuery
An Introduction To jQueryAn Introduction To jQuery
An Introduction To jQuery
 

Kürzlich hochgeladen

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Kürzlich hochgeladen (20)

Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

Gtg12

  • 1. Happy Programming with Go Compiler GTG 12 poga
  • 2.
  • 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