Go’s standard net/http package is excellent. It’s mature, reliable, performant, and provides almost everything you need to build HTTP clients.

But there is one thing I’ve always found myself writing repeatedly: boilerplate.

Creating requests, attaching headers, configuring authentication, handling response status codes, decoding JSON, closing response bodies, managing timeouts, and implementing retries — these are common tasks in almost every backend application.

I wanted something that would make these operations simpler without introducing another heavy abstraction or a collection of third-party dependencies.

That’s why I built httpx — a small, fluent HTTP client for Go, built directly on top of the standard library.

Why Another HTTP Client?

Go already has a powerful HTTP client, so why build another one?

The answer isn’t that net/http is missing something. It’s that everyday HTTP operations often require repetitive code.

Consider a simple GET request using the standard library:

req, err := http.NewRequestWithContext(
    ctx,
    http.MethodGet,
    "https://api.example.com/v1/users/123",
    nil,
)
if err != nil {
    return nil, err
}

req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+token)

resp, err := http.DefaultClient.Do(req)
if err != nil {
    return nil, err
}
defer resp.Body.Close()

if resp.StatusCode < 200 || resp.StatusCode > 299 {
    body, _ := io.ReadAll(
        io.LimitReader(resp.Body, 1024),
    )
    return nil, fmt.Errorf(
        "unexpected status %d: %s",
        resp.StatusCode,
        body,
    )
}

var user User
if err := json.NewDecoder(
    io.LimitReader(resp.Body, 10<<20),
).Decode(&user); err != nil {
    return nil, err
}

return &user, nil

Nothing is wrong with this code. In fact, this is exactly how Go encourages us to work.

However, when you repeat this pattern across dozens of services and integrations, you end up maintaining a lot of similar code.

Now, here’s the same operation using httpx:

client := httpx.New(
    httpx.WithBaseURL("https://api.example.com/v1"),
    httpx.WithAuth(httpx.NewBearerAuth(token)),
    httpx.WithRetryPolicy(httpx.StandardRetryPolicy()),
)

user, err := httpx.ToJSON[User](
    client.GET("/users/123").Do(ctx),
)
if err != nil {
    return nil, err
}

return &user, nil

That’s the idea behind httpx: less repetitive code, a straightforward API, and the flexibility of Go’s standard HTTP implementation underneath.

What Is httpx?

httpx is a lightweight, fluent HTTP client for Go.

It is designed to simplify common HTTP operations while keeping the underlying implementation close to net/http.

Some of its core principles are:

  • Simplicity: A fluent API that’s easy to read and understand.
  • Zero dependencies: Built using Go’s standard library.
  • Type safety: Generic JSON response decoding.
  • Control: Configurable timeouts, connection pooling, authentication, and retries.
  • Observability: Request hooks, structured logging, and HTTP tracing.
  • Flexibility: Support for custom http.Client and http.Transport implementations.

Let’s look at some of the features.

1. Fluent Request Building

The fluent API is one of the main reasons I built this package.

Instead of manually constructing every request, you can chain operations together.

resp, err := client.GET("/users").
    QueryParam("status", "active").
    QueryParam("limit", "20").
    Header("Accept", "application/json").
    Do(ctx)

if err != nil {
    return err
}
defer resp.Close()

if !resp.IsSuccess() {
    return fmt.Errorf("request failed: %s", resp.Status)
}

It supports the common HTTP methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, QUERY.The goal is to make request construction readable without hiding what’s actually happening.

2. Generic JSON Response Decoding

Go generics make working with JSON responses much cleaner.

With httpx, you can decode a response directly into a type using ToJSON[T].

type Todo struct {
    ID        int    `json:"id"`
    Title     string `json:"title"`
    Completed bool   `json:"completed"`
}

todo, err := httpx.ToJSON[Todo](
    client.GET("/todos/1").Do(ctx),
)
if err != nil {
    return err
}

fmt.Println(todo.Title)

No need to manually create a JSON decoder or remember to close the response body.

ToJSON[T] handles successful response decoding and closes the response body automatically.

It also handles non-2xx responses through a typed HTTPError.

This keeps the calling code focused on application logic rather than HTTP response plumbing.

3. Built-in Authentication

Authentication is another common requirement when integrating external services.

httpx supports several authentication mechanisms:

  • Bearer token authentication
  • Basic authentication
  • API key authentication through headers
  • API key authentication through query parameters

For example:

client := httpx.New(
    httpx.WithBaseURL("https://api.example.com"),
    httpx.WithAuth(
        httpx.NewBearerAuth("your-access-token"),
    ),
)

You can also override authentication at the request level when necessary.

4. Configurable Connection Pooling

HTTP connection management matters, especially in backend applications that communicate with multiple external services.

Go’s http.Transport already provides connection pooling, but configuring it appropriately is important.

httpx provides a PoolConfig option to configure connection-related settings.

client := httpx.New(
    httpx.WithPoolConfig(httpx.PoolConfig{
        MaxIdleConns:           100,
        MaxIdleConnsPerHost:    20,
        MaxConnsPerHost:        50,
        IdleConnTimeout:        90 * time.Second,
        TLSHandshakeTimeout:    10 * time.Second,
        ResponseHeaderTimeout:  5 * time.Second,
    }),
)

You can also configure request timeouts independently.

client := httpx.New(
    httpx.WithTimeout(10 * time.Second),
)

The default timeout is 30 seconds.

For applications with custom networking requirements, you can provide your own http.Client or http.Transport.

5. Retry Mechanism With Safe Defaults

Network failures happen.

An upstream service might temporarily become unavailable, return a rate-limit response, or experience a gateway timeout.

Retries can help, but implementing them carelessly can introduce serious problems.

For example, automatically retrying a POST request that creates an order could create duplicate orders.

