I have recently started integrating golang into more of my projects. It is an amazing little lanaguage with cool syntax, a huge community, and it’s a nice break from interpreted languages like Python and Ruby. In this tutorial, I am going to show you how to make an HTTP GET call to a public API, parse the ruturned JSON data, and store it all in golang structures.
Lets uses the citibike API as a simple example. As you can see, this API call does not require any authenication so no need to sign up for anything. The output should look something like the following:
The first step is to use golang’s http module to get the response:
Assuming you didnt see a panic call, the response to this http call is being stored in the res variable. Next, we need to read the http body into a byte array for parsing/processing (using golangs ioutil library):
Now that you have the http body, we are going to extract the JSON parameters into go structs so they can be easily accessed in other go programs. There are many different ways to do this, but I am going to use two separate golang
structures Station and StationAPIResponse
As you can see, StationAPIResponse contains an array of Station objects. All of the parameters coming from the citibike API can be accounted for here. Finally, I have a function that takes in the body, and returns a pointer to the array of StationAPIResponse`
Putting it all together, you can use the above code as follows:
If you want to use this code in another go program, I created a package you can pull down on github.
As always, if you are interseted in this type of content (python, go, machine learning, math), follow me on twitter. If you find any bugs, send me a pull request!