Learn Go · 15/18

Building Web Servers

10 min read

Hello there, future Go web developer! 👽 Welcome to the guide on building web servers.

So, you've learned the Go basics, and now you want to make your programs talk to the rest of the world through the internet. You're in the right place! We're about to turn your Go program from a quiet command-line tool into a bustling hub of web activity.

Let's get this server started!


1. The net/http Package Basics 📦

The Definition & The Problem

A web server is a program that listens for requests from clients (like a web browser) over the HTTP protocol and sends back responses.

The problem is, your Go program doesn't know how to speak HTTP out of the box. It doesn't know what a "GET request" is or how to format a "200 OK" response. We need to give it the tools to listen for, understand, and reply to these web requests.

The Solution: The net/http Package

Go comes with a powerful built-in package called net/http that has everything you need to build a production-ready web server without needing any external frameworks. It's like getting a full professional kitchen toolkit included when you buy a house.

Let's start with the absolute basics. Our goal is to create a server that, when you visit it in your browser, just says "Hello, Web!".

The Core Components

To get a server running, you need to know about three key things:

  1. http.ListenAndServe(): This is the function that kicks everything off. You tell it which address to "listen" on (e.g., localhost:8080) and who should handle the incoming requests. Think of this as opening your restaurant at a specific street address and handing the keys to a manager.

  2. http.HandleFunc(): This function registers a handler function for a given request path. It's like telling your manager, "When someone asks for the /menu path, I want this specific person (function) to handle their request."

  3. The Handler Function: This is the function that actually does the work. It always has the same signature: func(w http.ResponseWriter, r *http.Request).

    • http.ResponseWriter (w): This is your tool for sending a response back to the client. It's like the waiter's notepad and voice; you use it to write the reply.
    • *http.Request (r): This contains everything about the incoming request from the client—the URL they asked for, the headers they sent, and any data in the request body.

Example: Hello, World! Server

Create a file named main.go and add the following code.

go
package main

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

// helloHandler is our function for handling requests to the "/" path.
func helloHandler(w http.ResponseWriter, r *http.Request) {
	// We use Fprintf to write the string "Hello, Web!" into our ResponseWriter.
	fmt.Fprintf(w, "Hello, Web!")
}

func main() {
	// Register our helloHandler function to handle all requests to the web root ("/")
	http.HandleFunc("/", helloHandler)

	fmt.Println("Server is starting on port 8080...")
	// Start the server on port 8080.
	// The second argument `nil` tells it to use the default request handler we just configured.
	// ListenAndServe will block forever unless it encounters an error.
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

To run this:

  1. Open your terminal.
  2. Navigate to the directory where you saved main.go.
  3. Run the command: go run main.go
  4. Open your web browser and go to http://localhost:8080.

You should see "Hello, Web!" in your browser. Congratulations, you've just built a web server! 🎉


2. Creating RESTful Routes and Handlers 🚦

The Definition & The Problem

Routing is the process of directing an incoming request to the specific code that can handle it based on its URL path (e.g., /users, /products/123).

The problem with our first server is that it does the exact same thing for every single request, whether the user asks for /, /about, or /anything-else. This is like a restaurant where the only thing on the menu is a glass of water. We need a way to offer different things at different paths.

The Solution: The ServeMux

A ServeMux, or HTTP request multiplexer, is Go's built-in router. Its job is to look at the URL of an incoming request and match it to the correct handler. When you were using http.HandleFunc, you were actually using a global DefaultServeMux behind the scenes.

While the default one is fine for small apps, it's a better practice in the industry to create your own. This avoids potential conflicts if you import a third-party package that also registers routes on the default mux. It's like hiring your own dedicated restaurant manager instead of using a shared one that also manages three other restaurants down the street.

Example: Using Your Own ServeMux

Let's build a server that handles two different routes: / and /greet.

go
package main

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

func homeHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Welcome to the Home Page!")
}