That’s why retries in httpx are opt-in.

You can enable the standard retry policy:

client := httpx.New(
    httpx.WithRetryPolicy(
        httpx.StandardRetryPolicy(),
    ),
)

The standard policy provides:

  • Three total attempts, including the initial request.
  • Retries for network errors.
  • Retries for HTTP 429, 502, 503, and 504.
  • Capped exponential backoff.

By default, retries are restricted to supported idempotent HTTP methods and replayable request bodies.

If you explicitly want to retry a POST request, you can opt in:

resp, err := client.POST("/orders").
    IdempotencyKey("order-12345").
    JSON(payload).
    Retryable().
    Do(ctx)

For operations with side effects, always prefer server-supported idempotency keys.

The client can retry requests, but it cannot independently guarantee that an operation won’t be executed twice.

6. Request and Response Hooks

Observability is important in distributed systems.

When an application communicates with multiple services, understanding what happened during an HTTP request can save significant debugging time.

httpx provides request and response hooks that allow you to integrate custom instrumentation.

You can use them for:

  • Request and response logging.
  • Metrics collection.
  • Custom monitoring.
  • Request instrumentation.
  • Integration with existing observability systems.

It also provides logger and tracer integration points.

The intention is to make observability possible without forcing a particular logging or tracing implementation on users.

7. HTTP Tracing and Diagnostics

Sometimes an HTTP request is slow, but knowing that it took five seconds isn’t enough.

You want to understand where those five seconds went.

Was it DNS resolution? TCP connection establishment? TLS negotiation? Waiting for response headers?

httpx uses Go’s net/http/httptrace capabilities to provide request-level timing information.

This makes it easier to investigate network latency and understand the behavior of upstream services.

8. Streaming Large Responses

Not every HTTP response should be loaded entirely into memory.

Consider downloading a large archive or exporting a report.

Reading the entire response into a byte slice can unnecessarily increase memory consumption.

httpx provides Response.CopyTo to stream response data directly into an io.Writer.

resp, err := client.GET("/exports/archive").Do(ctx)
if err != nil {
    return err
}

if !resp.IsSuccess() {
    defer resp.Close()
    return fmt.Errorf("download failed: %s", resp.Status)
}

file, err := os.Create("archive.zip")
if err != nil {
    _ = resp.Close()
    return err
}
defer file.Close()

if _, err := resp.CopyTo(file); err != nil {
    return err
}

This allows you to download large responses without buffering the entire response body in memory.

For JSON and HTTP error helper reads, httpx also provides a configurable maximum response size, which defaults to 10 MiB.

9. Inspect Requests and Generate cURL Commands

Debugging API integrations sometimes requires reproducing a request outside the application.

You might want to inspect the exact URL, headers, and request body, or share a reproducible request with another developer.

httpx provides two useful methods for this:

  • ToText() — returns a human-readable representation of the outgoing request.
  • ToCURL() — generates an equivalent cURL command.

For example:

req := httpx.New().
    POST("https://api.example.com/users").
    Header("Authorization", "Bearer your-token").
    JSON(map[string]any{
        "name":  "John Doe",
        "email": "john@example.com",
    })

curl, err := req.ToCURL(ctx)
if err != nil {
    return err
}

fmt.Println(curl)

You can copy the generated command into your terminal to reproduce the request.

Both methods inspect the request without sending it.

One important consideration: generated output may contain sensitive information such as authorization headers, cookies, or API keys. Be careful when logging or sharing it.

Getting Started

Getting started with httpx is straightforward.

You need Go 1.22 or newer.

Install the package:

go get github.com/thedevsaddam/httpx

Import it:

import "github.com/thedevsaddam/httpx"

Create a client and start making requests.

client := httpx.New(
    httpx.WithBaseURL("https://api.example.com"),
    httpx.WithTimeout(10*time.Second),
)

resp, err := client.GET("/health").Do(ctx)
if err != nil {
    return err
}
defer resp.Close()

if !resp.IsSuccess() {
    return fmt.Errorf("unexpected response: %s", resp.Status)
}

For more examples and configuration options, check the project documentation.

GitHub: https://github.com/thedevsaddam/httpx

A Few Design Decisions

While building httpx, I wanted to avoid turning a small HTTP client into a framework.

There are already excellent HTTP libraries in the Go ecosystem. I don’t think every project needs another abstraction layer with its own configuration system, middleware architecture, or dependency tree.

I wanted to keep a few things simple:

1. Stay close to the standard library.

Developers should still understand what’s happening underneath. httpx should make common operations easier, not hide the HTTP implementation.

2. Avoid unnecessary dependencies.

The package uses the Go standard library. Fewer dependencies mean less dependency management and a smaller third-party dependency surface.

3. Make retries explicit.

Retries are useful, but they should never silently introduce unexpected side effects.

4. Keep the API predictable.

A developer familiar with Go’s HTTP package should be able to understand httpx without learning an entirely new programming model.

5. Make the common path simple.

Most HTTP integrations involve building a request, sending it, handling the response, and decoding the result. That workflow should not require excessive boilerplate.

What’s Next?

httpx is an ongoing project, and I intend to keep improving it while maintaining its core philosophy: simplicity, flexibility, and minimal dependencies.

I’m particularly interested in feedback from developers who use it in real-world backend applications.

If you work with Go and frequently integrate with REST APIs, give it a try.

Contributions, suggestions, bug reports, and discussions are welcome.

Final Thoughts

Go’s standard library is already powerful enough to build production-grade HTTP clients.

I built httpx because I wanted a more convenient developer experience without sacrificing that foundation.

It’s not intended to replace net/http. It’s intended to make working with it a little more enjoyable.

If that sounds useful, check out the project:

GitHub — thedevsaddam/httpx

Happy coding! 🚀