跳至正文

HTTP Client ​

Introduction ​

Most applications call other services' APIs. For example, you may fetch a user's GitHub profile, charge a card through a payment provider, or post to a customer's webhook. Laravel's HTTP client gives every request a timeout, retries a request when you ask it to, and turns failures into errors you can return with web.Fail. In your tests, you may fake every response, so your test suite never touches the network.

The client lives in the httpclient package and is built on net/http.

Making requests ​

To make a request, call Get, Post, Put, Patch, Delete, or Head with a context and the URL. For example, this handler fetches a GitHub profile:

go
package profiles

import (
	"go.laravel.com/httpclient"
	"go.laravel.com/web"
)

func Show(r *web.Request) *web.Response {
	res, err := httpclient.Get(r, "https://api.github.com/users/taylorotwell")
	if err != nil {
		return web.Fail(err)
	}

	return web.Text(res.Text())
}

Sending a request reads the whole response body. You get the response back whatever its status, so a 404 or a 500 isn't an error. The error is non-nil only when the request couldn't be sent or never got a response. To treat a failed status as an error, check out the section on error handling. For any other HTTP method, use Send(ctx, method, url).

You may send requests from handlers, console commands, queued jobs, and listeners. The context carries your application's client, so your settings and your tests' fakes apply to every request. A handler passes r, and a job, listener, or command passes the ctx it received. When you run work in goroutines of your own, use task.Run and send each request with the ctx it gives you.

Responses ​

A *httpclient.Response holds the response's Status, Header, Body, and final URL as fields. It also has these methods for inspecting the response:

MethodReturns
Successful()Whether the status is 2xx
Redirect()Whether the status is 3xx
Failed()Whether the status is 4xx or 5xx
ClientError(), ServerError()Whether the status is 4xx, or 5xx
Text()The body as a string
JSON[T]()The decoded value, or an error when the body isn't JSON that fits T
EnsureSuccessful()A *StatusError when the status isn't 2xx

To read a JSON body, decode it into a struct of your own. Give the struct's fields json tags, because Laravel decodes JSON with encoding/json/v2, which matches names exactly. When you only need a field or two, you may decode into a map[string]any instead:

go
type GitHubUser struct {
	Login string `json:"login"`
	Name  string `json:"name"`
}

user, err := res.JSON[GitHubUser]()
if err != nil {
	return web.Fail(err)
}

raw, err := res.JSON[map[string]any]()
if err != nil {
	return web.Fail(err)
}

name := raw["name"]

When you expect a 2xx JSON response and don't need to inspect headers or status codes yourself, call GetJSON, PostJSON, PutJSON, PatchJSON, or DeleteJSON. Each method fails with a *StatusError on a non-2xx status and decodes the body into the target type:

go
user, err := httpclient.Token(token).
	GetJSON[GitHubUser](r, "https://api.github.com/user")

Request data ​

Most APIs take JSON. To send a JSON body, use JSON, which takes any value that encoding/json/v2 can encode:

go
res, err := httpclient.JSON(map[string]string{"name": "Steve", "role": "Network Administrator"}).
	Post(r, "https://example.com/users")

To add query parameters, chain QueryParam for individual parameters, or pass Query a url.Values. Each call adds its parameters after any parameters already in the URL:

go
res, err := httpclient.QueryParam("name", "Taylor").
	QueryParam("page", "2").
	Get(r, "https://example.com/users")

To send a form instead of JSON, use Form. For a raw body of any content type, use Body. To send a file from disk without reading the whole file into memory, use BodyFile, which resolves a relative path against your application's base path:

go
res, err := httpclient.Form(url.Values{"name": {"Sara"}, "role": {"Privacy Consultant"}}).
	Post(r, "https://example.com/users")

res, err = httpclient.Body([]byte("Remember the milk."), "text/plain").
	Put(r, "https://example.com/notes/1")

res, err = httpclient.BodyFile("storage/app/backup.zip", "application/zip").
	Put(r, "https://example.com/backups/latest")

Attaching files ​

