Course › Week 4 · Concurrency and plugging into Laravel › Day 3 · lesson 24 of 42 · 30 min reading + 60–75 min practice
context and the HTTP client
Cancel work and set deadlines with context, and call APIs with timeouts and status checks.
Laravel’s Http::get() wraps Guzzle and adds timeouts, retries and throw(). Go’s net/http client is in the standard library, fast and safe to share, and it does less for you: a 404 or a 500 is not an error, the response body must be closed, and the default has no timeout at all.
Today: a GET, the status check, timeouts with context (the value that carries a deadline through a chain of calls), a POST with JSON, and a retry that respects the deadline. Every program calls a small Laravel-style API running on http://127.0.0.1:8000, the address php artisan serve uses.
Calling an API
1. A GET, a body to close, and JSON
http.Get(url) returns a *http.Response and an error. resp.Body is a stream (the CSV lesson showed streams); decode it straight into a struct, and close it when done.
package main
import (
"encoding/json/v2"
"fmt"
"net/http"
"os"
)
type Booking struct {
ID int `json:"id"`
Guest string `json:"guest"`
Nights int `json:"nights"`
}
func main() {
resp, err := http.Get("http://127.0.0.1:8000/api/bookings/5521")
if err != nil {
fmt.Fprintln(os.Stderr, "calling the API:", err)
os.Exit(1)
}
defer resp.Body.Close()
var body struct {
Data Booking `json:"data"`
}
if err := json.UnmarshalRead(resp.Body, &body); err != nil {
fmt.Fprintln(os.Stderr, "decoding the booking:", err)
os.Exit(1)
}
fmt.Printf("%d %+v\n", resp.StatusCode, body.Data)
}
200 {ID:5521 Guest:Lina Nights:3}Laravel’s API resources wrap the model in data, so the body is decoded into a struct with one Data field. A struct type with no name, declared on the spot, is enough for that: var body struct { … }.
defer resp.Body.Close() is required. The client keeps the connection open for the next request only when the body is read and closed; forget it, and a long-running program runs out of connections.
2. A 404 is not an error
err is only for failures to get a response at all: no network, a refused connection, a timeout. A response with status 404 or 500 is a successful HTTP call, so check StatusCode yourself:
package main
import (
"encoding/json/v2"
"fmt"
"net/http"
)
type Booking struct {
ID int `json:"id"`
Guest string `json:"guest"`
}
func fetchBooking(id int) (Booking, error) {
resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:8000/api/bookings/%d", id))
if err != nil {
return Booking{}, fmt.Errorf("fetching booking %d: %w", id, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var problem struct {
Message string `json:"message"`
}
if err := json.UnmarshalRead(resp.Body, &problem); err != nil {
return Booking{}, fmt.Errorf("fetching booking %d: status %d", id, resp.StatusCode)
}
return Booking{}, fmt.Errorf("fetching booking %d: status %d: %s", id, resp.StatusCode, problem.Message)
}
var body struct {
Data Booking `json:"data"`
}
if err := json.UnmarshalRead(resp.Body, &body); err != nil {
return Booking{}, fmt.Errorf("decoding booking %d: %w", id, err)
}
return body.Data, nil
}
func main() {
for _, id := range []int{5521, 9999} {
booking, err := fetchBooking(id)
if err != nil {
fmt.Println("error:", err)
continue
}
fmt.Printf("%+v\n", booking)
}
}
{ID:5521 Guest:Lina}
error: fetching booking 9999: status 404: No query results for model [App\Models\Booking] 9999http.StatusOK is the constant 200; net/http names every status. Laravel’s 404 body has a message, so the error says what Laravel said. If the body is not JSON (a proxy’s HTML error page, say), the error keeps the status alone.
This is the step Laravel does for you with ->throw(). Without the check, the program would decode {"message": …} into an empty Booking and carry on with ID 0.
Timeouts and context
3. The default client never gives up
http.Get uses http.DefaultClient, which has no timeout: a server that never answers keeps your program waiting forever. Make your own client with a Timeout, once, and share it:
package main
import (
"fmt"
"net/http"
"os"
"time"
)
func main() {
client := &http.Client{Timeout: 1 * time.Second}
resp, err := client.Get("http://127.0.0.1:8000/api/slow")
if err != nil {
fmt.Fprintln(os.Stderr, "calling the API:", err)
os.Exit(1)
}
defer resp.Body.Close()
fmt.Println(resp.StatusCode)
}
calling the API: Get "http://127.0.0.1:8000/api/slow": context deadline exceeded (Client.Timeout exceeded while awaiting headers)
exit status 1/api/slow takes 3 seconds; the client gave up after 1. Timeout covers the whole call, including reading the body. One *http.Client is safe to use from many goroutines at once and keeps connections open between requests, so create it once in main and pass it down, like a database pool.
4. context.WithTimeout
A context.Context carries a deadline and a “stop” signal through every function of a job. context.WithTimeout(parent, d) makes one that ends after d, and a cancel function that ends it earlier. Attach it to a request with http.NewRequestWithContext.
By convention ctx is the first parameter of every function that does I/O or may take long, and it is passed down to everything that function calls.
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"time"
)
func fetchStatus(ctx context.Context, client *http.Client, url string) (int, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return 0, err
}
resp, err := client.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
return resp.StatusCode, nil
}
func main() {
client := &http.Client{Timeout: 10 * time.Second}
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
status, err := fetchStatus(ctx, client, "http://127.0.0.1:8000/api/slow")
if errors.Is(err, context.DeadlineExceeded) {
fmt.Fprintln(os.Stderr, "the API did not answer within 500ms:", err)
os.Exit(1)
}
if err != nil {
fmt.Fprintln(os.Stderr, "calling the API:", err)
os.Exit(1)
}
fmt.Println(status)
}
the API did not answer within 500ms: Get "http://127.0.0.1:8000/api/slow": context deadline exceeded
exit status 1context.Background() is the empty context every chain starts from, in main. defer cancel() is required even when the timeout ends it: it frees the timer as soon as the work is done. go vet reports a cancel that is never called.
The client’s own Timeout stays as a safety net for each call; the context sets the budget for the whole job, which may make many calls. errors.Is(err, context.DeadlineExceeded) tells a timeout apart from any other failure.
Sending JSON
5. A POST, and a 422
Encode the body with json.Marshal, wrap the bytes in a reader with bytes.NewReader, and set the Content-Type and Accept headers so Laravel answers with JSON. A failed validation comes back as 422 with an errors object of field names and messages.
package main
import (
"bytes"
"context"
"encoding/json/v2"
"fmt"
"net/http"
"os"
"time"
)
type ValidationError struct {
Message string `json:"message"`
Errors map[string][]string `json:"errors"`
}
func (e *ValidationError) Error() string {
return e.Message
}
func sendReminder(ctx context.Context, client *http.Client, bookingID int, channel string) error {
payload, err := json.Marshal(map[string]string{"channel": channel})
if err != nil {
return err
}
url := fmt.Sprintf("http://127.0.0.1:8000/api/bookings/%d/reminders", bookingID)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("sending the reminder: %w", err)
}
defer resp.Body.Close()
switch {
case resp.StatusCode == http.StatusUnprocessableEntity:
invalid := &ValidationError{}
if err := json.UnmarshalRead(resp.Body, invalid); err != nil {
return fmt.Errorf("decoding the 422: %w", err)
}
return invalid
case resp.StatusCode >= 300:
return fmt.Errorf("sending the reminder: status %d", resp.StatusCode)
}
return nil
}
func main() {
client := &http.Client{Timeout: 10 * time.Second}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
for _, channel := range []string{"email", "pigeon"} {
err := sendReminder(ctx, client, 5521, channel)
if invalid, ok := err.(*ValidationError); ok {
fmt.Println(channel, "rejected:", invalid.Errors)
continue
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println(channel, "reminder sent")
}
}
email reminder sent
pigeon rejected: map[channel:[The selected channel is invalid.]]The 422 becomes a *ValidationError (the error-wrapping lesson) that carries Laravel’s field errors. main reads it with a type assertion, which is enough because sendReminder returns it unwrapped; once a caller wraps it, use errors.As.
Any status of 300 or more is a failure the caller sees. A map[string]string is fine for a one-field body; a struct with tags is better as soon as there are two.
Retrying
6. Retry a 503, with backoff, inside the deadline
A 503 or a connection error is often over a second later; a 4xx never is. Retry only the first kind, wait longer each time, and stop when the context ends.
ctx.Done() is a channel that is closed when the context ends, so a select (the channels lesson) waits for either the backoff or the end of the context, whichever comes first.
package main
import (
"context"
"fmt"
"net/http"
"os"
"time"
)
// getWithRetry calls url and retries a 5xx up to attempts times, waiting 100 ms, 200 ms, 400 ms…
// between tries. It stops early when ctx ends.
func getWithRetry(ctx context.Context, client *http.Client, url string, attempts int) (*http.Response, error) {
wait := 100 * time.Millisecond
for attempt := 1; ; attempt++ {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err == nil && resp.StatusCode < 500 {
return resp, nil
}
if err == nil {
resp.Body.Close()
err = fmt.Errorf("status %d", resp.StatusCode)
}
if attempt == attempts {
return nil, fmt.Errorf("after %d attempts: %w", attempts, err)
}
fmt.Printf("attempt %d failed (%v), retrying in %v\n", attempt, err, wait)
select {
case <-time.After(wait):
wait *= 2
case <-ctx.Done():
return nil, fmt.Errorf("giving up while waiting to retry: %w", ctx.Err())
}
}
}
func main() {
client := &http.Client{Timeout: 5 * time.Second}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
resp, err := getWithRetry(ctx, client, "http://127.0.0.1:8000/api/unstable?key=lesson-24", 4)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer resp.Body.Close()
fmt.Println("status:", resp.StatusCode)
}
attempt 1 failed (status 503), retrying in 100ms
attempt 2 failed (status 503), retrying in 200ms
status: 200/api/unstable answers 503 twice, then 200. A response that will be retried has its body closed before the next try. ctx.Err() says why the context ended: context.DeadlineExceeded or context.Canceled.
It is Laravel’s Http::retry(4, 100), written out. Only retry calls that are safe to repeat: a GET always, a POST only when the API makes it idempotent (an idempotency key, or an upsert on the other side).
Coming from PHP
<?php
$booking = Http::baseUrl('http://127.0.0.1:8000/api')
->acceptJson()
->timeout(1)
->retry(4, 100, fn ($e) => $e instanceof ConnectionException || $e->response?->serverError())
->get('/bookings/5521')
->throw()
->json('data');
Each Laravel method has a Go line: timeout is the client’s Timeout or a context deadline, retry is the loop in section 6, throw() is the status check, json('data') is the struct with a Data field. Go makes you write them, and in return nothing happens that you did not write.
The one thing PHP has no equivalent for is the context: one deadline for a whole job, passed through every call, that stops the waits in all of them at once. A Go worker gets a deadline from Laravel, gives it to every HTTP and database call, and stops cleanly when it runs out.
PracticeThe net/http documentation; Learn Go with Tests: Select
Do Select in Learn Go with Tests: it races two HTTP servers with select and tests it with httptest, a preview of Week 5. Then read the package overview at the top of go doc net/http.
Exercise: follow the pages
GET /api/bookings?page=N returns {"data": […], "current_page": N, "last_page": M}. Write allBookings(ctx, client) ([]Booking, error) that requests page 1, then every page up to last_page, and returns all bookings. Give the whole loop one 3-second context, check every status, and close every body.
Remember
- Close every response body, and check
StatusCodeyourself: a 404 or a 503 is not anerr. - Never use the default client without a timeout; give each job one
context.WithTimeoutand passctxto every call. - Retry only timeouts, connection errors, 429 and 5xx, with backoff, inside the deadline.
Tomorrow: Postgres with database/sql and pgx, on the tables your Laravel migrations created.