Creating a Web Server

Let’s create a barebones web server with Go.

We'll cover the following

This lesson presents a simple web server developed in Go in order to better understand the principles behind such applications.

Note: Although a web server programmed in Go can do many things efficiently and securely if what we really need is a powerful web server that supports modules, multiple websites, and virtual hosts, then we would be better off using a web server, such as Apache, Nginx, or Caddy, that is written in Go.

We might ask why the presented web server uses HTTP instead of secure HTTP (HTTPS). The answer to this question is simple: most Go web servers are deployed as Docker images and are hidden behind web servers such as Caddy and Nginx that provide the secure HTTP operation part using the appropriate security credentials. It does not make any sense to use the secure HTTP protocol along with the required security credentials without knowing how and under which domain name the application is going to be deployed. This is a common practice in microservices as well as regular web applications that are deployed in Docker images.

The net/http package offers functions and data types that allow us to develop powerful web servers and clients. The http.Set() and http.Get() methods can be used to make HTTP and HTTPS requests, whereas http.ListenAndServe() is used for creating web servers given the user-specified handler function or functions that handle incoming requests. Because most web services require support for multiple endpoints, we end up needing multiple discrete functions for handling incoming requests, which also leads to the better design of our services.

The simplest way to define the supported endpoints, as well as the handler function that responds to each client request, is with the use of http.HandleFunc(), which can be called multiple times.

Coding example

After this quick and somewhat theoretical introduction, it is time to begin talking about more practical topics, beginning with the implementation of a simple web server, as illustrated in wwwServer.go:

Get hands-on with 1200+ tech skills courses.