Some APIs take files, such as a report to store or an image to process. To upload files as a multipart form, give Attach the form field's name and an httpclient.Attachment. The client sends any Form fields alongside the files:

go
res, err := httpclient.Attach("report", httpclient.AttachFile("storage/app/reports/q3.pdf")).
	Form(url.Values{"quarter": {"Q3"}}).
	Post(r, "https://example.com/reports")

httpclient.AttachFile streams a file from disk, and resolves a relative path against your application's base path. httpclient.AttachData(data, "avatar.png") sends bytes you already have in memory under the file name you give. The client guesses each file's content type from its name. To send a different name or content type, use As and WithMime:

go
httpclient.AttachFile("storage/app/exports/1234.tmp").As("export.csv").WithMime("text/csv")

To forward a file that a user uploaded, attach the upload's Attachment(). The attachment keeps the file name the user gave and the content type that the file's bytes show. For example, this handler passes an uploaded photo on to a storage service:

go
type PhotoForm struct {
	Photo *web.Upload `json:"photo"`
}

func Store(r *web.Request) *web.Response {
	form, err := r.Validate[PhotoForm]()
	if err != nil {
		return web.Fail(err)
	}

	_, err := httpclient.EnsureSuccessful().
		Attach("photo", form.Photo.Attachment()).
		Post(r, "https://storage.example.com/photos")
	if err != nil {
		return web.Fail(err)
	}

	return web.Back()
}

Forward uploaded files inside the handler itself rather than in a queued job or r.Background, because Laravel deletes uploads once the response has been sent.

Headers ​

Many APIs ask for headers of their own, such as a tenant or an idempotency key. To add a header, use Header. To add several at once, use Headers. Each header replaces any earlier header with the same name:

go
res, err := httpclient.Headers(map[string]string{"X-Tenant": "acme", "X-Locale": "en"}).
	Header("Idempotency-Key", "user-1234").
	JSON(map[string]string{"name": "Taylor"}).
	Post(r, "https://example.com/users")

To say what content type you expect back, use Accept, or AcceptJSON for JSON:

go
res, err := httpclient.AcceptJSON().Get(r, "https://example.com/users")

res, err = httpclient.Accept("text/csv").Get(r, "https://example.com/reports/monthly")

Authentication ​

Most APIs ask for a key or a token with each request. To send a bearer token in the Authorization header (Authorization: Bearer <token>), use Token:

go
res, err := httpclient.Token("your-token").Get(r, "https://api.github.com/user")

If an API uses HTTP basic authentication instead, pass the username and password to BasicAuth:

go
res, err := httpclient.BasicAuth("taylor@laravel.com", "secret").Get(r, "https://example.com/user")

For an API that expects a key in a header of its own, send the header with Header:

go
res, err := httpclient.Header("X-Api-Key", "your-api-key").Get(r, "https://api.example.com/events")

In production applications, keep keys and tokens out of your source code. Read each one from a setting of your own in services.New, and store it on your application's services:

go
// services/services.go
type Services struct {
	GitHubToken string
}

func New(env *config.Env, app *laravel.App) Services {
	return Services{GitHubToken: env.String("GITHUB_TOKEN", "")}
}

A handler then reads the token with services.From(r):

go
package profiles

import (
	"go.laravel.com/httpclient"
	"go.laravel.com/web"

	"app/services"
)

func Show(r *web.Request) *web.Response {
	res, err := httpclient.Token(services.From(r).GitHubToken).Get(r, "https://api.github.com/user")
	if err != nil {
		return web.Fail(err)
	}

	return web.Text(res.Text())
}

Base URLs and reusable clients ​

When you call the same API from several places, configure the client once. Each option returns a new client and leaves the client you called it on unchanged, so a configured client is a template that every request to the API starts from. A client is safe to share between goroutines, so you may build it once in your services with its base URL, token, and error handling:

go
// services/services.go
type Services struct {
	GitHub *httpclient.Client
}

func New(env *config.Env, app *laravel.App) Services {
	return Services{
		GitHub: httpclient.BaseURL("https://api.github.com").
			Token(env.String("GITHUB_TOKEN", "")).
			AcceptJSON().
			EnsureSuccessful(),
	}
}

