ProgramGuru

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.

Visual explanation for handlersHandlers are interfaces, not just functions.Handler interfaceStep 1ServeHTTPStep 2Write status/bodyStep 3Recorder checksStep 4Handlers are interfaces, not just functions.
Handlers are interfaces, not just functions.

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

Hello

Trace 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

Which method satisfies the http.Handler interface?
Choose one answer. You can try again.

Answer and explanation

ServeHTTP(http.ResponseWriter, *http.Request)

Correct. The Greeting type implements ServeHTTP, so it is an HTTP handler.

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.

    Next lesson: Routing HTTP Requests →