Go is an exciting programming language for building modern-day web applications as well as systems software. It swept the tech industry at its release and is powering services like Docker, Kubernetes, Terraform, Dropbox, and Netflix.

Moreover, Go's robust collection of built-in packages make it an excellent choice for web programming. This article will teach how you write a basic web server in Go.

Importing the Necessary Packages

The net/HTTP package offers everything needed for creating web servers and clients. This package exposes several useful functions for dealing with web programming.

You can import it by adding the below line at the top of your source code:

        import "net/http"
    

We're also going to use the fmt package for formatting strings and the log package for handling errors. You can either import them individually as shown above or factor all of the packages using a single import statement:

        import (
    "fmt"
    "log"
    "net/http"
)

You can proceed to write the main function after you import the required packages. Go ahead and save the source file with a .go extension. If you're using Vim, use the below command to save and quit Vim:

        :wq server.go
    

Writing the Main Function

Go programs live within the main function, aptly named "main." You'll need to implement the server call here. Add the following lines in your source code and see what they do:

        func main() {
    http.HandleFunc("/", index)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

We're defining the main function using the func keyword. Go has strict rules regarding the placement of the opening brace, so make sure the starting brace is on the correct line. The first statement in main defines that all web requests coming to the root ("/") path will be handled by index, a function of the type http.HandlerFunc.

The second line starts the web server via the http.ListenAndServe function. It signals the server to continuously listen for incoming HTTP requests on port 8080 of the host machine. The second parameter of this function is needed to block the program until termination.

Since http.ListenAndServe always returns an error, we're wrapping this call inside a log.Fatal call. This statement logs any error messages generated on the server-side.

Implementing the Handler Function

As you can see, the main function calls the handler function index for processing client requests. However, we've yet to define this function for our server.

Let's add the necessary statements to make the index function usable:

        func index(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, welcome to %s!", r.URL.Path[1:])
}

This function takes two different arguments of type http.ResponseWriter and http.Request. The http.ResponseWriter parameter contains the server's response to the incoming request, which comes in the form of an http.Request object.

The Fprintf function from the fmt package is used for displaying and manipulating text strings. We're using this to show the server's response to our web requests. Finally, the r.URL.Path[1:] component is used for fetching data that comes after the root path.

Adding All Pieces Together

Your Go web server should be ready once you've added all the pieces together. The code should look similar to the following:

        package main
import (
    "fmt"
    "log"
    "net/http"
)

func index(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, welcome to %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", index)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

The first line is needed for compiling this Go web server code as an executable file.

Simple web server built with Go

Build Web Servers with Go

Go's robust library packages facilitate web programming for beginners. You can quickly develop simple web servers with only a few lines of code.

Moreover, the powerful testing features of this programming language also make it easy to implement Agile programming methodologies. These are a group of software development strategies based on iterative development and extensive collaboration between teams.