By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Every web page, mobile app and API works by the same small conversation. A client sends a request: a method such as GET or POST, a path such as /expenses, some headers, and sometimes a body. A server answers with a response: a status code such as 200, some headers, and a body.
The body might be a web page, a file or JSON. For Penny it is JSON, because your expense data is already a slice of structs that encoding/json knows how to write. Go ships the whole server in the standard library package net/http; no framework is needed for this project.
A Go server has three pieces. A router called http.ServeMux looks at the path of each request and chooses a handler function. The handler writes the response. That is the whole design of Penny's API.
Every handler has the same signature: func name(w http.ResponseWriter, r *http.Request). The w parameter is how you write the response, and r holds everything about the request, including its method, path and body. You register a handler on a path with mux.HandleFunc("/path", handler).
This complete program serves two endpoints. GET /health proves the server is awake, and GET /expenses returns Penny's list as JSON:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
// Expense is one row in Penny's list. Money is stored in integer cents.
type Expense struct {
ID int `json:"id"`
Description string `json:"description"`
Cents int `json:"cents"`
Category string `json:"category"`
}
var expenses = []Expense{
{ID: 1, Description: "coffee", Cents: 450, Category: "food"},
{ID: 2, Description: "bus ticket", Cents: 275, Category: "travel"},
}
// writeJSON sets the headers, writes the status code, then encodes the body.
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(value)
}
func expensesHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("Allow", "GET")
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
writeJSON(w, http.StatusOK, expenses)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
})
mux.HandleFunc("/expenses", expensesHandler)
fmt.Println("Penny API listening on http://localhost:8080")
if err := http.ListenAndServe(":8080", mux); err != nil {
fmt.Println("server error:", err)
}
}http.ListenAndServe blocks: it keeps the program alive and handles requests until the process is stopped. That is why a server example has no expected output pane. Its output depends on the requests you make.
Writing a JSON response has a fixed order: header, status, body. w.Header().Set must run before w.WriteHeader, because the status line and headers are sent first and cannot be changed afterwards. Then json.NewEncoder(w).Encode(value) writes the body.
The encoder is the same tool you used for files in step 34. This small program shows what it writes to a terminal. The response body from the server looks the same:
package main
import (
"encoding/json"
"os"
)
type Expense struct {
ID int `json:"id"`
Description string `json:"description"`
Cents int `json:"cents"`
Category string `json:"category"`
}
func main() {
expense := Expense{ID: 1, Description: "coffee", Cents: 450, Category: "food"}
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
encoder.Encode(expense)
}The status code is the server's first word to the client. Use the narrowest code that is true:
| Status | Name | Use it when |
|---|---|---|
200 | OK | the request succeeded and there is a body |
201 | Created | a POST created a new resource |
400 | Bad Request | the client sent invalid JSON or missing fields |
404 | Not Found | the path or the requested ID does not exist |
405 | Method Not Allowed | the path exists but not for that method |
500 | Internal Server Error | your side failed, such as a disk write error |
curl is a command-line HTTP client. It sends a request and prints the response body, so it is the fastest way to check an API without a browser. The workflow is always the same:
go run ..curl command and read the body or the status code.# The server must already be running in another terminal.
# GET /health returns a tiny status object.
curl -s http://localhost:8080/health
{"status":"ok"}
# GET /expenses returns the list as a JSON array.
curl -s http://localhost:8080/expenses
[{"id":1,"description":"coffee","cents":450,"category":"food"},{"id":2,"description":"bus ticket","cents":275,"category":"travel"}]
# Print only the status code and throw the body away.
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/expenses
200-H adds a header and -d sends a body.You do not need to start a server to test a handler. The net/http/httptest package can build a request and record the response, and then you call the handler function directly. The test is fast, uses no port, and runs with the same go test ./... from section 8:
// ==== file: main.go ====
package main
import (
"encoding/json"
"net/http"
)
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}
func main() {
http.HandleFunc("/health", healthHandler)
http.ListenAndServe(":8080", nil)
}
// ==== file: main_test.go ====
package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestHealthHandler(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "/health", nil)
recorder := httptest.NewRecorder()
healthHandler(recorder, request)
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d; want %d", recorder.Code, http.StatusOK)
}
got := strings.TrimSpace(recorder.Body.String())
want := `{"status":"ok"}`
if got != want {
t.Errorf("body = %s; want %s", got, want)
}
if contentType := recorder.Header().Get("Content-Type"); contentType != "application/json" {
t.Errorf("Content-Type = %q; want application/json", contentType)
}
}Add a third endpoint, GET /hello, that returns {"message":"hello from Penny"} with status 200. Register it on the mux and check it with curl -s http://localhost:8080/hello. Then write a TestHelloHandler with httptest that checks both the status and the body. Run go test ./... and confirm it passes.
Key takeaways
HTTP is a request (method, path, headers, body) and a response (status, headers, body).
http.ServeMux routes paths to handlers with the signature func(w http.ResponseWriter, r *http.Request).
Write a JSON response in order: set headers, write the status code, then json.NewEncoder(w).Encode.
Status codes carry meaning: 200 success, 201 created, 400 bad input, 404 missing, 405 wrong method, 500 server failure.
curl checks a running API, and httptest tests a handler without a server.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.