func greetHandler(w http.ResponseWriter, r *http.Request) {
	// Let's also check the HTTP method.
	if r.Method != "GET" {
		// Respond with an error for non-GET requests.
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	fmt.Fprintf(w, "Greetings, traveler!")
}

func main() {
	// Create a new ServeMux.
	mux := http.NewServeMux()

	// Register handlers on our new mux.
	mux.HandleFunc("/", homeHandler)
	mux.HandleFunc("/greet", greetHandler)

	fmt.Println("Server is starting on port 8080...")
	// Pass our custom mux to ListenAndServe.
	err := http.ListenAndServe(":8080", mux)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

Now, if you run this and go to http://localhost:8080, you'll see "Welcome to the Home Page!". If you go to http://localhost:8080/greet, you'll see "Greetings, traveler!".

Under the Hood: How does the mux matching work? The mux finds the longest path that matches the request URL. So a request to /greet/you would still be handled by /greet in this example, as it's the longest matching pattern registered.


3. Reading Request Bodies and Query Parameters 📥

The Definition & The Problem

Often, a server needs to receive data from the client. This data can come in two common forms:

  • Query Parameters: Data passed in the URL itself, after a ?. Example: /search?query=golang.
  • Request Body: Data sent within the request itself, commonly used with POST, PUT, and PATCH requests to create or update resources. Example: sending JSON data to create a new user.

The problem is, how do we access this data from our handler? The client is talking to us, but we need to know how to listen.

The Solution: The *http.Request Object

The *http.Request (which we've been calling r) is a struct that holds all the information about the client's request. It's a treasure chest, and we're about to look inside.

A. Reading Query Parameters

The r.URL.Query() method parses the query parameters from the URL into a map-like structure. You can then use the .Get() method to retrieve a specific value.

Example: Reading a Query Parameter

go
// Add this handler to your previous example.
// Don't forget to register it in main: mux.HandleFunc("/user", userHandler)

func userHandler(w http.ResponseWriter, r *http.Request) {
    // Get the query parameters from the URL.
    queryParams := r.URL.Query()

    // Get the value of the "name" parameter.
    // If the parameter doesn't exist, it returns an empty string.
    name := queryParams.Get("name")

    if name == "" {
        name = "Guest"
    }

    fmt.Fprintf(w, "Hello, %s!", name)
}

Run your server and navigate to http://localhost:8080/user?name=Alice. You'll see "Hello, Alice!". If you go to http://localhost:8080/user, you'll see "Hello, Guest!".

B. Reading a JSON Request Body

This is extremely common for APIs. The standard practice is to define a Go struct that matches the structure of the expected JSON and then use the json.Decoder to read the request body directly into an instance of that struct.

Industry Practice: Don't read the body into a raw byte slice (io.ReadAll) unless you have a specific reason. Decoding directly into a struct is safer, more efficient, and gives you the benefits of Go's type system.

Example: Decoding a JSON Body

go
package main

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

// Task represents the structure of our expected JSON.
type Task struct {
	Name      string `json:"name"`
	Completed bool   `json:"completed"`
}

func tasksHandler(w http.ResponseWriter, r *http.Request) {
	// We only want to handle POST requests at this endpoint.
	if r.Method != http.MethodPost {
		http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
		return
	}

	var task Task
	// Create a new JSON decoder that reads from the request body.
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&task)
	if err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	// For now, we'll just print it to the console to prove it worked.
	log.Printf("Received task: %+v\n", task)

	// And send a nice response back.
	fmt.Fprintf(w, "Task '%s' received!", task.Name)
}


func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/tasks", tasksHandler)

	fmt.Println("Server is starting on port 8080...")
	err := http.ListenAndServe(":8080", mux)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

You can't test this one with a browser easily. You'll need a tool like curl or Postman.

Using curl in your terminal:

sh
curl -X POST -H "Content-Type: application/json" -d '{"name":"Learn Go Web Dev","completed":false}' http://localhost:8080/tasks

Your server's terminal will log Received task: {Name:Learn Go Web Dev Completed:false} and the curl command will print Task 'Learn Go Web Dev' received!.


4. Writing and Using Middleware 🕵️

The Definition & The Problem

Middleware is a piece of code that intercepts an incoming request before it reaches its intended handler, and can also process the response on its way out.

The problem: Imagine you have 50 different routes in your application, and for every single one, you need to:

  1. Log the request's method and URL.
  2. Check if the user is authenticated.
  3. Add a Content-Type: application/json header to the response.

Copying and pasting that logic into all 50 handlers would be a nightmare. If you needed to change the logging format, you'd have to edit 50 functions! This is not "DRY" (Don't Repeat Yourself).

The Solution: The Middleware Pattern

Middleware solves this by wrapping your handler in another function. It's like a chain of security checkpoints a request must pass through before it gets to its final destination (the handler).

A middleware in Go is simply a function that accepts an http.Handler and returns another http.Handler.

Analogy: Imagine your handlers are VIPs at an exclusive event. Middleware is the security team.

  • loggingMiddleware: The first guard at the door who writes down the name and arrival time of every guest (request).
  • authMiddleware: The second guard who checks the guest's ID (authentication token).
  • Only after passing all the guards does the guest get to meet the VIP (your tasksHandler).

Example: A Simple Logging Middleware

Let's create a middleware that logs the HTTP method and the path of every request that comes in.

go
// loggingMiddleware takes a handler and returns a new handler.
func loggingMiddleware(next http.Handler) http.Handler {
	// The returned handler is what the server will actually call.
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Our middleware logic goes here.
		log.Printf("Received %s request for %s", r.Method, r.URL.Path)

		// Call the next handler in the chain.
		// This passes control to the next middleware or the actual handler.
		next.ServeHTTP(w, r)
	})
}

