The Simplest Go Web Server

This particular instance will only return a string of text. I don’t think you can really get more basic than that.

Purpose

This article is meant to introduce you to the Go language and useful Go libraries.

Prerequisites

You will need to have installed Go on your machine. If you haven’t done so, you can find setup instructions here. I will be using Visual Studio Code as my IDE. I have installed the rich Go language support package which adds intelligence and shortcuts to the IDE.

For this example, we will be running an executable. If you are running a Linux distribution you will need to make use of Wine.

Getting started

Open up Visual Studio code and create a new directory within your Go Workspace. My directory is Go/example. Inside of that directory, open a new file and write your boiler plate set up for a go application. Save the file as main.go.

package main
import (
"fmt"
"net/http"
)
func main() {
}

If we ran this now, with $ go run main.go, we would see nothing. We have the skeleton of a Go app but our application does nothing. In order to return our basic string, we will need the “fmt” library and in order to respond to an Http request, we will need the Go “net/http” library. Add those imports to your main.go.

You should now see red underlining indicating to you that you have not used your imports. That is because Go is extremely efficient and will not allow you to build unused items because that undermines Go efficiency.

We will also want to tell our web server where to listen in, for this example we’ll listen on port 8080. Using our “net/http” library we are able to use the ListenAndServe function. Once we add this function you will also see that the error indicator for the “net/http” library is removed because we now have used this import.

We still cannot run this example because we haven’t made use of our “fmt” library, but we have set up our server to listen on port 8080 and we have the core structure. All that is left is to add a handler to process our request and return a string.

For this we will make use of another “net/http” function, HandleFunc. HandleFunc takes two parameters, the url path parameter and the function which will be called by the url.

The path for HandleFunc will be /text/ to keep things simple and it will call a function named textHandler and return “Hello World”.

For our fans textHandler to handle the HTTP request and provide a response, it will take in two parameters. This handler will need a ResponseWriter which will allow us to render our text and a Request which represents an HTTP request received by a server. Make sure to write your function handler above your port listener or your server will never hit the function handler and all you will see is a page not found.