Understand the contract
The final project builds a read-only greeting endpoint and tests it without opening a network port. It combines explicit inputs, structured output, validation and HTTP metadata. Keep the scope small enough that you can explain every branch before adding storage, workers or a framework.
Save the first code block as main.go in a new module. hello reads a query parameter, trims whitespace and rejects an empty name. It marshals the response before writing headers so serialization errors can still produce a coherent error response. The handler contains no shared mutable state.
Work through the example
Save the second block as main_test.go and run go test ./.... The test invokes hello directly using httptest.NewRequest and NewRecorder. It checks both valid and invalid input, including JSON content type and decoded response content. Use go run . only after the tests pass, then visit /hello?name=Ada on the local listener.
package main
import (
"encoding/json"
"log"
"net/http"
"strings"
"time"
)
type Greeting struct { Message string `json:"message"` }
func hello(w http.ResponseWriter, r *http.Request) {
name := strings.TrimSpace(r.URL.Query().Get("name"))
if name == "" || len(name) > 100 {
http.Error(w, "name must contain 1-100 bytes", http.StatusBadRequest)
return
}
body, err := json.Marshal(Greeting{Message: "Hello, " + name})
if err != nil {
http.Error(w, "encoding failed", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(body)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /hello", hello)
server := &http.Server{
Addr: "127.0.0.1:8080", Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
}
log.Fatal(server.ListenAndServe())
}Test the handler without a listener
Save this block as main_test.go beside main.go. Run go test ./... in that module.
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestHello(t *testing.T) {
cases := []struct { name, target string; status int; message string }{
{"valid", "/hello?name=Ada", http.StatusOK, "Hello, Ada"},
{"missing", "/hello", http.StatusBadRequest, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
response := httptest.NewRecorder()
hello(response, httptest.NewRequest(http.MethodGet, tc.target, nil))
if response.Code != tc.status {
t.Fatalf("status = %d; want %d", response.Code, tc.status)
}
if tc.status == http.StatusOK {
if got := response.Header().Get("Content-Type"); got != "application/json" {
t.Fatalf("Content-Type = %q; want application/json", got)
}
var body Greeting
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { t.Fatal(err) }
if body.Message != tc.message {
t.Fatalf("message = %q; want %q", body.Message, tc.message)
}
}
})
}
}Watch this boundary
The name-length bound is measured in bytes and is an explicit teaching policy. This example has no persistence, authentication or background processing. Add those only with defined requirements and tests. If you later share a map between handlers, apply the ownership and mutex rules from the concurrency lessons.
Practice with a changed input
Add a test for whitespace-only input and a name exceeding the byte limit. Then add an independent HTTP-level test of the ServeMux method rule, since directly calling hello bypasses router method selection.
Lesson 50 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services