back to blog overview

A Web Server in Golang in 10 Minutes

Let’s create a simple web server in GO/Golang in a couple of minutes which serves static files and a function.

The GO programming language -or if you search it on the web: Golang- is becoming more and more important for backend developers, especially when it comes to implementing an API. Many developers like GO/Golang because backing coding with it is fun. I also like it, although I cannot really tell why. Maybe it’s because of my previous work in parallel programming.

You’ll have to try it for yourself. Let’s have a closer look.

Installing GO/Golang

Installing is pretty easy. Download and follow the instructions for your operating system at the GO install page. For Windows and Mac it’s pretty straight forward. Linux requires adding the install directory to the search path.

Hello World - or even better: Hello GO!

Here is our first GO program:

package main

import "fmt"

func main() {
	fmt.Println("Hello Go!")

}

Save it as hello.go and can run it with go run hello.go. It contains a main function which is called when running the program from the comannd line. The program should do what it says and print print out a classic “hello world”. We are using the formatted i/o package fmt to print our message. We will need it in our next steps.

A HTTP/Web Server in Go serving Static Files

Now we are creating a web server which is serving static files like HTML and images. To do so, we import the net/http package. The import can be done in one import statement. In main we first define a port variable by using the GO short declaration (:=). After that we create a HTTP file server, called http.FileServer, and tell the web server that it will handle the static requests for the root directory /. http.ListenAndServe activates the web server. We now need afiles subdirectory which contains some static data. Save the code as servers.go and run it with go run servers.go.

package main

import (
	"fmt"
	"net/http"
)

func main() {
	port := "55005"
	httpFileServer := http.FileServer(http.Dir("./files"))
	http.Handle("/", httpFileServer) 

    fmt.Printf("Listening http://localhost:%s\n", port)
    if error := http.ListenAndServe(":"+port, nil); error != nil {
         fmt.Printf("Error: %s\n", error)
    }
}

You can now open all static files with your web browser pointing to http://localhost:55005.

Serving a function with GO

Static files are ok, but more interesting are functions, which do something. With functions you may create an API which allows access to database content or which does any kind of calculations. We will create a simple function, which returns a string. To do so we define the handler function testHandler which will handle the request. The function receives the http.Request and a http.ResponseWriter as parameters. The first one is a reference to the HTTP request, the latter we will use to write the response. We then test the request. If it’s a GET then we write out a text. Otherwise we return an error. In the main function our handler function is added to the web server’s routes by stating http.HandleFunc("/test", testHandler). The route /test will cause now a call of our handler function. Save it as dynamic.go and run it with go run dynamic.go.

Here is the complete code.

package main

import (
	"fmt"
	"net/http"
)

func testHandler(rw http.ResponseWriter, req *http.Request) {
   if req.Method == "GET" {
	   fmt.Fprintf(rw, "You requested the TEST function.")
   }else{
	   	responseText:= fmt.Sprintf("Method %s is not supported.", req.Method)
        http.Error(rw, responseText, http.StatusNotFound)
        return
    }
}

func main() {
	port := "55005"
	httpFileServer := http.FileServer(http.Dir("./files"))
	http.Handle("/", httpFileServer) 

	http.HandleFunc("/test", testHandler)

    fmt.Printf("Listening http://localhost:%s\n", port)
    if error := http.ListenAndServe(":"+port, nil); error != nil {
         fmt.Printf("Error: %s\n", error)
    }
}

A Word on Concurrency

GO is percepted as a good language for concurrency. But where is the concurrency in our example here? The HTTP server which we are using is working with concurrency. The requests are handled concurrently and -if the hardware is able to provide this- executed in parallel.

Where to GO next

So where to GO next? If you just playing with GO at this time and want to learn GO in detail, try the Tour of GO.

December 27, 2020
Words: 700 | Reading Time: 4 min

back to blog overview

back to home page