Learn go series: Part I - Hello World as a service

Mon Dec 18 2017

This is Part 1 of "Learn go" series. This series assumes you have a general familiarity of the golang syntax and types. If not, I urge you to follow the interactive tour of go and/or watch Russ Cox's video

In this post, I will be walking you through an example of writing a Hello World json end point. So lets begin with...

As with many other languages, golang begins execution with main function. By convention, functions to be exported begin with capital letters. Here, we have imported fmt package which exports Println function.

I have been dabbling with go for almost a month now, and honestly, the entire language feels like a web framework. It has a ton of niceness baked right into it. You can pretty much skip importing libraries for most tasks. Let me give you an example of writing a native API from golang docs

As you can see, this works pretty well and we didn't even import any third-party libraries. Hold on, we aren't done yet though. Let's say I want the API to look like: http://localhost:8000/hello/{yourName}. Or I only want it to work with GET method. I have some other functionality in mind for POST.

It is quite possible with the native HandleFunc and the handler functions to add these functionality (cough switch case cough), but the code quickly becomes unwieldy. Let me walk you through one of my favorite solutions for such occasions - mux from the Gorilla toolkit.