ProgramGuru

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.

Visual explanation for responsesResponse metadata comes before body bytes.Set headersStep 1Write statusStep 2Encode bodyStep 3Client readsStep 4Response metadata comes before body bytes.
Response metadata comes before body bytes.

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 HTTP status is implied if a handler writes a body first?
Choose one answer. You can try again.

Answer and explanation

200 OK

Correct. The response carries status 202 and the application/json content type.

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.

    Next lesson: JSON APIs in Go →