httpclient

package
v1.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 13, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package httpclient offers HTTP client construction helpers with OAuth2 authentication and TLS/mTLS options.

It provides a fluent Builder that can create an http.Client with automatic Bearer token injection using oauth2client.TokenManager, configurable TLS (custom CA, mTLS, insecure for tests), timeouts, base transports, and redirect handling. OAuth2Transport can wrap any RoundTripper.

Features

  • Fluent builder for http.Client with optional OAuth2 token injection
  • TLS 1.2+ by default, with custom CA/mTLS and optional InsecureSkipVerify
  • Custom timeouts, base transport override, and redirect disabling
  • Reusable OAuth2Transport for manual composition

Quick Start

client, err := httpclient.NewBuilder().
    WithOAuth2(ctx,
        "https://auth.example.com/oauth/v2/token",
        "client-id",
        "client-secret",
        "openid profile",
    ).
    WithTLS("/path/to/ca.crt", "", "").
    WithTimeout(60 * time.Second).
    Build()
if err != nil {
    log.Fatal(err)
}

resp, err := client.Get("https://api.example.com/data")

Manual Transport Wrapping

transport := httpclient.NewOAuth2Transport(tm, nil)
client := &http.Client{Transport: transport}

All components are safe for concurrent use if the provided TokenManager is.

Example

Example demonstrates basic HTTP client usage with OAuth2.

package main

import (
	"context"
	"fmt"

	"github.com/AmmannChristian/go-authx/httpclient"
	"github.com/AmmannChristian/go-authx/oauth2client"
)

func main() {
	ctx := context.Background()

	// Create token manager
	tm := oauth2client.NewTokenManager(
		ctx,
		"https://auth.example.com/oauth/v2/token",
		"client-id",
		"client-secret",
		"openid profile",
	)

	// Create HTTP client
	client := httpclient.NewHTTPClient(tm)

	fmt.Printf("HTTP client created with timeout: %v\n", client.Timeout)
}
Output:
HTTP client created with timeout: 30s

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewHTTPClient

func NewHTTPClient(tm *oauth2client.TokenManager) *http.Client

NewHTTPClient is a convenience function that creates a simple HTTP client with OAuth2 authentication. For more configuration options, use Builder instead.

Example:

tm := oauth2client.NewTokenManager(ctx, tokenURL, clientID, clientSecret, scopes)
client := httpclient.NewHTTPClient(tm)
resp, err := client.Get("https://api.example.com/data")
Example

ExampleNewHTTPClient demonstrates the simple way to create an HTTP client.

package main

import (
	"context"
	"fmt"

	"github.com/AmmannChristian/go-authx/httpclient"
	"github.com/AmmannChristian/go-authx/oauth2client"
)

func main() {
	ctx := context.Background()

	tm := oauth2client.NewTokenManager(
		ctx,
		"https://auth.example.com/oauth/v2/token",
		"client-id",
		"client-secret",
		"openid",
	)

	client := httpclient.NewHTTPClient(tm)

	fmt.Printf("Client timeout: %v\n", client.Timeout)
}
Output:
Client timeout: 30s

Types

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder provides a fluent interface for constructing HTTP clients with optional OAuth2 authentication and TLS/mTLS support.

func NewBuilder

func NewBuilder() *Builder

NewBuilder creates a new HTTP client builder.

Example

ExampleNewBuilder demonstrates using the builder pattern for HTTP clients.

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/AmmannChristian/go-authx/httpclient"
)

func main() {
	ctx := context.Background()

	client, err := httpclient.NewBuilder().
		WithOAuth2(ctx, "https://auth.example.com/oauth/v2/token", "client-id", "secret", "openid").
		WithTimeout(60 * time.Second).
		Build()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Client configured with timeout: %v\n", client.Timeout)
}
Output:
Client configured with timeout: 1m0s

func (*Builder) Build

func (b *Builder) Build() (*http.Client, error)

Build constructs the HTTP client with the configured options.

Returns:

  • *http.Client: Configured HTTP client
  • error: Error if configuration is invalid

func (*Builder) WithBaseTransport

func (b *Builder) WithBaseTransport(transport http.RoundTripper) *Builder

WithBaseTransport sets a custom base transport. This is useful for adding custom middleware or using a custom connection pool.

func (*Builder) WithInsecureSkipVerify

func (b *Builder) WithInsecureSkipVerify() *Builder

WithInsecureSkipVerify disables TLS certificate verification (NOT RECOMMENDED for production). This should only be used for testing or development purposes.

func (*Builder) WithOAuth2

func (b *Builder) WithOAuth2(ctx context.Context, tokenURL, clientID, clientSecret, scopes string) *Builder

WithOAuth2 enables OAuth2 client credentials authentication by creating a new TokenManager.

Parameters:

  • ctx: Context for token requests
  • tokenURL: OAuth2 token endpoint (e.g., "https://auth.example.com/oauth/v2/token")
  • clientID: OAuth2 client identifier
  • clientSecret: OAuth2 client secret
  • scopes: Space-separated list of OAuth2 scopes (e.g., "openid profile email")