Start the template from a function of the httpclient package, as BaseURL is here, rather than from httpclient.New. The template's requests then go through your application's client in the context you send them with, so your tests can still fake them.

In a handler, send requests from the template with relative URLs, which the client resolves against the base URL:

go
func Dashboard(r *web.Request) *web.Response {
	github := services.From(r).GitHub

	user, err := github.Get(r, "/user")
	if err != nil {
		return web.Fail(err)
	}

	repos, err := github.Query(url.Values{"per_page": {"100"}}).Get(r, "/user/repos")
	if err != nil {
		return web.Fail(err)
	}

	// ...
}

URL parameters ​

Don't build a URL from user input with fmt.Sprintf, because a value such as ../admin changes the path you request. Instead, write {name} placeholders in the URL, and give URLParameters each placeholder's name followed by its value. The client encodes each value as a single path segment:

go
res, err := httpclient.URLParameters("owner", "laravel", "repo", "framework").
	Get(r, "https://api.github.com/repos/{owner}/{repo}")

To insert a value without encoding it, such as a whole base URL, write {+name}. For example, {+api}/users with "api", "https://api.example.com/v2" requests https://api.example.com/v2/users.

Timeouts ​

A slow service shouldn't keep your users waiting forever. By default, a request waits up to 30 seconds for its whole response, and up to 10 seconds to connect. To change the limit for one request, use Timeout:

go
res, err := httpclient.Timeout(3*time.Second).Get(r, "https://example.com")

A request that times out returns a *httpclient.ConnectionError, whose Timeout() method returns true. To change how long the request waits to connect, use ConnectTimeout. The request also stops when its context ends, such as when the visitor leaves the page. To change the defaults for every request, configure the client.

Retries ​

Services sometimes fail for a moment, such as during a deploy or under heavy load, and the same request succeeds a second later. To try a request again when it can't connect, or when it gets a status outside 2xx, use Retry. Give Retry the number of attempts to make and how long to wait between them. If you give several waits, the client uses each in turn and then repeats the last one:

go
res, err := httpclient.JSON(map[string]string{"event": "order.shipped"}).
	Retry(3, 100*time.Millisecond).
	Post(r, "https://example.com/webhooks")

res, err = httpclient.Retry(
	5,
	100*time.Millisecond,
	200*time.Millisecond,
	400*time.Millisecond,
	800*time.Millisecond,
).Get(r, "https://example.com")

When every attempt fails, the request returns the last attempt's error.

A rate-limited or overloaded service often says when to come back. When a 429 or 503 response has a Retry-After header, in seconds or as a date, the client waits at least that long before the next attempt, as long as the wait fits within the request's timeout or TotalTimeout. Otherwise, the client stops retrying and returns the response's error, so you may handle it or try again later.

Each attempt gets its own timeout, so several retries can keep a page waiting far longer than you'd like. To limit the attempts and the waits between them together, use TotalTimeout:

go
res, err := httpclient.Timeout(2*time.Second).
	Retry(5, 200*time.Millisecond, 400*time.Millisecond, 800*time.Millisecond).
	TotalTimeout(5*time.Second).
	Get(r, "https://api.github.com/users/taylorotwell")

With a TotalTimeout of 5 seconds, the client honors a Retry-After of 3 seconds when 3 seconds are left, even though each attempt may take only 2. A Retry-After of 24 hours returns the error at once.

To retry only some failures, use RetryWhen. Its function receives the failed attempt's error and the attempt's number, counting from 1. For example, this request retries only when it can't connect:

go
res, err := httpclient.Retry(3, 100*time.Millisecond).
	RetryWhen(func(err error, attempt int) bool {
		_, unreachable := errors.AsType[*httpclient.ConnectionError](err)

		return unreachable
	}).
	Get(r, "https://example.com")

警告

A retry sends the same request again. Retry only requests that are safe to repeat, such as a read or a payment with an idempotency key.

Error handling ​

