Sending HTTP Responses
Start with Sending HTTP Responses
In this lesson, explore sending http responses through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of sending http responses.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Set response headers before calling WriteHeader or writing the first body byte. If you do not explicitly send a status, Go defaults to 200 when the handler first writes the body.
Return clear content types and status codes. JSON responses should be encoded with json.Encoder so strings are escaped properly.
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 (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
)
func main() {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
json.NewEncoder(w).Encode(map[string]string{"status": "queued"})
})
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
fmt.Println(rec.Code, rec.Header().Get("Content-Type"))
fmt.Print(rec.Body.String())
}
Output
202 application/json
{"status":"queued"}Trace what the program does
The response carries status 202 and the application/json content type. The JSON encoder serializes a one-key map with a stable value.
Avoid common mistakes
- Status must be written before the response body.
- Encoding a JSON response can fail; handle errors where appropriate.
Try it yourself
Change the response to 201 with a Task object containing an ID and title.
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 Sending HTTP Responses 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.