Example

ExampleBuilder_WithOAuth2 demonstrates OAuth2 configuration.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/AmmannChristian/go-authx/httpclient"
)

func main() {
	ctx := context.Background()

	client, err := httpclient.NewBuilder().
		WithOAuth2(
			ctx,
			"https://auth.example.com/oauth/v2/token",
			"my-client-id",
			"my-client-secret",
			"openid profile email",
		).
		Build()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("OAuth2 authentication configured")
	_ = client
}
Output:
OAuth2 authentication configured

func (*Builder) WithTLS

func (b *Builder) WithTLS(caFile, certFile, keyFile string) *Builder

WithTLS enables TLS for the connection.

Parameters:

  • caFile: Path to CA certificate for server verification (optional, uses system roots if empty)
  • certFile: Path to client certificate for mTLS (optional, must be paired with keyFile)
  • keyFile: Path to client private key for mTLS (optional, must be paired with certFile)
Example

ExampleBuilder_WithTLS demonstrates TLS configuration.

package main

import (
	"context"
	"fmt"

	"github.com/AmmannChristian/go-authx/httpclient"
)

func main() {
	ctx := context.Background()

	client, err := httpclient.NewBuilder().
		WithOAuth2(ctx, "https://auth.example.com/oauth/v2/token", "client-id", "secret", "openid").
		WithTLS(
			"/path/to/ca.crt",     // CA certificate
			"/path/to/client.crt", // Client certificate (optional)
			"/path/to/client.key", // Client key (optional)
		).
		Build()
	if err != nil {
		// In this example, files don't exist, so we expect an error
		fmt.Println("TLS configuration attempted")
		return
	}

	fmt.Println("TLS configured")
	_ = client
}
Output:
TLS configuration attempted

func (*Builder) WithTimeout

func (b *Builder) WithTimeout(timeout time.Duration) *Builder

WithTimeout sets the request timeout for the HTTP client. Default is 30 seconds if not specified.

Example

ExampleBuilder_WithTimeout demonstrates timeout configuration.

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/AmmannChristian/go-authx/httpclient"
)

func main() {
	ctx := context.Background()

	client, err := httpclient.NewBuilder().
		WithOAuth2(ctx, "https://auth.example.com/oauth/v2/token", "client-id", "secret", "openid").
		WithTimeout(45 * time.Second).
		Build()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Timeout: %v\n", client.Timeout)
}
Output:
Timeout: 45s

func (*Builder) WithTokenManager

func (b *Builder) WithTokenManager(tm *oauth2client.TokenManager) *Builder

WithTokenManager sets the OAuth2 token manager for automatic authentication.

func (*Builder) WithoutRedirects

func (b *Builder) WithoutRedirects() *Builder

WithoutRedirects disables automatic redirect following. By default, the client follows up to 10 redirects.

Example

ExampleBuilder_WithoutRedirects demonstrates disabling redirect following.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/AmmannChristian/go-authx/httpclient"
)

func main() {
	ctx := context.Background()

	client, err := httpclient.NewBuilder().
		WithOAuth2(ctx, "https://auth.example.com/oauth/v2/token", "client-id", "secret", "openid").
		WithoutRedirects().
		Build()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Redirects disabled")
	_ = client
}
Output:
Redirects disabled

type OAuth2Transport

type OAuth2Transport struct {
	// Base is the underlying HTTP transport. If nil, http.DefaultTransport is used.
	Base http.RoundTripper

	// TokenManager provides OAuth2 access tokens.
	TokenManager *oauth2client.TokenManager
}

OAuth2Transport is an http.RoundTripper that automatically adds OAuth2 Bearer tokens to outgoing HTTP requests.

It wraps an existing transport (typically http.DefaultTransport) and injects the Authorization header before each request.

func NewOAuth2Transport

func NewOAuth2Transport(tm *oauth2client.TokenManager, base http.RoundTripper) *OAuth2Transport

NewOAuth2Transport creates a new OAuth2Transport with the given token manager. The base transport defaults to http.DefaultTransport if not specified.

Example

ExampleNewOAuth2Transport demonstrates creating a custom transport.

package main

import (
	"context"
	"fmt"

	"github.com/AmmannChristian/go-authx/httpclient"
	"github.com/AmmannChristian/go-authx/oauth2client"
)

func main() {
	ctx := context.Background()

	tm := oauth2client.NewTokenManager(
		ctx,
		"https://auth.example.com/oauth/v2/token",
		"client-id",
		"client-secret",
		"openid",
	)

	transport := httpclient.NewOAuth2Transport(tm, nil)

	fmt.Printf("Transport type: OAuth2Transport\n")
	_ = transport
}
Output:
Transport type: OAuth2Transport

func (*OAuth2Transport) RoundTrip

func (t *OAuth2Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper interface. It fetches a valid OAuth2 token and adds it as "Authorization: Bearer <token>" to the request headers before delegating to the base transport. The token fetch respects the request context's cancellation and deadline.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL