A Peek at a Tiny Web Server

The famous few lines that serve the web

8 min read

You made it to the final lesson, and you have earned the classic Go party trick: a complete, working web server in about a dozen lines. You will not run this one inside Gwecode, but by the end of this lesson you will understand every line, using only ideas you already know.

The whole program

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello from your Go server!")
}

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

That is not a toy or a sketch. Run this on your own computer with Go installed, open a browser at localhost:8080, and you get a real page served by your own code.

How the web works, in one paragraph

When you visit a website, your browser sends a request to a server: please give me this page. The server sends back a response: here it is. A web server is simply a program that waits for requests and writes responses, forever. Sound familiar? It is the forever loop from the for lesson, wearing a suit.

Reading the server line by line

  1. import ("fmt", "net/http") brings in printing tools plus net/http, Go's built-in web toolbox.
  2. func handler(w, r) is a normal function with two parameters: r holds the incoming request, and w is where you write your response. Anything you write to w travels back to the visitor's browser.
  3. fmt.Fprintln(w, ...) is Println's sibling: instead of printing to your screen, it prints into w, and from there to the browser.
  4. http.HandleFunc("/", handler) says: when someone asks for the front page, the path /, run my handler function.
  5. http.ListenAndServe(":8080", nil) starts the forever loop, listening for visitors on port 8080. A port is like a numbered door on your computer, and 8080 is a favorite for practice servers.

Notice what you did NOT need: no framework, no downloads, no configuration files. A production-quality web server ships inside Go's standard library, which is exactly why so many of the internet's back-end services are written in Go.

Where you go from here

Look back at where you started: twelve lessons ago you had never seen a line of Go. Now you can read packages, variables, ifs, loops, functions, slices, maps, structs, and even a web server. Some friendly next steps:

  • Install Go from its official site and run the hello program from lesson one for real.
  • Try the Tour of Go, a free interactive walkthrough that will feel comfortable now.
  • Grow the little server: make different paths like /about answer with different messages.

Thank you for learning with us, and happy coding. You are officially a Go programmer at the start of the road, and the road is wide open.

Quick check

Q1 In the handler function, what is w for?

Q2 What does http.ListenAndServe(":8080", nil) do?

Want to save your progress? It's free.

Create a free account