0. Setting up your environment

Installing Go

You can find the instructions for installing Go on your OS here.

Once you have installed Go you can run the following command to verify that the installation succeeded:

$ go version
go version go1.16 darwin/amd64


For programming in Go, I use Visual Studio Code as my IDE with the Go extension and I highly recommend using it.

1. Boilerplate

Let’s create a new directory, and set up the boilerplate code.

$ mkdir go-microservice
$ cd go-microservice
$ git init
$ go mod init github.com/rohitjha/go-microservice

This is the content of my go.mod file:

module github.com/rohitjha/go-microservice

go 1.16

2. A Simple HTTP server

Let’s create a very simple HTTP server in a file main.go at the same level as the go.mod file. Here are the contents of the file:

package main

import (

func handler(rw http.ResponseWriter, r *http.Request) {
    message := "Hello, World!\n"

func main() {
    http.HandleFunc("/", handler)

    log.Println("Starting Server")
    err := http.ListenAndServe(":8080", nil)

We’re using the net/http package from the Go standard library to build our simple HTTP server. The function handler is associated with the / URL path and is invoked when an HTTP request is made to http://localhost:8080/. The function logs the message string to the console and also returns it as the response body through the call to rw.Write().

Building and running the server

To start the server, let’s build and run the program:

$ go build main.go
$ ./go-microservice
2021/02/28 19:06:00 Starting Server


Once the server is running, you can use curl to make a request:

$ curl http://localhost:8080/
Hello, World!

And there will be a log line:

2021/02/28 19:06:00 Hello, World!

To look at other details such as status code and headers, let’s run curl with the verbose flag -v:

$ curl -v http://localhost:8080
*   Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> GET / HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.64.1
> Accept: */*
< HTTP/1.1 200 OK
< Date: Mon, 01 Mar 2021 03:59:53 GMT
< Content-Length: 14
< Content-Type: text/plain; charset=utf-8
Hello, World!
* Connection #0 to host localhost left intact
* Closing connection 0


In this part of the tutorial, we’ve set up our environment and built a simple HTTP server that returns a response. Astute readers would have observed that our handler returns the same response regardless of the HTTP method (GET, PUT, POST, DELETE, etc.) of the request. We’re going to improve our server in future tutorials so that we have different logic for different methods.

You can find the code for this part of the tutorial here.