Write a simple server with Go

Backend development is a hot topic right now, and there are literally thousands of languages to write a server with. You have the oldest contender PHP, you have Ruby, Python, Java, C++, JavaScript and a plethora of other languages.

Golang, or just go, is relatively newer in this field. It’s written by Google, and is compiled and statically typed and is focused mainly towards networking. Here are some of the features of Go that make it a great choice to run on a server

  1. Speed: Go is compiled to machine code, which makes it really fast and gives an edge over other interpreted languages like Ruby, Python or JavaScript.
  2. Static typing: Go is statically and strongly typed language. So the compiler can catch a lot of errors due to variable types during compilation. For example, in JavaScript, sudden type coercion can lead to unexpected results or errors during runtime (think of “5” + 5 = “55”). This is not the case with Go.
  3. Easy to learn: Go’s syntax is inspired from C and is easy to learn. Go isn’t overburdened with features and doesn’t take a long time to grasp the concepts.
  4. Concurrency: This is Go’s selling point. Go has goroutines which are lightweight processes. Go does not only provide CPU parallelisms but also asynchronous operations. Using a coroutine is as easy as putting go in front of a function name, and communicating between goroutines are really easy through channels.
  5. Great standard library: Go has a rich standard library that makes it easy to handle I/O, writing servers, managing cryptography works etc.
  6. Testing: You don’t need to have any external dependency to test. If you have file.go write your tests in file_test.go and then run go test and voila!

Now let’s write a simple little server in Go. This will just be a basic server which will give you the current time.

Installing Go

First you need to install Go. For that I’ll send you off to the official docs.

After you have installed Go, you can move on to the coding part.

Setting Up

Now first, let’s create the project folder. At this point, we probably don’t need a folder, but we will expand on this server later and add more features, so it’s better to have a proper structure.

First we’ll create a directory named “go-server” in the Go installation directory. On Linux, that would be ~/go/src/. On Linux, you can run this command –

mkdir -p ~/go/src/${USER}/go-server

Now you’ll have a directory under ~/go/src/your_username/

Writing the server

We are now ready to write the code, but first we need to download the mux package. So run this command –

go get -u github.com/gorilla/mux

This will install the mux package so that we will be able to use it in our project.

Now move to the directory you just created and create a file called main.go and write the following

package main

import(
        "fmt"
        "net/http"
        "github.com/gorilla/mux"
        "time"
)

func main() {
        r := mux.NewRouter()
        r.HandleFunc("/time", GetTime)
        http.ListenAndServe(":8000", r)
}

func GetTime(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Current time is %s\n", time.Now())
}

Let’s try to understand what’s happening.

package main

This line tells the compiler that the file is part of the “main” package. Packages can be thought of as logical units that can be imported elsewhere.

import (
...
)

This line imports the 4 packages we’ll be using.

  1. fmt: To format and write the response
  2. net/http: To create the server
  3. mux: To write the router
  4. time: To get the current time
func main() {
...
}

This defines the main function. This is the function that will be run.

r := mux.NewRouter()

This creates a variable named r which is a mux router. A router manages the routes of your server. It takes an incoming request and matches is against a set of registered routes and accordingly drives the request.

r.HandleFunc("/time", GetTime)

Here we register a route called “/time” and tell the router that if we have a request in the “/time” route, you invoke the GetTime() function (defined later)

http.ListenAndServe(":8000", r)

Finally, we start the server at port 8000 and pass the router.

Let’s take a look at the GetTime function

func GetTime(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Current time is %s\n", time.Now())
}

The route functions must take two parameters. One is a http.ResponseWriter and another is a *http.Request (pointer to http.Request) Here we have named the w and r respectively.

w will be used to write to the response, and r will be used to access the request. Here we don’t have anything to get from the request so we just write to the response using fmt.Fprintf. We take the current time using time.Now() .

Running the server

Make sure you are in the same directory as the main.go file. Then run this command –

go run main.go

Now you’ll be able to hit localhost:8000 and get a response –

curl localhost:8000/time

And here’s the response –

Current time is 2018-10-13 00:34:09.017262763 +0530 IST m=+1.012663595

Conclusion

So now you know how to write a simple server in Go. Later we will expand on this server and explore other possibilities that Go has to offer.

Comment below if you have any doubts. If you like the blog, consider sharing, and don’t forget to subscribe!

Aniket Bhattacharyea

Aniket Bhattacharyea