HTTP Handlers
Start with HTTP Handlers
In this lesson, explore http handlers through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of http handlers.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
An http.Handler has a ServeHTTP(ResponseWriter, *Request) method. http.HandlerFunc adapts ordinary functions to that interface.
Handlers can be composed, tested and supplied to middleware. Avoid storing per-request data in unsynchronized global variables.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
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"
)
type Greeting struct{ Text string }
func (g Greeting) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, g.Text) }
func main() {
rec := httptest.NewRecorder()
Greeting{"Hello"}.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
fmt.Println(rec.Body.String())
}
Output
HelloTrace what the program does
The Greeting type implements ServeHTTP, so it is an HTTP handler. The recorder captures Hello.
Avoid common mistakes
- A handler method can have a pointer receiver if it needs controlled mutable state.
- Write an HTTP response once; do not try to change its status after the body starts.
Try it yourself
Create a handler type that returns a configurable service name.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced HTTP Handlers 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.