Wilson Mar bio photo

Wilson Mar

Hello. Hire me!

Email me Calendar Skype call 310 320-7878

LinkedIn Twitter Gitter Google+ Youtube

Github Stackoverflow Pinterest

This is what the cool kids are using to create utilities


This is a quick step-by-step introduction to the Go programming language (GoLang).

Go is an opinionated language:

  • Compiler doesn’t issue warnings, just errors
  • Unused local variables are an error
  • fmt (an contraction of “format”, pronounced “frumpt”) is Go’s single way to format output

Like C:

  • Strongly typed (must specify data type in commands)
  • Used by developers of C (Kernigan, who literally wrote the book on C)
  • Uses its own compiler to create itself

Unlike C:

Like Java:

  • Collects garbage
  • Is memory safe by default
  • Networking is baked into the standard library and runtime

Like both Java and C:

  • needs to be built by a compiler (not interpreted like Python)
  • double slashes for comments

Unlike both:

  • fast compile to native code
  • low GC pause (100 microseconds)
  • Memory is zeroed if not explicitly initialized
  • there are no parentheses surrounding the three components of the for statement

Install Compiler

  1. If there was a previous version installed:

    Uninstalling /usr/local/Cellar/go/1.8... (7,017 files, 281.6MB)
  2. Use third-party software installers so new versions can be managed automatically.

    If you use Homebrew on your Mac, install on any folder using:

    brew install go

    (go or golang can be specified)

    Alternately, MacPorts:

    sudo port install go

    Alternately, do what the GoLang web page says: download installer from:



  3. Consider a paid, commercially supported, quality-assured Go distribution for big data, database connectivity, code quality, microservices/cloud development:


    NOTE: This was in “beta” as of April, 2017.

  4. See where the Go command references:

    go version

    shows (at time of writing):

    go version go1.8.3 darwin/amd64
  5. To upgrade to the latest:

    brew upgrade go

    Source files folder

  6. In an internet browser (Chrome or Firefox):


    Its contents is described here below.


  7. Fork the sample repository to your own GitHub account.

  8. Switch to a Terminal shell window.

  9. Create a folder to hold various Git repositories (personal preference here, replace gits and wilsonmar with your account name):

    cd ~
    mkdir gits
    cd gits
    mkdir wilsonmar
    cd wilsonmar
  10. Edit (~/.bash_profile on Macs) to create $GOPATH (replacing wilsonmar with your GitHub account name):

    export GOHOME="$HOME/gits/wilsonmar/golang-samples"

    Alternately, append by using this command:

    echo “export PATH=$PATH:/usr/local/go/bin” » ~/.bash_profile

  11. Navigate to the default home folder.

    cd $GOHOME
  12. Pull down from GitHub:

    git clone https://github.com/wilsonmar/golang-samples

    PROTIP: Go source code files exist within a folder of the same name and have a suffix of .go.

  13. Verify by getting the environment settings:

    go env

    shows (at time of writing), on a Mac:

    GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/j_/gh27gpxj1t58hyryfg9drvdc0000gn/T/go-build434742939=/tmp/go-build -gno-record-gcc-switches -fno-common"
    CGO_CFLAGS="-g -O2"
    CGO_CXXFLAGS="-g -O2"
    CGO_FFLAGS="-g -O2"
    CGO_LDFLAGS="-g -O2"

    NOTE: GOROOT is in Cellar because it was installed by Homebrew.

    No need to define $GOROOT in ~/.bash_profile unless Go was downloaded to a custom location.


  14. Verify whether you can do Go commands:

    go help | more

    Go displays help as a page in your default text editor.

    PROTIP: If you don’t pipe to more, you’ll see the bottom of the document and have to page back up.

  15. If you see a colon at the lower-left corner:

    • press spacebar to page down
    • press q to quit.

    Auto format

  16. Format source code according to Go coding standards:

    go gofmt [flags] [path ...]

    See https://golang.org/cmd/gofmt/”> about flags.


  17. Install and configuring goimports to automatically run on save to format and auto adjust import statements as needed:

    go get code.google.com/p/go.tools/cmd/goimports

    BLAH: I’m getting these messages:

    package code.google.com/p/go.tools/cmd/goimports: unrecognized import path "code.google.com/p/go.tools/cmd/goimports" (parse https://code.google.com/p/go.tools/cmd/goimports?go-get=1: no go-import meta tags (meta tag github.com/golang/go did not match import path code.google.com/p/go.tools/cmd/goimports))
  18. Setup vim to auto run goimports on save using vim-go:

    let g:go_fmt_command = "goimports"

    BLAH: Response is “-bash: let: g:go_fmt_command: syntax error in expression (error token is “:go_fmt_command”)”

  19. Setup reload web server when file change is detected:



    https://github.com/gin-gonic/gin “Gin” web framework

    IDEs to edit/run Go

    Unlike C#, Go is not associated with an IDE such as Microsoft Visual Studio. However, shortcuts and reformat are provided for text editors:

    • Atom Golang video by Todd McLeod

    • WebStorm Gogland from JetBrains, who made IntelliJ for Java, PyCharm, etc.

    • TextMate 2 has a Go bundle at http://macromates.com/download

    • vim has a vim-go package at https://github.com/fatih/vim-go

    • SublimeText?

    • Visual Studio Code?

    File Issue for Go on GitHub

  20. To create a new bug (issue) by opening GitHub from your command line:

    go bug

    This opens a browser window on Go’s GitHub page at

    Go’s repo was previously in Mercurial.

Who uses Go?

Although unveiled in 2009, companies who have adopted Go in their products include Atlassian, Docker, Facebook, DigitalOcean, Cloudflare, eBay, Heroku, Hashicorp, Capital One.

The 2016 survey found that 40% of respondants used the language for less that 1 year.

The greatest use is in runnable/interactive programs (CLI).

When asked what they like most about Go, users most commonly mentioned Go’s simplicity, ease of use, concurrency features, and performance.

When asked what changes would most improve Go, users most commonly mentioned generics, package versioning, and dependency management. Other popular responses were GUIs, debugging, and error handling.

Go isn’t an appropriate fit for iOS, JS.

The Go compiler is programmed in Go itself rather than C. * This means Go installers don’t have dependencies like Java and Python programs.

Due to its small size, Go can be a good fit for use on a Raspberry Pi small computer to receive and provide small amounts of data. ?

PROTIP: The canonical list of companies using Go is at

Hello World Code in Go Playground

PROTIP: Like Python has “Pythonic”, “Gothic” is Go’s way of saying idiomatic Go code (the easiest and most common ways of accomplishing a task using native language constructs rather than porting assumptions from a different language).

  1. View a simple Go program in an on-line editor for Go at https://play.golang.org/p/0Hz57BQdTA

    // hello.go
    package main
    import( "fmt"; "time")
    var now = time.Now()
    func main() {
     fmt.Printf("hello, world at %v",now)

    Notice no semicolons at the end of each line.

    The response printed out is the default time format is of the time of Go’s initial commit:

    2009-11-10 23:00:00 UTC
    1257894000 epoch time

    Tour of Language Syntax

  2. Tours of Go language syntax are presented on these websites:

Add Packages Imported

Path of Packages in $GOPATH

An alternative way to specify 3rd-party libraries:

import (

If you get error message “cannot find package” when running a go program, try the procedure below.

NOTE: Go looks for packages first within the folder where you installed Go. If you installed using Homebrew, that would be like:


(from $GOROOT)

PROTIP: Don’t install packages under where Go is installed. This is so you won’t have problems after you upgrade to the next version.

  1. Create a $HOME/gopkgs folder to store 3rd party Go packages in one place.

    cd ~
    mkdir gopkgs
    cd gopkgs
  2. Create a $GOPATH environment variable to store a list of folders containing Go programs, separate by semicolons. In my ~/.bash_profile:

    export GOPATH=$HOME/gopkgs

    There can be a list in the path, separated by colons in Linux/Mac. Go searches each directory listed in GOPATH to find source code.

    CAUTION: New packages are always downloaded into the first directory in the list.

    See https://golang.org/doc/code.html#GOPATH

  3. Close Terminal and start it again, or

    source ~/.bash_profile
  4. Get a package from below. For example:

    go get github.com/stretchr/testify

    If nothing is returned, that’s a good sign.

    If there isn’t one, Go will have created a src folder.

    NOTE: The pkg folder holds installed package objects, such as “linux_amd64”.

    Also, within src is created a github.com folder.

    NOTE: Other “collaboration platforms” like GitHub include:

    • launchpad.net
    • bitbucket.com
    • gitlab.com

    For each 3rd-party library is created a folder for each GitHub user. For example, stretchr.

    cd ~/gopkgs/src/github.com
    mkdir stretchr
    cd stretchr

    Go get does the equivalent of cloning a package repo from GitHub. The manual equivalent of that is:

    git clone https://github.com/stretchr/testify --depth=1
  5. Compile to binary executables all files in current folder to $GOPATH/bin :

    cd $GOPATH
    go install .
  6. Create a folder to store your own Go programs. For me, I have a repository on GitHub: https://github.com/wilsonmar/golang-samples

    I’ve cloned that to my local folder at:


Install apps

To install the Go package for reading from continously updated files (tail -f)

go get github.com/arschles/go-in-5-minutes/tree/master/episode0
  • BLAH: The above returns an error.

  • This repo is described in videos at goin5minutes.com. Aaron Schlesinger, Sr. Software Engineer at EngineYard, describes how to write Functional Programming in Go for real projects.

The most popular Go packages on all of GitHub:

  1. https://github.com/stretchr/testify/assert A sacred extension to the standard go testing package

  2. https://github.com/gorilla/mux provides mux.Router which, like Go’s in-built http.ServeMux, matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. “Mux” stands for Multiplexor, to multiplex routes (URLs) to different handlers. Routers are also called dispatchers. This article says install using

    brew install go --cross-compile-common
    go get -u github.com/gorilla/mux

    The Gorilla mux allows devs to really lock down an API.

  3. https://github.com/Sirupsen/logrus by Simon Eskildsen @shopify
    Structured, pluggable logging for Go.

  4. https://github.com/gorilla/context
    A golang registry for global request variables.

  5. https://github.com/golang/protobuf/proto ???

  6. https://github.com/urfave/cli, formaerly
    A simple, fast, and fun package for building command line apps in Go.

  7. https://github.com/mattn/go-sqlite3
    sqlite3 driver for go that using database/sql

  8. https://github.com/go-sql-driver/mysql
    Go MySQL Driver is a MySQL driver for Go’s (golang) database/sql package

  9. https://github.com/BurntSushi/toml
    TOML (Tom’s Obvious, Minimal Language) parser for Golang with reflection. https://github.com/toml-lang/toml

  10. https://github.com/garyburd/redigo
    Go client for Redis

  11. https://github.com/golang/glog
    Leveled execution logs for Go

  12. https://github.com/onsi/ginkgo by Onsi Fakhouri @ Pivital
    BDD Testing Framework for Go http://onsi.github.io/ginkgo/

  13. https://github.com/onsi/gomega
    Ginkgo’s Preferred Matcher Library

  14. https://github.com/juju/errors at Ubuntu Canonical
    Common juju errors and functions to annotate errors. Based on juju/errgo. Model and deploy applications to any cloud

  15. https://github.com/juju/testing/checkers
    This package provides additional base test suites to be used with gocheck. Testing gocheck suites and checkers used across juju projects.

  16. Julien Schmidt’s router at https://github.com/julienschmidt/httprouter
    is a trie based high performance HTTP request router.

Kafka in Go

Kafka, a streaming commit log service, kinda like Git for applications data as a “system of record”. Kafka sends topics.

Zookeeper (ZK)


Cherami: Uber Engineering’s Durable and Scalable Task Queue in Go

Social #golang

Go users call themselves Gophers. Thus the logo.

Highest rated Go questions

Highest rated Go questions





Gopher Slack (invite.slack.golangbridge.org)


Hacker News


@GopherAcademy - gopheracademy.com

https://changelog.com/gotime podcasts

@cool_golang is a bot that automatically retweets any mention of #golang on Twitter.


@gophersauce - Golang backend web framework #golang #go checkout. “The easiest App SDK in the world.” https://github.com/cheikhshift/Gopher-Sauce/blob/master/tutorial.md


@GopherCon - https://gophercon.com/ - July 13-15, 2017 in Denver, Colorado


Rock Stars’ emissions

The Go language was invented within Google
by Robert Griesemer and Unix luminaries Rob Pike and Ken Thompson.[1]


  • https://talks.golang.org/2014/taste.slide#2

Rob Pike (Go Commander, Google)

TJ Holowaychuk is perhaps the most visible defector from Node, as he wrote Node. See https://goo.gl/WVxwtb

Russ Cox

Todd McLeod presents his deep knowledge in a laid-back style so it’s like being at a party:

Mike Van Sickle (@vansimke)

  • https://app.pluralsight.com/library/courses/creating-web-applications-go/table-of-contents

Mark Summerfield [1]

  • Book: Programming in Go: Creating Applications

Dave Chaney

  • https://dave.cheney.net/resources-for-new-go-programmers

  • https://talks.godoc.org/github.com/davecheney/introduction-to-go/introduction-to-go.slide#1

  • https://github.com/davecheney/introduction-to-go

Francesc Campoy

  • Google Developer Advocate

  • https://talks.golang.org/2017/state-of-go.slide#1

  • https://youtu.be/ynoY2xz-F8s Understanding nil

Nic Raboy

  • https://www.youtube.com/watch?v=t96hBT53S4U Create A Simple RESTful API With Golang

Brian Hatfield

  • @BrianHatfield

  • Tweets about GC pause times

William Kennedy

  • @goinggodotnet

Free Tutorials






My Code Samples

  1. Download or git clone my code samples for the Go language is at

  2. Open a Terminal shell window and give the files execute permissions:

    chmod 555 * 

    hello-time.go template

  3. cd to hello-time, which I use as the basis for creating new files.

    • print the elasped time of the program run.
    • define a date
    • calculate days from hours
    • format dates based on a template
    • see https://coderwall.com/p/l7e3fq/golang-time-function-wrapper
  4. A line at the top of the file enables it to be optionally run as a shell sript:

  5. Run it as a program:

    go run hello-time.go
  6. Build it

    go build

    A file with no file extension should appear in the folder on Linux. Extension .exe is added on Windows machines.

    When compiling packages, build ignores files that end in ‘_test.go’.

    To build an executable for running on other operating systems:

    GOOS=openbsd go build
    GOOS=windows GOARCH=386 go build
  7. Run the executable on Linux or mac:


    Alternately, on Windows, run the executable:


    PROTIP: All Go programs must be part of a package. main is the default package.

    • Global variable - start time.
    • Four character indent. gofmt indents using tabs that take 8 characters.

    For Multiple Operating systems

  8. View multi-platform.go

    Random number generator

  9. rand.go

    • Import flag to obtain arguments from command line
    • Reflection of elasped time is not appropriate here because it is intended to run as a utility.
    • Defined in a main plus separate utility functions.
    • Loop the number of repeats specified.
    • Slice of an integer array containing prime numbers. See https://tour.golang.org/moretypes/8 Notice there can be a ending comma after the last item in the list. This avoids one of the most annoying error messages in other languages.
    • Pointer

    Loop until manually stopped

    Within a main infinite loop:

    func main() {
      var input string
      for {
  10. switch

    • Print command to construct a line printed over several command lines
    • Recognize operating system being used by using “runtime.GOOS”.
  11. strings

    • One Println with several commands.
  12. latlong

    It manages latitudes and longitudes in a map data type containing a key-value structure.

    • Uses float64 floating point number for latitude/longitude
    • Uses function to do repeated lookups
  13. utf8

    It provides examples of counting and comparing Asian characters encoded in UTF-8.

    • Provides an illustration of fmt.Print() vs. fmt.Println() with escapted double-quotes.
    • Provides an example of using range.
  14. cd to env-vars (in Git branch env-vars)


    Different Operating Systems

Other tutorials

Structure of program files


Data Types

boolean constants are lower case: true, false

Numbers are not permitted at the start of an identifier (variable).

Go detects unused imports as an error.

Go has an array type, but most interactions are with slices which are built off arrays. I don’t worry too much about the name and just use them The specification for slices are “[]T” where T is the type. So “[]string” is a set of strings, “[]int” is a set of integers, and so on.


var n int = 4
var i = 0
for i = 1; i < n; i++ {

int is actually an alias! Like C, Go has signed and unsigned integers:

  • int holds a maximum value of 32,000.
  • int8,
  • int16,
  • int32,
  • int64

UTF-8 Data Types

Alias rune are single-character constants: ‘a’, す’, ‘シ’, ‘1’, …

When working with unicode you should be converting your strings to []rune. That’s why the utf8 package is so sparse, most things are covered by []rune conversion and the unicode package. The utf8 package is like a very thin abstraction layer for using strings as []rune.

All source code in Go is UTF-8, so you can use an emoji, Japanese Kanji, or other language in variable names:

    var π = 3.14159
    var radius = 6371.0 // radius of the Earth in km
    var circumference = 2 * π * radius
    println("Circumference of the earth is", circumference, "km")

Run result in scientific notation:

   Circumference of the earth is +4.003014e+004 km

See https://coderwall.com/p/k7zvyg/dealing-with-unicode-in-go

Developer Tools

  1. Display documentation for the Println function within fmt:

    godoc fmt Println

    Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.

Code Quality



https://github.com/google/shenzhen-go Visual Go environment

backtrace.io/go/ Reduce your time to resolution. Go beyond stacktraces and logs. Get to the root cause quickly with deep application introspection at your fingertips.

Agouti is an acceptance testing framework for Go.






https://github.com/influxdata/semaphore Distributed semaphore for Etcd in go forked at https://github.com/influxdata/semaphore


https://godoc.org/go.uber.org/zap Fast, structured, leveled logging in Go. forked at https://github.com/influxdata/zap





Testing/Error Handling

assert: extended core testing capabilities to write tests more easily

errors: improved error handling


if … { … } else { … }, switch { … }

Heavily nested if else if blocks are discouraged.

for (init statement); condition; (post statement) { … }

As Go is a strongly typed language, for two variables to be equal, both their type and their value must be equal.

while condition { … } and

do { … } while condition

do { … } until condition

// TODO: Control flow: break, fallthrough, continue, goto, return.

  1. sync.go uses Concurrency features.

    One of Go’s biggest strengths is that the concurrency features it provides are much easier to understand and use properly than threads and locks.

    Go has “goroutines” that are lightweight concurrency model based on coroutines. Goroutines do not use convoluted callback coding styles.

    PROTIP: The design of the Go language makes it work on multiple CPU cores. I can’t begin to state how important this is for scalability and speed.

    Go’s language runtime makes sure that there are enough threads to keep cores active.

    Go’s defer command.

    A defer statement defers the execution of a function until the surrounding function returns.

    The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.

    Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.

      for i := 0; i < 10; i++ {
     defer fmt.Println(i)

    See https://blog.golang.org/defer-panic-and-recover

Web server

https://github.com/GoesToEleven/golang-web-dev contains code for Tood McLeod’s WebDev class for Go at GreaterCommons.com.



A static web server to serve Jekyll generated static files:

// From https://coderwall.com/p/up2jbg/golang-static-files-server
package main
import "net/http"
func main() {
    http.Handle("/", http.FileServer(http.Dir("_site")))
    err := http.ListenAndServe(":8000", nil)
    if err != nil {

Profiling Go Code




flame graphs

go test -coverprofile

Output a cover profile as you are testing a package, then use go tool to visualize them on a browser.

go test -coverprofile=c.out && go tool cover -html=c.out


go test -bench=.

https://newrelic.com/golang monitor

Protocol Buffers (Protobuf)



### Webpage folder templates

  1. In webpage, main.go uses a templating capability with mustache markers:

    • Display a line before running as a server which locks no command line input:
    fmt.Println("Use internet browser to view localhost:8080.")
    fmt.Println("Press control+C to stop server.")
    http.ListenAndServe(":8080", nil)

Code Generators

https://github.com/erizocosmico/go-itergen by Santiago M. Mola (@mola_io) generates Go source files

https://godoc.org/text/template Go Package Templates use moustaches around variables.


https://github.com/uartois/sonar-golang Sonarqube plugin for the golang language created by Falque Thibault with 34 rules from GoLint.

https://github.com/qfarm/qfarm Sonar for Golang - PoC created during 24h hackaton



Machine Learning

https://github.com/sjwhitworth/golearn reads a databse of iris flowers, as KNN (Nearest Neighbor) makes predictions using the training dataset directly. k is just the number of neighbors “voting” on the test example’s class. See http://machinelearningmastery.com/k-nearest-neighbors-for-machine-learning/




  • https://blog.gopheracademy.com great resources for Gophers in general
  • http://gotime.fm awesome weekly podcast of Go awesomeness
  • https://gobyexample.com examples of how to do things in Go
  • http://go-database-sql.org how to use SQL databases in Go
  • https://dmitri.shuralyov.com/idiomatic-go tips on how to write more idiomatic Go code
  • https://divan.github.io/posts/avoid_gotchas will help you avoid gotchas in Go


  • http://www.golangbootcamp.com/book
  • http://gopl.io/
  • https://www.manning.com/books/go-in-action (if you e-mail @wkennedy at bill@ardanlabs.com you can get a free copy for being part of this Slack)


  • https://www.slideshare.net/appleboy/write-microservice-in-golang