Skip to content
go-spherePublic

About

A unified HTTP framework abstraction layer for Go that provides a consistent interface across multiple popular web frameworks.

Resources

Security policy

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

 

History

169 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

httpx

A unified HTTP framework abstraction layer for Go that provides a consistent interface across multiple popular web frameworks.

Overview

httpx is designed to provide a framework-agnostic HTTP handling layer that allows you to write application logic once and run it on any supported HTTP framework.

Adapters and support levels

The adapters are not equals. Pick one by its support level, not by the framework you would otherwise reach for:

Adapter Framework Level Use in production
stdx net/http Reference. The complete implementation of the httpx contract and the default engine of sphere. Yes, recommended.
ginx Gin Production. Implements every httpx interface and optional capability, with no exceptions. Yes.
echox Echo v4 Experimental. Fairly complete, but not held to production standards. Not recommended.
fiberx Fiber v3 Reference only. Incomplete; shows how to adapt a buffering, fasthttp-based framework to httpx. No.
hertzx Hertz Reference only. Incomplete; shows how to adapt a buffering framework to httpx. No.
  • stdx is the standard httpx is measured against: what its route tree accepts is the route grammar, and what it does is the contract. It is the standard library plus a small route tree written for this contract, pulls in no framework, and serves Static/HandleStd/std middleware with nothing to bridge; a 10-layer chain costs ~35 ns with zero allocations.
  • ginx must match stdx on every interface and capability. A difference between the two is a ginx bug.
  • echox runs the full shared suite, but its fixes and edge cases get less scrutiny than the production adapters'.
  • fiberx and hertzx run the shared suite too, but their frameworks buffer the whole response and route on fasthttp-style request objects, and some behaviour is only approximated (see each package's documentation for the known differences). Use them to learn how an adapter is built, not to serve traffic.

Adapter options

Every adapter's New takes the same core options under the same names, so setup code is portable across all five:

Option Type Notes
WithAddr(addr) string The listen address, on all five. ginx/echox/stdx create the *http.Server if one was not supplied; fiberx wraps WithListen; hertzx only applies it when the adapter builds the engine.
WithErrorHandler(h) httpx.ErrorHandler Framework-neutral, on all five. h is called with a real adapter-backed httpx.Context.
WithNativeErrorHandler(h) adapter's own ErrorHandler ginx and hertzx only — the two frameworks whose error-handler shape the adapter installs directly.
WithTrustedProxies(...) ...string Uniform ClientIP policy; an empty list ignores forwarding headers.
WithMaxBodySize(n) int64 Request body limit for routes registered through the adapter; over it is a 413 through the error handler. n <= 0 (default) adds none, though fiberx/hertzx keep their framework's own 4 MiB limit, raised to n when n is larger.
WithEngine(e) native engine Bring your own *gin.Engine, *echo.Echo, *fiber.App, *server.Hertz (stdx takes WithServer(*http.Server)).

Two related names are not portable, on purpose:

  • <adapter>.DefaultErrorHandler — each adapter exports DefaultErrorHandler, which is that adapter's default handler in its native shape: the value it installs on the framework when you configure nothing. The five signatures therefore differ (func(*gin.Context, error), echo.HTTPErrorHandler, func(fiber.Ctx, error) error, func(context.Context, *app.RequestContext, error)), and for stdx the native shape simply is httpx.ErrorHandler, because net/http has no error handler of its own to match.
  • From<Framework> — ginx.FromGin, echox.FromEcho, fiberx.FromFiber, hertzx.FromHertz and stdx.FromStd build an httpx.Context from a native one, so httpx helpers can be used from a native error handler or middleware. Each takes what its framework hands you.

Testing

The shared conformance suite lives in httpxtest. An adapter is certified on its own — against a recorded contract rather than against another adapter — by declaring its capabilities and an engine factory:

func TestConformance(t *testing.T) {
    httpxtest.Run(t, httpxtest.Suite{
        Name: "ginx",
        Caps: httpxtest.Caps{NamedWildcard: true, Flusher: true},
        NewEngine: func(tb testing.TB, opts httpxtest.Options) httpx.Engine {
            return ginx.New(
                ginx.WithEngine(gin.New()),
                ginx.WithErrorHandler(opts.ErrorHandler),
                ginx.WithMaxBodySize(opts.MaxBodySize),
            )
        },
    })
}

A third-party adapter can import httpxtest and certify itself against the same contract as the official five: registration and routing, chain control flow (including how httpx layers nest inside the framework's own middleware), request bodies and binders, forms and uploads, and the edges — repeated query/header keys, unknown-length bodies, encoded paths, large bodies. Every capability an adapter declares in Caps is also checked against what it actually does. Each official adapter runs the suite from its own module, in its conformance_test.go. Response shape is pinned by the golden contracts in httpxtest/golden/, which every adapter compares against; see that directory's README for the format. Rewrite them with make golden, which records from each adapter and then verifies that all of them still agree.

make test          # every module, including each adapter's conformance run
make golden        # rewrite and verify the shared response contracts
(cd ginx && go test -run TestConformance -v .)

# The same scenario table, measured per adapter through its own dispatcher.
go test ./conformance -run '^$' -bench '^BenchmarkHTTPXTestSuite/adapter=ginx$' -benchmem

conformance/ remains for what genuinely needs all five adapters in one process: the cross-framework benchmark tables and the tests that need a real listener. Adapter-specific behavior is tested in the adapter's own module (for example ginx/middleware_test.go for how ginx composes chains into gin routes, and ginx/middleware_alloc_test.go for the allocation guards).

Benchmarks

benchmarks/BENCHMARK.md compares all five adapters against the framework they wrap — gin, echo, fiber, hertz and net/http — on the shared scenario table, plus a fixed-rate network run.

make bench-report   # every table in one session -> benchmarks/BENCHMARK.md

Numbers may only be quoted next to each other when they came out of the same bench-report run: it compiles one test binary and measures every table from it back to back, recording the environment and the git revision alongside. The per-table targets (make bench-adapter, bench-suite, bench-native, bench-network) are for iterating on one table, and two of their runs are two different environments. See benchmarks/README.md.

Streaming and Server-Sent Events

Every official adapter implements the optional Streamer context capability. Use AsStreamer when you need raw incremental output such as NDJSON:

router.GET("/chunks", func(ctx httpx.Context) error {
    streamer, ok := httpx.AsStreamer(ctx)
    if !ok {
        return httpx.ErrStreamerNotSupported
    }
    return streamer.Stream(http.StatusOK, "application/x-ndjson", func(w io.Writer) error {
        for _, chunk := range chunks {
            if _, err := fmt.Fprintf(w, "%s\n", chunk); err != nil {
                return err // client gone; stop producing
            }
        }
        return nil
    })
})

Each write made by the stream callback is flushed to the client. The status line and headers are sent before the callback runs, so a client such as an EventSource sees the connection open while the handler still waits for its first event. Once streaming starts, the response is committed, so callback errors are for termination and cleanup; they cannot become a different HTTP response.

ServerSentEvents is the framework-neutral SSE layer over Streamer:

router.GET("/events", func(ctx httpx.Context) error {
    return httpx.ServerSentEvents(ctx, func(w *httpx.SSEWriter) error {
        if err := w.SendJSON("update", payload); err != nil {
            return err // client gone; stop producing
        }
        return w.Send(&httpx.SSEEvent{ID: "42", Event: "done", Data: "bye"})
    })
})

SSEWriter supports Send, SendEvent, SendData, SendJSON, and Comment. Each event is encoded and flushed as one unit. ServerSentEvents sets Content-Type: text/event-stream, Cache-Control: no-cache, and X-Accel-Buffering: no; stop producing as soon as a send fails or the request context is canceled.

Streaming capability matrix:

Capability Gin Echo Hertz Fiber net/http
Streamer / ServerSentEvents Yes Yes Yes Yes Yes
Flusher / AsFlusher Yes Yes Yes No Yes

Fiber uses its deferred stream-writer API, so the stream callback runs after the handler returns and Stream returns nil immediately. In-process requests through httpx.TestRequester buffer stream writes into the final response body; use a real HTTP connection when testing incremental delivery or disconnects.

Middleware

There is one middleware form. A httpx.Middleware receives the rest of the chain and returns the handler that runs in its place:

type Middleware func(next httpx.Handler) httpx.Handler

func RequestID(next httpx.Handler) httpx.Handler {
    return func(ctx httpx.Context) error {
        ctx.SetContext(withRequestID(ctx.Context()))
        return next(ctx)
    }
}

engine.Use(RequestID)              // engine scope
needAuth := api.Group("/", auth)   // group scope, in one call

Use is on both httpx.Engine and httpx.Router (through httpx.MiddlewareScope), and Group's variadic takes the same type.

Five things to know about:

  • Stopping the chain is returning without calling next — after writing a response, or by returning an error for the adapter's error handler to render. There is no Abort to reason about and no layer index.
  • No per-request state. The chain is composed into each route at registration: one call per layer, zero allocations, and no depth at which cost stops growing linearly.
  • What a chain covers. Every registered route, Static, StaticFS and HandleStd included — a layer wraps a static mount and can block it. Plus, for an engine-scope chain only, the paths no route matched: the adapter's 404/405 fallback composes the engine's own layers in front of the handler that renders the error, so an access log, a panic recovery layer or a CORS layer sees a request for /nope and may answer it instead. A group's layers never cover an unmatched path — a 404 belongs to no group.
  • A route's chain is resolved when the route is registered, not when its scope was created, so engine.Use after a group exists still reaches the routes that group registers afterwards. Routes already registered keep the chain they were registered with — the rule every framework applies to its own Use, and what makes a registered route immutable.
  • An error from an inner layer is rendered at the route, not at the layer that produced it, so a layer that logs the outcome should use the error returned by next, not only Context.StatusCode.

Native middleware

The framework's own middleware is registered with UseNative, on both Engine and Router in ginx (gin.HandlerFunc), echox (echo.MiddlewareFunc), fiberx (fiber.Handler) and hertzx (app.HandlerFunc):

router.(*ginx.Router).UseNative(gin.Recovery())

There is no Adapt<Framework>Middleware any more, and there cannot be: every httpx layer on a scope shares a single native handler slot, so a native middleware wrapped as an httpx.Middleware would advance the framework's own index past that slot instead of into the httpx chain. UseNative was already the documented preference; it is now the only way.

A UseNative layer therefore always runs outside everything registered with Use on the same scope, whatever the call order. On fiberx one extra rule applies: register it before the routes it should wrap, because fiber matches its route stack in registration order.

stdx has no UseNative, deliberately. There is no framework chain to hand a middleware to, and net/http has no middleware type but the one AdaptStdMiddleware already takes.

Plain net/http middleware

AdaptStdMiddleware(func(http.Handler) http.Handler) httpx.Middleware is on all five adapters: context values (ctx.Context()), response-writer wrapping and short-circuiting all propagate (on stdx, ginx and echox, arbitrary *http.Request header/field mutations propagate as well, whereas fiberx and hertzx forward context.Context mutations while buffering non-streamed responses for replay). func(http.Handler) http.Handler is framework-neutral, so unlike a native middleware it maps directly onto the composed form.

router.Use(ginx.AdaptStdMiddleware(otelhttp.NewMiddleware("api")))

Router Feature Detection

httpx exposes optional router capability detection through the RouterFeatureProvider interface implemented by every Router.

supports := router.SupportsRouterFeature(httpx.RouterFeatureNamedWildcard)

Currently supported router feature keys:

  • httpx.RouterFeatureNamedWildcard - named wildcard params in route path patterns, e.g. /*filepath

Feature values are adapter declarations and can be extended in future versions.

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

A unified HTTP framework abstraction layer for Go that provides a consistent interface across multiple popular web frameworks.

Resources

Security policy

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages