GO Alphabets Plus

KT
3 min readMar 19, 2019

GO is fun to learn and having good documentations to start with. You can take Go Tour https://tour.golang.org/welcome/1

Refer to installation and learning guides and blogs https://golang.org/doc/

GO Idiomatic to refer to https://dmitri.shuralyov.com/idiomatic-go. Good to know some Anti-Patterns. https://about.sourcegraph.com/go/idiomatic-go

Alright, here’s some of the pain points seen by me and folks I worked with.

GO Exported/Unexported

Like in Java we have private and public methods, GO has a similar concept called Exported/Unexported. And its established using case. duh!

In Go, a name is exported if it begins with a capital letter. For example, OAuthEnabled and GitHubToken is exported

oAuthEnabled and gitHubToken do not start with a capital letter, so they are not exported.

When importing a package, you can refer only to its exported names. Any “unexported” names are not accessible from outside the package.

// Exported.
var OAuthEnabled bool
var GitHubToken string

// Unexported.
var oauthEnabled bool
var githubToken string

Date/Time formatting

This was super pain for me, spent significant hours in understanding it.

Go doesn’t use yyyy-mm-dd layout to format or parse a time. Instead, you format a special layout parameter

Mon Jan 2 15:04:05 MST 2006

the same way as the time or date should be formatted. (This date is easier to remember when written as 01/02 03:04:05PM ‘06 -0700.)

Here’s links to refer and learn

Below is the snippet of our Epoc to UTC conversion. Keep a watch on number of ZEROs in epoc time when you are doing the conversion, otherwise conversion might go off. Epoc time in secs has 10 digits. In my snippet, epoc time was in milliseconds so I had to divide by 1000 before conversion.

Packages and Project layout

We begin with flat structure wrote everything in main package. It was manageable in the beginning later it turned out to be pain since within package everything is accessible by any go file. Don’t get into tiny package syndrome but organize your code to be more readable.

We liked the Actor Model she referred to in below video, we did some more study and end up using it. In our micro-service we have many actors :)

Use channels to communicate between GO routines

We had the use case to execute some steps in parallel and some in sequence. We started with Mutex and sharing the memory. It was working for us but more error prone in long run. In GO, channels are meant to communicate between GO routines so we moved to channels. Followed Rob Pike saying.

The Go approach : Don’t communicate by sharing memory, share memory by communicating.

Closing Response body and Channels

We had memory leaks, coz channels and response bodies were not closed properly. Use of defers were helpful. It make sure connections are closed properly before function returns.

Error Handling

Handle all types of errors. Connection errors, timeouts, read errors, unmarshal errors.

--

--