A 4xx or 5xx response isn't an error by itself. Usually, though, your code can't go on without a successful response. To treat a failed status as an error, call EnsureSuccessful on the client. Sending then returns a *httpclient.StatusError for any status outside 2xx:

go
res, err := httpclient.EnsureSuccessful().Get(r, "https://api.github.com/users/taylorotwell")

You may also call res.EnsureSuccessful() on a response you've already inspected. The client returns these errors:

ErrorWhen
*httpclient.ConnectionErrorNo response arrived, because the host couldn't be reached, TLS failed, or the request timed out
*httpclient.StatusErrorThe status was outside 2xx, with EnsureSuccessful or Retry. Its Response field holds the response
*httpclient.DecodeErrorJSON couldn't decode the body into the value you gave it
Any other errorThe request couldn't be sent, such as for an invalid URL or header

To handle particular failures, such as a timeout or a missing user, match the error with errors.As:

go
res, err := httpclient.EnsureSuccessful().Get(r, "https://api.github.com/users/taylorotwell")

var failed *httpclient.ConnectionError
var status *httpclient.StatusError
switch {
case errors.As(err, &failed) && failed.Timeout():
	// ...
case errors.As(err, &status) && status.Response.Status == http.StatusNotFound:
	// ...
case err != nil:
	return web.Fail(err)
}

When a handler returns web.Fail(err), Laravel reports the error and responds with a 500. The report names the URL and shows the start of the response's body:

text
httpclient: the request to https://api.example.com/users returned 404 Not Found: {"message":"Not found"}

Concurrent requests ​

Sometimes you need several responses that don't depend on each other, such as a repository and its latest release. Sending the requests one after another makes your user wait for each in turn. Instead, pass a function for each request to task.Run, which runs the functions at once and returns when they've all returned. Each function sends its request with the ctx it receives:

go
package releases

import (
	"context"

	"go.laravel.com/httpclient"
	"go.laravel.com/task"
	"go.laravel.com/web"
)

func Show(r *web.Request) *web.Response {
	var repo, release *httpclient.Response
	err := task.Run(r,
		func(ctx context.Context) (err error) {
			repo, err = httpclient.EnsureSuccessful().
				Get(ctx, "https://api.github.com/repos/laravel/framework")
			return err
		},
		func(ctx context.Context) (err error) {
			release, err = httpclient.EnsureSuccessful().
				Get(ctx, "https://api.github.com/repos/laravel/framework/releases/latest")
			return err
		},
	)
	if err != nil {
		return web.Fail(err)
	}

	// ...
}

When one request fails, task.Run ends the other function's context, so a request that's still waiting stops early, and task.Run returns the failed request's error.

When you send many requests, you may want to limit how many run at once, so you don't flood the API. task.Map calls a function for each item, with at most the number you give it running at the same time, and returns the results in the order of the items:

go
orgs := []string{"laravel", "golang", "kubernetes"}
responses, err := task.Map(
	r,
	orgs,
	5,
	func(ctx context.Context, org string) (*httpclient.Response, error) {
		return httpclient.URLParameters("org", org).Get(ctx, "https://api.github.com/orgs/{org}")
	},
)
if err != nil {
	return web.Fail(err)
}

Streaming responses ​

Sending a request reads the whole body into memory. For a large download, or an API that answers in pieces, such as an AI model that streams its reply, use Stream instead. Stream takes the HTTP method as well as the URL, and returns the standard *http.Response as soon as the headers arrive, so you read the body as it comes in. Close the body once you're done.

For example, this handler writes a large export to your local disk without holding the whole export in memory:

go
res, err := httpclient.EnsureSuccessful().
	Stream(r, http.MethodGet, "https://example.com/exports/orders.csv")
if err != nil {
	return web.Fail(err)
}
defer res.Body.Close()

if err := storage.Use("local").WriteStream(r, "exports/orders.csv", res.Body); err != nil {
	return web.Fail(err)
}

When you stream, the timeout limits each wait for more of the body rather than the whole body, so a long stream that keeps sending never times out. If a stream stops sending, its next read fails with a *httpclient.ConnectionError.

Server-sent events ​

