ProgramGuru

Routing HTTP Requests

Start with Routing HTTP Requests

In this lesson, explore routing http requests through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of routing http requests.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

http.ServeMux matches URL paths, HTTP methods and named path parameters. Go 1.22 introduced patterns such as GET /tasks/{id} and access through r.PathValue("id").

Routes should reflect distinct resources and methods. Registering overlapping or invalid patterns can panic at startup, so validate your route table.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for routingMethod and path patterns are parsed by ServeMux.GET /tasks/42Step 1Match /tasks/{id}Step 2PathValue = 42Step 3Handler responseStep 4Method and path patterns are parsed by ServeMux.
Method and path patterns are parsed by ServeMux.

Tools, syntax and practical notes

Requires Go 1.22+ routing semantics. See ServeMux patterns.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

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

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /tasks/{id}", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Task ", r.PathValue("id")) })
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, httptest.NewRequest("GET", "/tasks/42", nil))
	fmt.Println(rec.Body.String())
}

Output

Task 42

Trace what the program does

ServeMux matches the GET pattern and sets the named path value id=42. The handler writes Task 42.

Avoid common mistakes

  • Method patterns and PathValue require Go 1.22 or later.
  • Validate extracted IDs instead of assuming every URL segment is a valid database identifier.

Try it yourself

Add a GET /users/{name} route and print its path value.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

How do you read a named path wildcard in modern ServeMux?
Choose one answer. You can try again.

Answer and explanation

r.PathValue("id")

Correct. ServeMux matches the GET pattern and sets the named path value id=42.

What you should remember

You have practiced Routing HTTP Requests in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Working with Query Parameters →