Now, how do we use it? We wrap our handler with it in main.

go
func main() {
	mux := http.NewServeMux()

	// Our original handler.
	finalTasksHandler := http.HandlerFunc(tasksHandler)

	// Wrap our tasksHandler with the loggingMiddleware.
	mux.Handle("/tasks", loggingMiddleware(finalTasksHandler))

	fmt.Println("Server is starting on port 8080...")
    // ... rest of main function
}

Now, when you send a POST request to /tasks, your server's console will show the log message before it processes the task itself. You've successfully added a reusable piece of logic without modifying your original handler! You can wrap any number of handlers with this same middleware.

Fun Fact: This pattern of functions-wrapping-interfaces is very common in Go and is incredibly powerful. While many third-party libraries provide fancier ways to "chain" middleware, they all use this fundamental concept under the hood. Understanding it is key to becoming a proficient Go web developer.


Further Reading 📚

Challenge

Go Web Server Challenge: Task API

Your task is to build a simple in-memory Task API server using Go's net/http package. You will need to handle different HTTP methods, parse JSON data, and apply middleware for logging.

Requirements:

  1. Custom Router: Do not use the default ServeMux. Create a new one using http.NewServeMux().
  2. Task Handler (/tasks): Create a single handler function and register it for the /tasks path. This handler must support two HTTP methods:
    • GET: When a GET request is received, it should respond with a JSON array of all tasks from the in-memory store.
    • POST: When a POST request is received, it should decode the JSON body into a new Task struct, add it to the in-memory store, and respond with a 201 Created status code and the newly created task as a JSON object.
  3. Middleware: Implement a loggingMiddleware function. This function should:
    • Accept an http.Handler as input and return an http.Handler.
    • Log the HTTP method and the URL path of every incoming request (e.g., using log.Printf).
    • Pass the request to the next handler in the chain.
  4. Server Setup:
    • Wrap your task handler with the loggingMiddleware.
    • Register the wrapped handler with your custom ServeMux.
    • Start the HTTP server on address :8080.

Expected result

Your completed Go program should successfully implement a small web API for managing tasks. The solution must demonstrate the correct usage of a custom ServeMux, handling of different HTTP methods within a single handler, JSON decoding/encoding, and middleware application.

Here is a valid solution:

go
package main

import (
	"encoding/json"
	"log"
	"net/http"
	"sync"
)

// Task represents a single to-do item
type Task struct {
	ID        int    `json:"id"`
	Title     string `json:"title"`
	Completed bool   `json:"completed"`
}

var (
	// In-memory store for tasks
	tasks = []Task{
		{ID: 1, Title: "Learn Go", Completed: false},
		{ID: 2, Title: "Build a web server", Completed: false},
	}
	// Mutex to safely access the tasks slice from multiple goroutines
	mu       sync.Mutex
	nextID = 3
)

// loggingMiddleware logs the method and path of each request
func loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Printf("Request received: %s %s", r.Method, r.URL.Path)
		next.ServeHTTP(w, r)
	})
}

// tasksHandler handles requests to the /tasks endpoint
func tasksHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		mu.Lock()
		defer mu.Unlock()
		w.Header().Set("Content-Type", "application/json")
		if err := json.NewEncoder(w).Encode(tasks); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	case http.MethodPost:
		var newTask Task
		if err := json.NewDecoder(r.Body).Decode(&newTask); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		
		mu.Lock()
		defer mu.Unlock()
		newTask.ID = nextID
		nextID++
		tasks = append(tasks, newTask)
		
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusCreated)
		json.NewEncoder(w).Encode(newTask)
	default:
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
	}
}

func main() {
	mux := http.NewServeMux()

	finalTasksHandler := http.HandlerFunc(tasksHandler)
	mux.Handle("/tasks", loggingMiddleware(finalTasksHandler))

	log.Println("Server starting on port 8080...")
	if err := http.ListenAndServe(":8080", mux); err != nil {
		log.Fatalf("Could not start server: %s\n", err)
	}
}
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.