Many AI and realtime APIs stream their replies as server-sent events, so a chat page can show each word as the model writes it. httpclient.Events reads the events from a body and gives you each event once it's complete. Each event holds its Data, and its JSON method decodes the data.

For example, this handler asks OpenAI for a haiku and passes each piece of the reply on to the browser as an event stream of its own. The handler returns before the events are sent, so the function it gives web.StreamEvents closes OpenAI's body once the reply is done:

go
package chat

import (
	"net/http"

	"go.laravel.com/httpclient"
	"go.laravel.com/web"

	"app/services"
)

type completionChunk struct {
	Choices []struct {
		Delta struct {
			Content string `json:"content"`
		} `json:"delta"`
	} `json:"choices"`
}

func Show(r *web.Request) *web.Response {
	res, err := httpclient.Token(services.From(r).OpenAIKey).
		JSON(map[string]any{
			"model":    "gpt-6.2-sol",
			"stream":   true,
			"messages": []map[string]string{{"role": "user", "content": "Write a haiku about Go."}},
		}).
		EnsureSuccessful().
		Stream(r, http.MethodPost, "https://api.openai.com/v1/chat/completions")
	if err != nil {
		return web.Fail(err)
	}

	return web.StreamEvents(func(send func(web.Event) error) error {
		defer res.Body.Close()

		for event, err := range httpclient.Events(res.Body) {
			if err != nil {
				return err
			}
			if event.Data == "[DONE]" {
				return nil
			}

			chunk, err := event.JSON[completionChunk]()
			if err != nil || len(chunk.Choices) == 0 {
				continue
			}

			if err := send(web.Event{Data: chunk.Choices[0].Delta.Content}); err != nil {
				return err
			}
		}

		return nil
	})
}

Configuring the client ​

Every request your application sends, whether it starts from httpclient.Get or from a template in your services, goes through your application's client. Sharing one client lets requests across your application reuse their connections, default timeouts, and hooks. The client starts from these defaults, which are fine for most applications:

SettingDefault
Timeout30 seconds
Connect timeout10 seconds
RedirectsUp to 10
User-AgentLaravel-Go/ and the framework's version

To change these settings for every request, set HTTP in the laravel.Options in bootstrap/app.go. Your function receives Laravel's client and returns the client your application uses:

go
HTTP: func(client *httpclient.Client) *httpclient.Client {
	return client.
		Timeout(10 * time.Second).
		ConnectTimeout(5 * time.Second).
		UserAgent("Acme/1.0").
		BeforeSending(func(req *http.Request) error {
			req.Header.Set("X-Tenant", "acme")

			return nil
		}).
		AfterResponse(func(res *httpclient.Response) {
			slog.Debug("API response", "status", res.Status)
		})
},

Build the client you return from the client you receive, not from httpclient.New, so your tests can still fake its requests.

Hooks let you inspect or change every request and response that passes through a client. BeforeSending hooks run in the order you added them, before each attempt is sent, and a hook that returns an error fails the request. AfterResponse hooks see every response that comes back, including the response to each retried attempt and faked responses in tests. If a hook signs the body, read the body with req.GetBody, so the request still has its body to send.

If a BeforeSending hook should only apply to one API, such as a hook that adds credentials, check the request's URL before you change the request:

go
client.BeforeSending(func(req *http.Request) error {
	if req.URL.Host == "api.example.com" {
		req.Header.Set("Authorization", "Bearer secret")
	}

	return nil
})

Transport options ​

When an API needs connection options, such as a proxy, a private certificate authority, or a client certificate, give Transport an *http.Transport of your own with those options. Transport also takes any http.RoundTripper that wraps another, such as one that records metrics. To change how the client follows redirects, give CheckRedirect a policy, which works as the CheckRedirect field of http.Client does. To follow no redirects, return http.ErrUseLastResponse:

go
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.TLSClientConfig = &tls.Config{RootCAs: pool}

api := httpclient.Transport(transport).CheckRedirect(func(*http.Request, []*http.Request) error {
	return http.ErrUseLastResponse
})

A client with a transport of its own keeps its own connections, apart from the rest of your application's requests.

