Learning Go

I’m new to Go, and I want a crash course in building services with it. Note that this is not a “blog post” in the traditional sense. I’ll be updating this over time as I learn more.

Learning Go resources

I think anyone’s first stop should likely be the official documentation. The Go Tour takes you through a bunch of the language features interactively, step-by-step, without needing to install a thing.

A blog post with comments: How I write Go services after seven years

Mat Ryer wrote a post in May 2018 called How I write Go HTTP services after seven years. This seems like a good starting point, because 7 years is a long time in Go history.

I often find some value in reading comments about such posts to see what agreements and disagreements there are. Here is the Reddit thread for the post. There weren’t as many Hacker News comments. Another HN thread had 2 comments.

Database handling

Practical Persistence in Go describes a few different ways to approach accessing databases within Go.

While there are ORMs for Go, I’m more inclined to start with straight-up SQL. Go has a built-in dbapi/JDBC-like interface for talking to databases. Beyond that basic interface, there is sqlx, which adds some extra capabilities:

  • Marshal rows into structs (with embedded struct support), maps, and slices
  • Named parameter support including prepared statements
  • Get and Select to go quickly from query to struct/slice

Testing database interactions in Go provides links to a handful of tools that help with running tests against databases.

Logging

Go has built-in logging, but if we wanted to do structured logging we might need to pick up a different package.

Web serving

Many people just stick with Go’s built-in web server. Gin is a popular alternative that claims to offer very fast routing, among other features.

Error handling

Error handling is one of those things that bugs people coming from the land of exceptions. Go’s explicit error handling is simple and makes sure that you’re considering your errors, but it can also get noisy. There’s a proposal for check/handle to make it a bit less noisy while still being fundamentally the same error handling model. Better Error Handling, in Go describes an approach which can be used today to make certain error handling situations a bit cleaner.

Separate services in a single repository?

At Khan Academy, we currently work in a monorepo. Given that we’re starting with Go now, it would seem to make sense to use Modules, rather than starting from the GOPATH approach.

Quite a few tools don’t yet support Modules, but I was able to get a setup going which had multiple modules in a single repository by using the replace directive in the go.mod file. The resulting code compiled fine and I had no trouble editing it in VS Code.