/gomega:ghttpfrom gomega
Provides ghttp test HTTP server utilities for testing HTTP clients: NewServer/NewTLSServer, AppendHandlers, Verify* assertions, RespondWith, CombineHandlers, RouteToHandler, and RoundTripper. Use when testing code that makes outbound HTTP requests.
Ships in gomega. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
ghttp spins up a real test HTTP server so you can exercise code that makes outbound HTTP requests (clients, SDKs, anything calling net/http). You register handlers that assert on the incoming request and return a canned response; the server records every request it receives. It wraps net/http/httptest.
import (
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"net/http"
)
This skill assumes a dot-import of gomega. Docs: https://onsi.github.io/gomega/#ghttp-testing-http-clients. See gomega:matchers for the matchers used in assertions and gomega:async if the client is non-blocking.
server := ghttp.NewServer() // or ghttp.NewTLSServer()
defer server.Close() // ALWAYS defer Close
client := myapi.NewClient(server.URL()) // URL is random per run — inject it
The server URL is auto-generated and varies between runs, so you must inject server.URL() into the code under test rather than hard-coding it. With Ginkgo, server = ghttp.NewServer() in BeforeEach and server.Close() in AfterEach.
server.AppendHandlers(handlers...) registers an ordered list of handlers, one per expected request. The first request is matched against the first handler, the second against the second, and so on. A handler is just an http.HandlerFunc.
server.AppendHandlers(
ghttp.VerifyRequest("GET", "/sprockets"),
)
Gotchas (the core mental model):
ghttp.CombineHandlers (below).Expect(server.ReceivedRequests()).To(HaveLen(1)).These return handlers that fail the test if the request doesn't match:
ghttp.VerifyRequest("GET", "/sprockets") // method + path
ghttp.VerifyRequest("GET", "/sprockets", "category=encabulators") // + RawQuery
ghttp.VerifyRequest("GET", MatchRegexp(`^/sprockets/\d+$`)) // path via a matcher
ghttp.VerifyHeader(http.Header{"X-API-Version": []string{"1.0"}})
ghttp.VerifyHeaderKV("X-API-Version", "1.0") // convenience for one key
ghttp.VerifyHost("api.example.com") // req.Host; string or matcher
ghttp.VerifyContentType("application/json") // exact Content-Type, params included
ghttp.VerifyMimeType("application/json") // ignores params like "; charset=utf-8"
ghttp.VerifyBasicAuth("gopher", "tacoshell")
ghttp.VerifyBody([]byte("raw body"))
ghttp.VerifyJSON(`{"name":"foo"}`) // semantic JSON compare
ghttp.VerifyJSONRepresenting(Sprocket{Name: "foo"}) // marshal obj, then compare
ghttp.VerifyForm(url.Values{"q": []string{"x"}}) // parsed form values
ghttp.VerifyFormKV("q", "x") // convenience for one key
ghttp.VerifyProtoRepresenting(expectedMsg) // protobuf body, proto.Equal compare
The path argument to VerifyRequest is a string (exact match) or a Gomega matcher such as MatchRegexp(...) or HavePrefix(...) — not a *regexp.Regexp (that's RouteToHandler). The optional query string is parsed and compared as url.Values: parameter order doesn't matter, but the parameters must match exactly. VerifyJSON/VerifyJSONRepresenting also require the application/json mime type, and VerifyProtoRepresenting requires Content-Type: application/x-protobuf. You can write your own verify handler — pass any http.HandlerFunc that makes assertions against the *http.Request.
ghttp.CombineHandlers(...) wraps several handlers into one handler so they all run against a single request. Pass that one wrapper to AppendHandlers. This is how you assert on a request and respond:
server.AppendHandlers(
ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/sprockets", "category=encabulators"),
ghttp.VerifyBasicAuth(username, password),
ghttp.VerifyHeaderKV("X-API-Version", "1.0"),
ghttp.RespondWithJSONEncoded(http.StatusOK, sprockets),
),
)
ghttp.RespondWith(http.StatusOK, `[{"name":"foo"}]`) // status + body (string or []byte) (+ optional http.Header)
ghttp.RespondWith(http.StatusOK, body, http.Header{"X-Foo": []string{"bar"}})
ghttp.RespondWithJSONEncoded(http.StatusOK, anyObject) // JSON-encodes the object for you
ghttp.RespondWithJSONEncodedPtr(&statusCode, &object) // reads through pointers at request time
ghttp.RespondWithPtr(&statusCode, &body) // body is a *string or *[]byte
ghttp.RespondWithProto(http.StatusOK, msg) // protobuf-encodes a protoadapt.MessageV1
RespondWithJSONEncoded(Ptr) and RespondWithProto set Content-Type (application/json / application/x-protobuf) unless the optional http.Header already does.
var server *ghttp.Server
var client *sprockets.Client
BeforeEach(func() {
server = ghttp.NewServer()
client = sprockets.NewClient(server.URL())
})
AfterEach(func() { server.Close() })
It("fetches sprockets", func() {
returned := []Sprocket{{Name: "entropic decoupler", Color: "red"}}
server.AppendHandlers(
ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/sprockets", "category=encabulators"),
ghttp.VerifyHeaderKV("X-API-Version", "1.0"),
ghttp.RespondWithJSONEncoded(http.StatusOK, returned),
),
)
sprockets, err := client.FetchSprockets("encabulators")
Expect(err).NotTo(HaveOccurred())
Expect(sprockets).To(Equal(returned))
Expect(server.ReceivedRequests()).To(HaveLen(1))
})
To exercise 200/401/404 against the same handler setup, capture a status (and/or body) variable in a closure via the *Ptr responders and mutate it per sub-context. The pointer is dereferenced when the request arrives:
var statusCode int
var returned []Sprocket
BeforeEach(func() {
server.AppendHandlers(ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/sprockets"),
ghttp.RespondWithJSONEncodedPtr(&statusCode, &returned),
))
})
Context("when unauthorized", func() {
BeforeEach(func() { statusCode = http.StatusUnauthorized })
It("errors", func() {
_, err := client.FetchSprockets("")
Expect(err).To(MatchError(SprocketsErrorUnauthorized))
})
})
Pass multiple handlers to AppendHandlers for clients that make several requests (e.g. pagination). They're consumed in order:
server.AppendHandlers(
ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/sprockets", "category=encabulators"),
ghttp.RespondWithJSONEncoded(http.StatusOK, firstPage),
),
ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/sprockets", "category=encabulators&pagination-token=next"),
ghttp.RespondWithJSONEncoded(http.StatusOK, secondPage),
),
)
Because the server fails when requests exceed handlers, this also asserts the client stops after the last page.
server.SetHandler(0, newHandler) // replace handler at index
h := server.GetHandler(0) // read it back
server.WrapHandler(0, extraVerifyHandler) // run an extra handler after the existing one
AppendHandlers is for ordered assertions. When requests can arrive in any order or any number of times, use server.RouteToHandler(method, path, handler) instead. The path is a string or a *regexp.Regexp.
server.RouteToHandler("POST", "/login", ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/login", "user=bob&password=password"),
ghttp.RespondWith(http.StatusOK, "your-auth-token"),
))
Routing precedence: on each request the server first checks RouteToHandler routes; if none match it pops the next AppendHandlers handler; if that stack is empty it consults the unhandled-request policy below. You can mix both: ordered assertions via AppendHandlers for the requests you care about, MUXed routes for incidental traffic (auth, health checks) that interleaves.
By default an unhandled request fails the test. To return a fixed status instead:
server.SetAllowUnhandledRequests(true)
server.SetUnhandledRequestStatusCode(http.StatusOK) // default would be 500
Unhandled requests are still recorded in server.ReceivedRequests(), so you can assert on them after the fact.
server.HTTPTestServer is the underlying *httptest.Server — use it for custom listeners (via ghttp.NewUnstartedServer() + server.Start()), TLS config, or anything ghttp doesn't wrap.server.RoundTripper(rt) returns an http.RoundTripper that redirects requests to the test server. Use it when you must hand a configured *http.Client to the code under test rather than a URL. Pass nil to use http.DefaultTransport:httpClient := &http.Client{Transport: server.RoundTripper(nil)}
RoundTripper rewrites every request to plain http:// at the server's address, so it doesn't work with NewTLSServer.
The package-level handlers assert through the global Gomega. If you're not using it — e.g. g := NewWithT(t) under plain go test, or a Gomega with a custom fail handler — build handlers from ghttp.NewGHTTPWithGomega(g), which has the same Verify*/RespondWith* methods (combine them with the package-level CombineHandlers):
g := NewWithT(t)
gh := ghttp.NewGHTTPWithGomega(g)
server.AppendHandlers(ghttp.CombineHandlers(
gh.VerifyRequest("GET", "/sprockets"),
gh.RespondWithJSONEncoded(http.StatusOK, sprockets),
))
The server's own unhandled-request check still goes through the global Gomega: without RegisterTestingT(t) an unhandled request just gets a 500 response and nothing fails, so also assert on server.ReceivedRequests().
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub onsi/gomega --plugin gomega12 skills in this plugin
/assertionsWrite correct synchronous Gomega assertions — Expect/Ω notation, the To/NotTo/ToNot/Should/ShouldNot equivalences, the multi-return error idiom, Succeed vs HaveOccurred, the .Error() chaining form, annotating assertions (format-string and func()string), tuning failure output via the format subpackage (MaxLength/MaxDepth/UseStringerRepresentation/GomegaStringer/TruncatedDiff/RegisterCustomFormatter/format.Object), and asserting inside helper functions with GinkgoHelper/WithOffset/ExpectWithOffset, NewWithT(t) for plain testing, and the g Gomega callback. Use when writing or reviewing synchronous (non-polling) Gomega assertions./asyncPolling assertions in Gomega — Eventually (poll until it passes) and Consistently (must keep passing), the func(g Gomega) callback idiom, WithTimeout/WithPolling/Within/ProbeEvery, WithContext and Ginkgo SpecContext, StopTrying/TryAgainAfter bail-outs, MustPassRepeatedly, and default-interval tuning. Use when an assertion can't be true synchronously — anything involving goroutines, channels, network calls, eventual consistency, or "wait until / stays true"./composing-matchersBuild compound Gomega assertions by combining matchers — And/SatisfyAll (all pass), Or/SatisfyAny (any pass), Not (negate), WithTransform to map the actual before matching, Satisfy for an ad-hoc predicate, HaveValue to dereference pointers/interfaces, HaveField for struct fields and method results, HaveEach for every element, plus the matchers-as-arguments idiom that lets you nest matchers inside ContainElement/ConsistOf/HaveKeyWithValue/Receive. Use when one Expect needs several requirements at once, or you want to assert deep into a value without writing a custom matcher.Other plugins' skills for the same job