Dedicated clients ​

Sometimes a single integration needs its own User-Agent, a longer timeout, private certificates, or a redirect policy that you don't want on every request. In those cases, build a dedicated client from a function of the httpclient package, and send that integration's requests from it.

Because a client with its own transport keeps its own connections, don't build one inside each handler. Instead, build it once in your services, and read it wherever you need it:

go
// services/services.go
type Services struct {
	Reports *httpclient.Client
}

func New(env *config.Env, app *laravel.App) Services {
	return Services{
		Reports: httpclient.BaseURL("https://reports.example.com").
			Timeout(60 * time.Second).
			UserAgent("Acme Reports/1.0").
			EnsureSuccessful(),
	}
}
go
func Monthly(r *web.Request) *web.Response {
	res, err := services.From(r).Reports.Get(r, "/monthly")
	if err != nil {
		return web.Fail(err)
	}

	return web.Text(res.Text())
}

Even when requests go through a dedicated client, your tests still fake them.

Logging ​

Each request logs a debug line that shows its method, URL, status, and duration_ms, or the error it failed with. To see these lines, set LOG_LEVEL=debug. URLs in logs and error messages leave out credentials and the query string, where API keys often appear.

When you export traces, each request and its retries form one span. Each attempt sends the W3C traceparent header, so the service you call can join the trace.

Testing ​

Faking responses ​

Your tests shouldn't wait on another service or charge a real card. httpclienttest.New installs a fake in your test's application. The fake answers your application's requests without touching the network, and records each request for your assertions. By default, every request gets an empty 200:

go
package feature_test

import (
	"testing"

	"go.laravel.com/httpclienttest"

	"app/tests"
)

func TestShowsAGitHubProfile(t *testing.T) {
	client := tests.New(t)
	github := httpclienttest.New(client)

	client.Get("/profile").AssertOK()

	github.AssertSentCount(1)
}

Each test's application gets its own fake, so tests that run in parallel never share a fake. An application takes only one fake, and a second call to httpclienttest.New for the same test client fails the test, so give that single fake a pattern for each API your test calls. The fake also answers requests that your test sends itself with client.Context(), such as by calling a job's Handle.

To fake specific URLs, pass URL patterns to Respond. A pattern may match anywhere in the URL, and * matches anything. Each request gets the answer of the first pattern that matches it. httpclienttest.Status, Text, and JSON make a response, and WithStatus, WithHeader, and WithBody change the response:

go
github := httpclienttest.New(client).
	Respond("api.github.com/users/*", httpclienttest.JSON(map[string]string{
		"login": "taylorotwell",
		"name":  "Taylor Otwell",
	})).
	Respond("api.stripe.com/*", httpclienttest.JSON(map[string]string{
		"error": "card_declined",
	}).WithStatus(402)).
	Respond("example.com/health", httpclienttest.Status(503)).
	Respond("*", httpclienttest.Text("Hello World"))

To test what happens when a host can't be reached, use httpclienttest.FailedConnection(). Requests that match its pattern fail with a *httpclient.ConnectionError:

go
github := httpclienttest.New(client).Respond("api.github.com/*", httpclienttest.FailedConnection())

Faked requests go through the client's hooks and retries as real requests do, but they don't wait between retries.

说明

The fake answers requests sent with Laravel's HTTP client. It doesn't fake libraries that make their own requests, such as an SDK with its own http.Client. To learn how to point such a library at a server your test starts, check out the testing guide's section on replacing dependencies.

Response sequences ​

To test code that retries, you may want a URL to fail a few times and then succeed. httpclienttest.NewSequence gives each request the next answer in turn:

go
github := httpclienttest.New(client).Respond("api.github.com/*", httpclienttest.NewSequence(
	httpclienttest.FailedConnection(),
	httpclienttest.Status(503),
	httpclienttest.JSON(map[string]string{"login": "taylorotwell"}),
))

Once a sequence runs out, its requests fail with httpclient.ErrNotFaked. To keep answering instead, give WhenEmpty the answer for every later request. WhenEmpty takes any answer, such as a response, FailedConnection(), or an AnswerFunc:

