An Elaborate Web Server

This lesson covers all the primary services provided by a server by implementing a detailed web server, and showing how each service is delivered independently.

To further deepen your understanding of the Http package and how to build web server functionality, study and experiment with the following example. First, the code is listed, then, the usage of the different functionalities of the program and its output are shown.

The example below demonstrates various ways in which you can write web server handlers. The web server itself is started at line 43 in main() with error-handling in the following lines.

Package expvar provides a standardized interface to public variables, such as operation counters in servers. A variable containing the number of hello requests is defined at line 15, and a struct Counter at line 22 as well as a channel of integers at line 27. Also, some command-line flags are defined (from line 17 to line 19, which are then parsed at line 30.

Then, from line 31 to line 42, we define all of the handlers, which are used by this webserver. At line 34, we define a new Counter variable named ctr. Then, at line 36, we publish ctr, which is global to the webserver.

More detailed explanations of each of the web server handlers can be found below, which also shows you which request URL corresponds to which handler function.

Get hands-on with 1200+ tech skills courses.