Building a Web Application using Golang

Golang

As a software engineer, it is always interesting to learn a new programming language. At Osprey Security, when it turned out that I would be involved in a project with Go or Golang as it is also referred to, as the primary back-end language, it was a really exciting feeling. The fact that Golang was designed to be a good fit for server side programming added more spice to all this.

Here I’m going to share my first impression on the language. Quite a few features of Golang will be described in the prism of Java which I used a lot last years.

Syntax Description

What is striking for a Java developer is that Golang is not an object oriented language in a pure sense of this word. Yes, it has structures and you can call functions on those structures, as if you call methods in OOP language but there is no inheritance. Golang uses composition instead. Go front end vs. backendis not functional, but it has anonymous functions, high order functions and so on. As for me, I see Go as procedural language. If somebody asks me to describe Go, I would say… like C.  As in C, there is no exception handling, but functions return error codes instead. There is no function overloading as it regarded a bad practice, but there is support for pointers!

My Choice of a Code Editor for Golang

hello worldGo is a comparatively new language but there are a lot of editors which one can use to write code in. You can use vim or emacs or choose some specialized IDE, for example LiteIDE. In the beginning, I started with LiteIDE, but it seems too simple as if you are working in an ordinary text editor. Later on, I found out that there is a Go plug-in for Intellij Idea similar to the one I used for Java development. Yay!! So I hurried to install the plug-in. It is not quite mature and doesn’t have the full power of Intellij but I am very comfortable with it.

Dependency Management

In the Java world, you can specify your dependencies in Maven and it will take care of other things for you. For Go, there is nice little tool called godep and it works a little differently. First, you have to import all the dependencies manually with the “go get” command. Then call godep save and it will automatically save the list of your dependencies in a file (similar to pom.xml file). You can later distribute this file alongside with your source. By having that file on another machine, you can simply run godep restore to restore dependencies.

How to build a REST API in Golang –  sample code

Go was created keeping the server-side paradigm in mind. So let’s see how easy it is to create a REST API in Golang. I’m not going show something complex here but just a simple end point. Go has an embedded request router but it is limited to fixed paths. Its alternative Gorilla Mux is very powerful and reliable router. Let’s look at the code first.

package main

import (

       "github.com/gorilla/mux"

       "net/http"

       "strconv"

       "encoding/json"

)

type user struct {

       Id   int    `json:"id"`

       Name string `json:"name"`

       Age  int    `json:"age"`

}

var users []user

func usersHandler(w http.ResponseWriter, r *http.Request) {

       vars := mux.Vars(r)

       id, err := strconv.Atoi(vars["id"])

       if err != nil {

              w.WriteHeader(http.StatusBadRequest)

              return

       }

       if id > len(users) || id < 1 {

              w.WriteHeader(http.StatusNotFound)

              return

       }

       user := users[id-1]

       output, err := json.Marshal(user)

       if err != nil {

              w.WriteHeader(http.StatusInternalServerError)

              return

       }

       w.Header().Set("Content-Type", "application/json")

       w.Write(output)

}

func main() {

       users = []user{user{1, "Alex", 42}, user{2, "Max", 30}}

       router := mux.NewRouter()

       router.HandleFunc("/users/{id:[0-9]+}", usersHandler)

       http.ListenAndServe(":8888", router)

}

First we create new router and set userHandler function to serve the end point. Pay attention to expressions in curly braces. There we define path variables and a regular expression pattern for it. Then we begin to listen on port 8888. That’s it! We have working end point and the only thing we have to define is to create a function which will serve requests! In this function we simply return value from array.

user := users[id-1]

Pay attention that Go has embed utilities to work with JSON.

output, err := json.Marshal(user)

The following line serializes a structure to JSON.

type user struct {

       Id   int    `json:"id"`

       Name string `json:"name"`

       Age  int    `json:"age"`

}

may produce something like this

{"id":2,"name":"Max","age":30}

JSON fields names are defined via reflection like json:”id”.

Go has not exceptions so functions usually returns errors as second parameter in result.

if err != nil {

//error handling code here

}

Error handling is a common pattern as you can see in the snipped above.

The rest of the code is self explanatory. I hope that you get the idea of using Go!

So it’s clear that creating an API with Go is a trivial task. The language has everything for this. You don’t need any third party frameworks or libraries but you can choose one if you are not satisfied with native library support. Error handling is old fashioned but I don’t think that it makes things more complicated.

It’s easy to start with Go but more time is needed to clearly understand all its advantages and disadvantages. I hope the language will provide us with more pleasant surprises!! Now let’s Go!

Latest posts by Ruslan Kuskuldin (see all)


Comments

  1. I have noticed you don’t monetize your website, don’t waste
    your traffic, you can earn extra bucks every month because you’ve got high quality content.
    If you want to know how to make extra $$$, search for: Mertiso’s tips best adsense
    alternative

Leave a Reply

Your email address will not be published / Required fields are marked *