go
httpclienttest.NewSequence(httpclienttest.Text("Hello World")).
	WhenEmpty(httpclienttest.JSON(map[string]string{"error": "not_found"}).WithStatus(404))

Fake callbacks ​

Sometimes the answer depends on the request, such as a status that depends on the token the request sends. Use httpclienttest.AnswerFunc, whose function receives the request and returns any answer:

go
api := httpclienttest.New(client).Respond(
	"api.example.com/*",
	httpclienttest.AnswerFunc(func(req *httpclienttest.Request) httpclienttest.Answer {
		if req.HasHeader("Authorization", "Bearer secret") {
			return httpclienttest.Status(200)
		}

		return httpclienttest.Status(401)
	}),
)

The function may inspect any part of the request, with the same Request fields and methods that assertions use.

Faking streamed responses ​

A fake answers Stream as it answers other requests. To fake a stream of server-sent events, give the response a body in the event stream format. For example, this test fakes OpenAI's reply for the chat handler. The handler sends each piece of the reply to the browser as an event of its own, so the test looks for each event's data: line:

go
func TestChatRepliesStream(t *testing.T) {
	client := tests.New(t)
	httpclienttest.New(client).Respond("api.openai.com/*", httpclienttest.Text(
		"data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"}}]}\n\n"+
			"data: {\"choices\":[{\"delta\":{\"content\":\"lo!\"}}]}\n\n"+
			"data: [DONE]\n\n",
	).WithHeader("Content-Type", "text/event-stream"))

	client.Get("/chat").AssertOK().AssertSee("data: Hel").AssertSee("data: lo!")
}

Inspecting requests ​

The fake records every request your application sends, including each retry. AssertSent takes a function that receives each request, and passes when the function returns true for at least one request:

go
github.AssertSent(func(req *httpclienttest.Request) bool {
	return req.Method == http.MethodPost &&
		req.URL == "https://example.com/users" &&
		req.HasHeader("X-Tenant", "acme") &&
		req.Data()["name"] == "Taylor"
})

github.AssertNotSent(func(req *httpclienttest.Request) bool {
	return strings.Contains(req.URL, "/posts")
})
github.AssertSentCount(5)
github.AssertNothingSent()

An *httpclienttest.Request holds the whole request, in both AssertSent functions and fake callbacks:

Field or methodDescription
MethodThe HTTP method, such as GET
URLThe full URL, including the base URL and the query string
HeaderEvery header, as an http.Header
HasHeader(name, value)Whether the header was sent with exactly this value
BodyThe raw body, as []byte
Data()A JSON object body or a form's fields, as a map[string]any
JSON[T]()Decodes a JSON body into a type of your own
FilesThe files attached to a multipart form
HasFile(field, name)Whether a file was attached under this form field with this file name

For example, check a multipart upload with HasFile:

go
github.AssertSent(func(req *httpclienttest.Request) bool { return req.HasFile("report", "q3.pdf") })

For other checks, Sent() returns every request. Recorded() pairs each request with its fake response, which is nil for a request that got no response:

go
recorded := github.Recorded()
if recorded[0].Response.Status != 500 {
	t.Errorf("the first request got %d", recorded[0].Response.Status)
}

Stray requests ​

A request that no pattern matches gets an empty 200. To make sure your test fakes every request it expects, call PreventStrayRequests. A request that no pattern matches then fails with httpclient.ErrNotFaked, and the error names the request's method and URL:

go
github := httpclienttest.New(client).
	Respond("api.github.com/*", httpclienttest.JSON(map[string]string{"login": "taylorotwell"})).
	PreventStrayRequests()

To let some requests through to the network, such as requests to a server your test starts, allow their URL patterns with AllowStrayRequests. This is also how you test a stream that stalls or breaks part way:

go
server := httptest.NewServer(handler)
t.Cleanup(server.Close)

github := httpclienttest.New(client).
	Respond("api.github.com/*", httpclienttest.JSON(map[string]string{"login": "taylorotwell"})).
	AllowStrayRequests(server.URL + "/*")