SlideShare a Scribd company logo
GO security tips
Andrey Shalaenko
Zeo Alliance
Golang overview
● Strong, static, inferred, structural typing system
● Pointers are available for all types.
There is no pointer arithmetic (except unsafe.Pointer)
● String is a read-only slice of bytes
● Dynamic arrays (slices), HashMap, etc
● GC (mark-sweep, tri-color)
(Go's next GC propose)
● Functional programming (first class function)
● Light-weight process (goroutine)
● Interface system (replace class inheritance)
● Quick and native compilation, speed
● Tools for developers (list)
● Standard packages
● Statically linked
Language Benefits
Golang overview
Language omissions
● Generics
● Exceptions (“errors are values“ © Rob Pike)
● Inheritance (structs compose)
● Method overloading
● Assertation
Golang overview
● Quick and native compilation, speed
● Tools for developers
(https://dominik.honnef.co/posts/2014/12/go-tools/)
● Standard packages
● Statically linked
● Package Management (Godep)
Developers benefits
Go Lang has proved to be a better choice for the following tasks :
● Web applications and web servers
Originally Go was created as a tool for fast and easy writing of web and
mobile applications by a large number of developers and to provide an
easy support environment for the code. Its own features, go routines
and channels, only enhance its advantages when writing code.
● Stand-alone command-line application or script.
This language has everything going for it: a single executed file without
any dependencies (if they are not needed), higher processing speed,
compared to other applications, ability to work with outside C libraries
and even to process system calls.
● A great alternative to parallel script writing in C/C++. It is easier to write
and deploy those scripts in Go.
Vulnerability List
Golang and OWASP TOP 10
● Same as other languages…
● databes/sql supports placeholder args
● nil, nil, nil …
//bad
sql := "SELECT * FROM users WHERE name='"+name+"' and
password='"+password+"'"
Db.Exec(sql)
//good
sql := "SELECT * FROM users WHERE name = ? AND password = ?"
Db.Exec(sql, name, password)
SQL Injections
Golang and OWASP TOP 10
SQL Injections
● Limit DB user permissions so that impact is minimal
● Sanitize inputs, escape special chars (HTMLEscapeString)
● Use parameterized queries
○ Code review Db.exec so that you’re using the parameterized
query interface
○ Or use Query/Prepare instead (Golang make prepare
statement from your parameterized query)
● Run your code against sqlmap or gauntlt
Golang and OWASP TOP 10
Web Applications: XSS
● Go Templates - html/templates and text/templates
○ Use html/templates for your app (same interface)
■ html/packages escape all html tags
(template.HTMLEscape or ExecuteTemplate)
● https://gohugo.io/
Golang and OWASP TOP 10
Web Applications: CSRF
● nosurf
○ https://github.com/justinas/nosurf
● Gorilla CSRF
○ http://www.gorillatoolkit.org/pkg/csrf
● gin-csrf
○ https://github.com/utrack/gin-csrf
Web Application building
● Easy to build your own HTTPS/HTTPS server
Web Application building
Web Frameworks and routers
● compare public api of famous Go web frameworks and routers
○ https://github.com/diyan/go-web-framework-comparsion
● benchmark of famous Go web frameworks and routers
○ https://github.com/smallnest/go-web-framework-benchmark
● benchmark HTTP request routers
○ https://github.com/julienschmidt/go-http-routing-benchmark
● Which I use:
○ GIn
■ https://github.com/gin-gonic/gin
○ Gorilla
■ https://github.com/gorilla
Web Application building
Gorilla toolkit
● Toolkit for writing web applications
○ https://github.com/gorilla
● gorilla/securecookie
○ secure cookie: encode/decode
○ value is validate with HMAC
● gorilla/sessions
○ Simple API for signed (and encrypted) cookies
○ Clean mechanism to rotate session authentication and encryption keys
● gorilla/mux:
○ great for routing web apps
● gorilla/context (in Go1.8 part of STL), gorilla/websockets, gorilla/gettext,
gorilla/http, etc
Web Application building
Gin
● Web Framework
○ https://github.com/gin-gonic/gin
● Fast
○ Use lightweight and high performance HTTP request router
(HttpRouter https://github.com/julienschmidt/httprouter)
● Zero Allocation router
● Graceful restart or stop server (native support in Go1.8)
● gin-contrib
○ A lot of tools for comfort web development
○ https://github.com/gin-gonic/contrib
○ gin-cors, gin-csrf, gin-jwt, gin-sessions, gin-oauth2, gin-sentry,
etc...
Web Application building
Secure middleware
● https://github.com/unrolled/secure
○ + XSS Protection
○ + CSP header
○ + SSL Check/SSL Redirects
Web Application building
Secure middleware: example
var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
})
func main() {
secureMiddleware := secure.New(secure.Options{
AllowedHosts: []string{"example.com",
"ssl.example.com"},
HostsProxyHeaders: []string{"X-Forwarded-Host"},
SSLRedirect: true,
SSLHost: "ssl.example.com",
SSLProxyHeaders: map[string]string{"X-Forwarded-
Proto": "https"},
STSSeconds: 315360000,
STSIncludeSubdomains: true,
STSPreload: true,
FrameDeny: true,
ContentTypeNosniff: true,
BrowserXssFilter: true,
ContentSecurityPolicy: "default-src 'self'",
PublicKey: `pin-sha256="base64+primary=="; pin-
sha256="base64+backup=="; max-age=5184000; includeSubdomains; report-
uri="https://www.example.com/hpkp-report"`,
})
app := secureMiddleware.Handler(myHandler)
Concurrency
● Go makes concurrency easy
// explicit concurrency using 'go' statement
go func() {
...
}
// implicit concurrency via standard library
timer.AfterFunc(5 * time.Seconds, func() {
...
})
● ... but also allows you to share mutable data between goroutines
● Therefore data races are possible
● These are often hard to debug
● Go's memory safety guarantees do not apply in presence of data races
Concurrency
Data Race conditions
● Two memory accesses are involved in a data race if they:
○ Target the same piece of memory
○ Happen concurrently in two goroutines
○ At least one of the accesses is a write
value := 0
for i := 0; i < 1000000; i++ {
go func() {
value += 1
}()
}
fmt.Printf("%dn", value)
Concurrency
Detecting race condition
● Use the `-race` build option
○ go test -race net/http
○ go run -race app.go
○ go build -race path/to/package
● Run your app (or tests)
● The race detector will log details of races to console
Concurrency
Detecting race condition. Caveats
● Only finds races in running code.
● Therefore testing must exercise realistic workloads
● Performance overhead - CPU cost of runtime library calls (~2-10x) and
additional memory usage (~5-10x)
○ In order to detect data races, we need to monitor:
■ Accesses to memory from different threads
■ Operations that impose ordering on memory accesses - either
directly (eg. functions in `sync/atomic`) or indirectly (eg.
primitives like mutexes, sending values over channels).
● Only detects data races - These are not the only kind of race condition
Concurrency
Detecting race condition. Example
func main() {
c := make(chan bool)
m := make(map[string]string)
go func() {
m["1"] = "a" // First conflicting access.
c <- true
}()
m["2"] = "b" // Second conflicting access.
<-c
for k, v := range m {
fmt.Println(k, v)
}
}
$ go test -race mypkg // to test the package
$ go run -race mysrc.go // to run the source file
$ go build -race mycmd // to build the command
$ go install -race mypkg // to install the package
Concurrency
Detecting race condition. Example
==================
WARNING: DATA RACE
Write at 0x00c42007c0c0 by goroutine 6:
runtime.mapassign1()
/usr/local/go/src/runtime/hashmap.go:442 +0x0
main.main.func1()
/home/zigzag/work/scripts/go/src/race_example/race_example1.go:8 +0x86
Previous write at 0x00c42007c0c0 by main goroutine:
runtime.mapassign1()
/usr/local/go/src/runtime/hashmap.go:442 +0x0
main.main()
/home/zigzag/work/scripts/go/src/race_example/race_example1.go:11 +0x13e
Goroutine 6 (running) created at:
main.main()
/home/zigzag/work/scripts/go/src/race_example/race_example1.go:10 +0xd4
==================
2 b
1 a
Found 1 data race(s)
exit status 66
Concurrency
Detecting race condition. Rules
● Use channel to synchronize between goroutine
● Only one goroutine can read and write a variable
● + or use sync/mutex or sync/atomic
○ https://golang.org/pkg/sync/#Mutex
○ https://golang.org/pkg/sync/atomic/
● close(c): Use like sending an EOF value. Only sending goroutine should
call close
Concurrency
Detecting race condition.
Further Reading
● Usage
○ http://blog.golang.org/race-detector Introducing the Go Race
Detector (blog post)
○ https://code.google.com/p/thread-sanitizer/wiki/GoManual
ThreadSanitizer Go manual
● Implementation
○ https://code.google.com/p/thread-sanitizer/wiki/Algorithm
ThreadSanitizer algorithm overview
○ http://preshing.com/20120913/acquire-and-release-semantics/
Primer on Acquire and Release Semantics (useful to understand
what it means for one memory access to happen_before another)
● The Go memory model
○ http://golang.org/ref/mem
More resources
● https://golang.org/doc/
● https://golang.org/doc/code.html
● https://golang.org/doc/effective_go.htm
● https://github.com/astaxie/build-web-application-with-golang
● https://speakerdeck.com/ngalbreath/secure-application-development-with-
golang
● https://www.reddit.com/r/golang/
Thank you
Andriy Shalaenko - GO security tips

More Related Content

PDF
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
PPTX
みんなの知らないChrome appsの世界
PDF
DConf 2016: Keynote by Walter Bright
PDF
GOCON Autumn (Story of our own Monitoring Agent in golang)
PDF
Google Dart
PPTX
Let's talks about string operations in C++17
PPTX
Vocabulary Types in C++17
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
みんなの知らないChrome appsの世界
DConf 2016: Keynote by Walter Bright
GOCON Autumn (Story of our own Monitoring Agent in golang)
Google Dart
Let's talks about string operations in C++17
Vocabulary Types in C++17

What's hot (18)

PPTX
C++17 std::filesystem - Overview
ODP
Intravert Server side processing for Cassandra
PDF
ClojureScript for the web
PDF
Go 1.10 Release Party - PDX Go
PDF
JavaScript From Hell - CONFidence 2.0 2009
PDF
ClojureScript loves React, DomCode May 26 2015
PPTX
Graph ql api gateway
PDF
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
PPTX
Go. Why it goes
PDF
Xdebug from a to x
PDF
Full Stack Clojure
PDF
ClojureScript interfaces to React
PDF
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
PDF
(not= DSL macros)
PDF
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
PDF
10 reasons to be excited about go
PDF
Basic c++ 11/14 for python programmers
PDF
DEFCON 23 - Jason Haddix - how do i shot web
C++17 std::filesystem - Overview
Intravert Server side processing for Cassandra
ClojureScript for the web
Go 1.10 Release Party - PDX Go
JavaScript From Hell - CONFidence 2.0 2009
ClojureScript loves React, DomCode May 26 2015
Graph ql api gateway
Доклад Антона Поварова "Go in Badoo" с Golang Meetup
Go. Why it goes
Xdebug from a to x
Full Stack Clojure
ClojureScript interfaces to React
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
(not= DSL macros)
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
10 reasons to be excited about go
Basic c++ 11/14 for python programmers
DEFCON 23 - Jason Haddix - how do i shot web
Ad

Similar to Andriy Shalaenko - GO security tips (20)

PDF
13 practical tips for writing secure golang applications
PDF
LCA2014 - Introduction to Go
KEY
Google Go Overview
PPTX
Introduction to go lang
PDF
Learning Go Programming 1st Edition Vladimir Vivien
PPTX
The GO Language : From Beginners to Gophers
PDF
Inroduction to golang
KEY
Beauty and Power of Go
PPT
go.ppt
PDF
Introduction to Go
PPTX
Golang - Overview of Go (golang) Language
PPTX
How to Build Your First Web App in Go
PPT
A First Look at Google's Go Programming Language
PPT
Google's Go Programming Language - Introduction
PPTX
Go programing language
PDF
Golang
PPTX
Go from a PHP Perspective
PDF
Introduction to Go programming language
ODP
Ready to go
PDF
Go, the one language to learn in 2014
13 practical tips for writing secure golang applications
LCA2014 - Introduction to Go
Google Go Overview
Introduction to go lang
Learning Go Programming 1st Edition Vladimir Vivien
The GO Language : From Beginners to Gophers
Inroduction to golang
Beauty and Power of Go
go.ppt
Introduction to Go
Golang - Overview of Go (golang) Language
How to Build Your First Web App in Go
A First Look at Google's Go Programming Language
Google's Go Programming Language - Introduction
Go programing language
Golang
Go from a PHP Perspective
Introduction to Go programming language
Ready to go
Go, the one language to learn in 2014
Ad

More from OWASP Kyiv (20)

PDF
Is there a penetration testing within PCI DSS certification? (Dmytro Diordiyc...
PPTX
Software Supply Chain Security та компоненти з відомими вразливостями
PPTX
Cloud Security Hardening та аудит хмарної безпеки за допомогою Scout Suite
PDF
Threat Modeling with OWASP Threat Dragon
PDF
Anastasia Vixentael - Don't Waste Time on Learning Cryptography: Better Use I...
PDF
Vlad Styran - Cyber Security Economics 101
PDF
Pavlo Radchuk - OWASP SAMM: Understanding Agile in Security
PDF
Ivan Vyshnevskyi - Not So Quiet Git Push
PDF
Dima Kovalenko - Modern SSL Pinning
PDF
Yevhen Teleshyk - OAuth Phishing
PDF
Vlada Kulish - Why So Serial?
PDF
Vlad Styran - OWASP Kyiv 2017 Report and 2018 Plans
PDF
Roman Borodin - ISC2 & ISACA Certification Programs First-hand Experience
PDF
Ihor Bliumental - WebSockets
PPTX
Serhiy Korolenko - The Strength of Ukrainian Users’ P@ssw0rds2017
PDF
Viktor Zhora - Cyber and Geopolitics: Ukrainian factor
PPTX
Vlad Styran - "Hidden" Features of the Tools We All Love
PDF
Volodymyr Ilibman - Close Look at Nyetya Investigation
PDF
Ihor Bliumental - Collision CORS
PPTX
Lidiia 'Alice' Skalytska - Security Checklist for Web Developers
Is there a penetration testing within PCI DSS certification? (Dmytro Diordiyc...
Software Supply Chain Security та компоненти з відомими вразливостями
Cloud Security Hardening та аудит хмарної безпеки за допомогою Scout Suite
Threat Modeling with OWASP Threat Dragon
Anastasia Vixentael - Don't Waste Time on Learning Cryptography: Better Use I...
Vlad Styran - Cyber Security Economics 101
Pavlo Radchuk - OWASP SAMM: Understanding Agile in Security
Ivan Vyshnevskyi - Not So Quiet Git Push
Dima Kovalenko - Modern SSL Pinning
Yevhen Teleshyk - OAuth Phishing
Vlada Kulish - Why So Serial?
Vlad Styran - OWASP Kyiv 2017 Report and 2018 Plans
Roman Borodin - ISC2 & ISACA Certification Programs First-hand Experience
Ihor Bliumental - WebSockets
Serhiy Korolenko - The Strength of Ukrainian Users’ P@ssw0rds2017
Viktor Zhora - Cyber and Geopolitics: Ukrainian factor
Vlad Styran - "Hidden" Features of the Tools We All Love
Volodymyr Ilibman - Close Look at Nyetya Investigation
Ihor Bliumental - Collision CORS
Lidiia 'Alice' Skalytska - Security Checklist for Web Developers

Recently uploaded (20)

PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPT
Teaching material agriculture food technology
PDF
Electronic commerce courselecture one. Pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
1. Introduction to Computer Programming.pptx
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Getting Started with Data Integration: FME Form 101
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Approach and Philosophy of On baking technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Tartificialntelligence_presentation.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
Machine learning based COVID-19 study performance prediction
Building Integrated photovoltaic BIPV_UPV.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Teaching material agriculture food technology
Electronic commerce courselecture one. Pdf
MYSQL Presentation for SQL database connectivity
Unlocking AI with Model Context Protocol (MCP)
1. Introduction to Computer Programming.pptx
Group 1 Presentation -Planning and Decision Making .pptx
Getting Started with Data Integration: FME Form 101
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Approach and Philosophy of On baking technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Network Security Unit 5.pdf for BCA BBA.
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
MIND Revenue Release Quarter 2 2025 Press Release
Tartificialntelligence_presentation.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Machine learning based COVID-19 study performance prediction

Andriy Shalaenko - GO security tips

  • 1. GO security tips Andrey Shalaenko Zeo Alliance
  • 2. Golang overview ● Strong, static, inferred, structural typing system ● Pointers are available for all types. There is no pointer arithmetic (except unsafe.Pointer) ● String is a read-only slice of bytes ● Dynamic arrays (slices), HashMap, etc ● GC (mark-sweep, tri-color) (Go's next GC propose) ● Functional programming (first class function) ● Light-weight process (goroutine) ● Interface system (replace class inheritance) ● Quick and native compilation, speed ● Tools for developers (list) ● Standard packages ● Statically linked Language Benefits
  • 3. Golang overview Language omissions ● Generics ● Exceptions (“errors are values“ © Rob Pike) ● Inheritance (structs compose) ● Method overloading ● Assertation
  • 4. Golang overview ● Quick and native compilation, speed ● Tools for developers (https://dominik.honnef.co/posts/2014/12/go-tools/) ● Standard packages ● Statically linked ● Package Management (Godep) Developers benefits
  • 5. Go Lang has proved to be a better choice for the following tasks : ● Web applications and web servers Originally Go was created as a tool for fast and easy writing of web and mobile applications by a large number of developers and to provide an easy support environment for the code. Its own features, go routines and channels, only enhance its advantages when writing code. ● Stand-alone command-line application or script. This language has everything going for it: a single executed file without any dependencies (if they are not needed), higher processing speed, compared to other applications, ability to work with outside C libraries and even to process system calls. ● A great alternative to parallel script writing in C/C++. It is easier to write and deploy those scripts in Go.
  • 7. Golang and OWASP TOP 10 ● Same as other languages… ● databes/sql supports placeholder args ● nil, nil, nil … //bad sql := "SELECT * FROM users WHERE name='"+name+"' and password='"+password+"'" Db.Exec(sql) //good sql := "SELECT * FROM users WHERE name = ? AND password = ?" Db.Exec(sql, name, password) SQL Injections
  • 8. Golang and OWASP TOP 10 SQL Injections ● Limit DB user permissions so that impact is minimal ● Sanitize inputs, escape special chars (HTMLEscapeString) ● Use parameterized queries ○ Code review Db.exec so that you’re using the parameterized query interface ○ Or use Query/Prepare instead (Golang make prepare statement from your parameterized query) ● Run your code against sqlmap or gauntlt
  • 9. Golang and OWASP TOP 10 Web Applications: XSS ● Go Templates - html/templates and text/templates ○ Use html/templates for your app (same interface) ■ html/packages escape all html tags (template.HTMLEscape or ExecuteTemplate) ● https://gohugo.io/
  • 10. Golang and OWASP TOP 10 Web Applications: CSRF ● nosurf ○ https://github.com/justinas/nosurf ● Gorilla CSRF ○ http://www.gorillatoolkit.org/pkg/csrf ● gin-csrf ○ https://github.com/utrack/gin-csrf
  • 11. Web Application building ● Easy to build your own HTTPS/HTTPS server
  • 12. Web Application building Web Frameworks and routers ● compare public api of famous Go web frameworks and routers ○ https://github.com/diyan/go-web-framework-comparsion ● benchmark of famous Go web frameworks and routers ○ https://github.com/smallnest/go-web-framework-benchmark ● benchmark HTTP request routers ○ https://github.com/julienschmidt/go-http-routing-benchmark ● Which I use: ○ GIn ■ https://github.com/gin-gonic/gin ○ Gorilla ■ https://github.com/gorilla
  • 13. Web Application building Gorilla toolkit ● Toolkit for writing web applications ○ https://github.com/gorilla ● gorilla/securecookie ○ secure cookie: encode/decode ○ value is validate with HMAC ● gorilla/sessions ○ Simple API for signed (and encrypted) cookies ○ Clean mechanism to rotate session authentication and encryption keys ● gorilla/mux: ○ great for routing web apps ● gorilla/context (in Go1.8 part of STL), gorilla/websockets, gorilla/gettext, gorilla/http, etc
  • 14. Web Application building Gin ● Web Framework ○ https://github.com/gin-gonic/gin ● Fast ○ Use lightweight and high performance HTTP request router (HttpRouter https://github.com/julienschmidt/httprouter) ● Zero Allocation router ● Graceful restart or stop server (native support in Go1.8) ● gin-contrib ○ A lot of tools for comfort web development ○ https://github.com/gin-gonic/contrib ○ gin-cors, gin-csrf, gin-jwt, gin-sessions, gin-oauth2, gin-sentry, etc...
  • 15. Web Application building Secure middleware ● https://github.com/unrolled/secure ○ + XSS Protection ○ + CSP header ○ + SSL Check/SSL Redirects
  • 16. Web Application building Secure middleware: example var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello world")) }) func main() { secureMiddleware := secure.New(secure.Options{ AllowedHosts: []string{"example.com", "ssl.example.com"}, HostsProxyHeaders: []string{"X-Forwarded-Host"}, SSLRedirect: true, SSLHost: "ssl.example.com", SSLProxyHeaders: map[string]string{"X-Forwarded- Proto": "https"}, STSSeconds: 315360000, STSIncludeSubdomains: true, STSPreload: true, FrameDeny: true, ContentTypeNosniff: true, BrowserXssFilter: true, ContentSecurityPolicy: "default-src 'self'", PublicKey: `pin-sha256="base64+primary=="; pin- sha256="base64+backup=="; max-age=5184000; includeSubdomains; report- uri="https://www.example.com/hpkp-report"`, }) app := secureMiddleware.Handler(myHandler)
  • 17. Concurrency ● Go makes concurrency easy // explicit concurrency using 'go' statement go func() { ... } // implicit concurrency via standard library timer.AfterFunc(5 * time.Seconds, func() { ... }) ● ... but also allows you to share mutable data between goroutines ● Therefore data races are possible ● These are often hard to debug ● Go's memory safety guarantees do not apply in presence of data races
  • 18. Concurrency Data Race conditions ● Two memory accesses are involved in a data race if they: ○ Target the same piece of memory ○ Happen concurrently in two goroutines ○ At least one of the accesses is a write value := 0 for i := 0; i < 1000000; i++ { go func() { value += 1 }() } fmt.Printf("%dn", value)
  • 19. Concurrency Detecting race condition ● Use the `-race` build option ○ go test -race net/http ○ go run -race app.go ○ go build -race path/to/package ● Run your app (or tests) ● The race detector will log details of races to console
  • 20. Concurrency Detecting race condition. Caveats ● Only finds races in running code. ● Therefore testing must exercise realistic workloads ● Performance overhead - CPU cost of runtime library calls (~2-10x) and additional memory usage (~5-10x) ○ In order to detect data races, we need to monitor: ■ Accesses to memory from different threads ■ Operations that impose ordering on memory accesses - either directly (eg. functions in `sync/atomic`) or indirectly (eg. primitives like mutexes, sending values over channels). ● Only detects data races - These are not the only kind of race condition
  • 21. Concurrency Detecting race condition. Example func main() { c := make(chan bool) m := make(map[string]string) go func() { m["1"] = "a" // First conflicting access. c <- true }() m["2"] = "b" // Second conflicting access. <-c for k, v := range m { fmt.Println(k, v) } } $ go test -race mypkg // to test the package $ go run -race mysrc.go // to run the source file $ go build -race mycmd // to build the command $ go install -race mypkg // to install the package
  • 22. Concurrency Detecting race condition. Example ================== WARNING: DATA RACE Write at 0x00c42007c0c0 by goroutine 6: runtime.mapassign1() /usr/local/go/src/runtime/hashmap.go:442 +0x0 main.main.func1() /home/zigzag/work/scripts/go/src/race_example/race_example1.go:8 +0x86 Previous write at 0x00c42007c0c0 by main goroutine: runtime.mapassign1() /usr/local/go/src/runtime/hashmap.go:442 +0x0 main.main() /home/zigzag/work/scripts/go/src/race_example/race_example1.go:11 +0x13e Goroutine 6 (running) created at: main.main() /home/zigzag/work/scripts/go/src/race_example/race_example1.go:10 +0xd4 ================== 2 b 1 a Found 1 data race(s) exit status 66
  • 23. Concurrency Detecting race condition. Rules ● Use channel to synchronize between goroutine ● Only one goroutine can read and write a variable ● + or use sync/mutex or sync/atomic ○ https://golang.org/pkg/sync/#Mutex ○ https://golang.org/pkg/sync/atomic/ ● close(c): Use like sending an EOF value. Only sending goroutine should call close
  • 24. Concurrency Detecting race condition. Further Reading ● Usage ○ http://blog.golang.org/race-detector Introducing the Go Race Detector (blog post) ○ https://code.google.com/p/thread-sanitizer/wiki/GoManual ThreadSanitizer Go manual ● Implementation ○ https://code.google.com/p/thread-sanitizer/wiki/Algorithm ThreadSanitizer algorithm overview ○ http://preshing.com/20120913/acquire-and-release-semantics/ Primer on Acquire and Release Semantics (useful to understand what it means for one memory access to happen_before another) ● The Go memory model ○ http://golang.org/ref/mem
  • 25. More resources ● https://golang.org/doc/ ● https://golang.org/doc/code.html ● https://golang.org/doc/effective_go.htm ● https://github.com/astaxie/build-web-application-with-golang ● https://speakerdeck.com/ngalbreath/secure-application-development-with- golang ● https://www.reddit.com/r/golang/