portaproxy

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2025 License: Apache-2.0 Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Portaproxy

portaproxy is a Go package providing a straightforward, manager-centric API for controlling TCP/HTTP reverse proxies. It allows developers to programmatically manage multiple proxy instances, their backend targets, and their lifecycle, making it ideal for dynamic environments and blue-green deployment strategies.

Features

  • Manager-centric API: A single Manager instance controls all proxy operations.
  • Port-based Proxy Identification: Each proxy is identified and managed by its public-facing listener port.
  • Backend Slots: Supports multiple named backend configurations ("slots") per proxy, enabling flexible deployment strategies (blue-green, canary, etc.).
  • Atomic Switching: Instantly switch live traffic between named backend slots with zero downtime for new connections.
  • Round-Robin Load Balancing: Distributes requests evenly among healthy backends in the active slot.
  • Configurable Health Checks: Periodically checks backend health and automatically removes/adds unhealthy/healthy backends from rotation.
  • Configurable Timeouts: Fine-grained control over client and backend connection timeouts.
  • Structured Logging: Integrates with log/slog for clear, structured output.
  • Custom Backend Transport: Allows advanced users to provide a custom http.RoundTripper for backend communication.
  • Graceful Shutdown: Proxies shut down gracefully, allowing in-flight requests to complete.

Installation

To use portaproxy in your Go project, simply run:

go get codeberg.org/ess/portaproxy

Usage

Basic Example
package main

import (
    "log/slog"
    "os"
    "time"

    "codeberg.org/ess/portaproxy"
)

func main() {
    // 1. Setup logger
    logger := slog.New(slog.NewTextHandler(os.Stdout, nil))

    // 2. Create and configure the proxy manager
    defaultConfig := &portaproxy.ProxyConfig{
        HealthCheckPath:     "/healthz",
        HealthCheckInterval: 5 * time.Second,
        UnhealthyThreshold:  2,
        HealthyThreshold:    2,
        BackendDialTimeout:  2 * time.Second,
    }
    mgr := portaproxy.New(logger, defaultConfig)

    // 3. Start the proxy on port 8080
    logger.Info("Starting proxy", "port", 8080)
    if err := mgr.Start(8080, nil); err != nil {
        logger.Error("Failed to start proxy", "error", err)
        os.Exit(1)
    }

    // 4. Define the initial 'blue' environment and make it active
    blueBackends := []string{"http://localhost:9001", "http://localhost:9002"} // Assuming backends are running
    mgr.SetBackends(8080, "blue", blueBackends)
    mgr.Switch(8080, "blue")
    logger.Info("Proxy configured", "slot", "blue", "backends", blueBackends)

    // ... application runs ...

    // 5. Later, define a 'green' environment and switch to it
    greenBackends := []string{"http://localhost:9003", "http://localhost:9004"}
    mgr.SetBackends(8080, "green", greenBackends)
    mgr.Switch(8080, "green")
    logger.Info("Switched to green", "slot", "green", "backends", greenBackends)

    // 6. Get active slot and backend status
    active, _ := mgr.GetActive(8080)
    statuses, _ := mgr.BackendStatus(8080, active)
    logger.Info("Current status", "active_slot", active, "backends", statuses)

    // 7. Stop the proxy
    logger.Info("Stopping proxy", "port", 8080)
    if err := mgr.Stop(8080); err != nil {
        logger.Error("Failed to stop proxy", "error", err)
    }
}

API Overview

Types
  • type ProxyConfig struct
    • Holds configuration for a proxy's behavior, including health checks and timeouts.
  • type BackendStatus struct
    • Represents the health and URL of a single backend, returned by Manager.BackendStatus.
Functions
  • func New(logger *slog.Logger, defaultConfig *ProxyConfig) *Manager
    • Creates a new Manager instance.
    • logger: For structured logging. If nil, logs are discarded.
    • defaultConfig: Default ProxyConfig for all proxies managed by this Manager. Can be overridden per-proxy.
Methods on *Manager
  • func (m *Manager) Start(port int, overrideConfig *ProxyConfig) error
    • Creates and starts a new reverse proxy on port.
    • overrideConfig: Optional config to override defaultConfig.
  • func (m *Manager) Stop(port int) error
    • Gracefully halts the proxy on port, stopping health checks and shutting down the HTTP server.
  • func (m *Manager) SetBackends(port int, name string, backends []string) error
    • Defines or updates a named slot with a list of backend URLs. Thread-safe.
  • func (m *Manager) AddBackend(port int, name string, backendURL string) error
    • Adds a single backend URL to a named slot. Creates the slot if it doesn't exist. Thread-safe.
  • func (m *Manager) RemoveBackend(port int, name string, backendURL string) error
    • Removes a single backend URL from a named slot. Thread-safe.
  • func (m *Manager) DeleteBackends(port int, name string) error
    • Removes a named slot and all its backends. If active, the proxy will have no active slot and may return errors to clients until a new slot is activated via Switch.
  • func (m *Manager) GetBackends(port int, name string) ([]string, error)
    • Returns the list of backend URLs for a given slot.
  • func (m *Manager) GetSlots(port int) ([]string, error)
    • Returns the names of all configured slots for a given port.
  • func (m *Manager) BackendStatus(port int, name string) ([]BackendStatus, error)
    • Returns the health status of all backends in a given slot.
  • func (m *Manager) Switch(port int, name string) error
    • Atomically sets the named slot as the active one for the proxy.
  • func (m *Manager) GetActive(port int) (string, error)
    • Returns the name of the currently active slot.
Errors
  • var ErrProxyExists error
  • var ErrProxyNotFound error
  • var ErrSlotNotFound error
  • var ErrInvalidURL error
  • var ErrNoActiveSlot error

License

portaproxy is licensed under the Apache License 2.0.

Contributing

We use the Git Flow branching model for this project.

  • All feature branches should be created off the develop branch.
  • Pull Requests should target the develop branch for merging.

Contributions are welcome! Please open an issue or submit a pull request.

History

  • v1.0.2 (2025-10-22) - Normalized backend URLs
  • v1.0.1 (2025-10-22) - Request path fixes
  • v1.0.0 (2025-10-21) - Initial public release

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrProxyExists is returned when trying to start a proxy on a port that is already in use.
	ErrProxyExists = errors.New("proxy already exists on this port")
	// ErrProxyNotFound is returned when an operation is attempted on a proxy that does not exist.
	ErrProxyNotFound = errors.New("proxy not found")
	// ErrSlotNotFound is returned when an operation is attempted on a slot that does not exist.
	ErrSlotNotFound = errors.New("slot not found")
	// ErrInvalidURL is returned when a backend URL is malformed.
	ErrInvalidURL = errors.New("invalid backend URL")
	// ErrNoActiveSlot is returned when a request is made to a proxy with no active slot.
	ErrNoActiveSlot = errors.New("no active slot")
)

Functions

This section is empty.

Types

type BackendStatus

type BackendStatus struct {
	// URL is the URL of the backend server.
	URL string
	// Healthy is true if the backend is currently passing health checks.
	Healthy bool
}

BackendStatus represents the health and URL of a single backend. This struct is returned by the Manager's BackendStatus method.

type Manager

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

Manager is the central component for managing reverse proxies. It holds the configuration and state for all running proxies. A Manager should be created using the New function.

func New

func New(logger *slog.Logger, defaultConfig *ProxyConfig) *Manager

New creates a new Manager instance. It takes a logger for structured logging and a defaultConfig that will be applied to all proxies started by this manager. If logger is nil, logs will be discarded. The defaultConfig can be overridden on a per-proxy basis in the Start method.

func (*Manager) AddBackend

func (m *Manager) AddBackend(port int, name string, backendURL string) error

AddBackend adds a single backend URL to a named slot. If the slot does not exist, it will be created. This operation is thread-safe.

func (*Manager) BackendStatus

func (m *Manager) BackendStatus(port int, name string) ([]BackendStatus, error)

BackendStatus returns the health status of all backends in a given slot.

func (*Manager) DeleteBackends

func (m *Manager) DeleteBackends(port int, name string) error

DeleteBackends removes a named slot and all its backends from the proxy. If the slot was active, the proxy will have no active slot and may return errors to clients until a new slot is activated via Switch.

func (*Manager) GetActive

func (m *Manager) GetActive(port int) (string, error)

GetActive returns the name of the currently active slot.

func (*Manager) GetBackends

func (m *Manager) GetBackends(port int, name string) ([]string, error)

GetBackends returns the list of backend URLs for a given slot.

func (*Manager) GetSlots

func (m *Manager) GetSlots(port int) ([]string, error)

GetSlots returns the names of all configured slots for a given port.

func (*Manager) RemoveBackend

func (m *Manager) RemoveBackend(port int, name string, backendURL string) error

RemoveBackend removes a single backend URL from a named slot. This operation is thread-safe.

func (*Manager) SetBackends

func (m *Manager) SetBackends(port int, name string, backends []string) error

SetBackends defines or updates a named slot with a list of backend URLs. This operation is thread-safe. If the slot is currently active, the proxy will immediately begin using the new backends. The health of new backends is assumed to be true until the next health check cycle.

func (*Manager) Start

func (m *Manager) Start(port int, overrideConfig *ProxyConfig) error

Start creates and starts a new reverse proxy on the specified port. It launches the proxy's HTTP server in a background goroutine. An optional overrideConfig can be provided to use settings different from the default config provided in the New() function. If overrideConfig is nil, the defaults are used.

func (*Manager) Stop

func (m *Manager) Stop(port int) error

Stop gracefully halts the proxy running on the specified port. It stops the health checker and shuts down the HTTP server, waiting for active connections to drain.

func (*Manager) Switch

func (m *Manager) Switch(port int, name string) error

Switch atomically sets the named slot as the active one for the proxy. All new incoming requests will be routed to the backends in this slot.

type ProxyConfig

type ProxyConfig struct {
	// HealthCheckPath is the HTTP path that will be requested to determine a backend's health.
	// If this path is empty, health checks will be disabled.
	HealthCheckPath string
	// HealthCheckInterval is the time between health checks of a backend.
	HealthCheckInterval time.Duration
	// UnhealthyThreshold is the number of consecutive failed health checks required to mark a backend as unhealthy.
	UnhealthyThreshold int
	// HealthyThreshold is the number of consecutive successful health checks required to mark an unhealthy backend as healthy again.
	HealthyThreshold int

	// ClientReadTimeout is the maximum duration for reading the entire request from a client, including the body.
	ClientReadTimeout time.Duration
	// ClientWriteTimeout is the maximum duration before timing out writes of the response to the client.
	ClientWriteTimeout time.Duration
	// ClientIdleTimeout is the maximum amount of time to wait for the next request when keep-alives are enabled.
	ClientIdleTimeout time.Duration
	// BackendDialTimeout is the maximum duration for establishing a connection to a backend server.
	BackendDialTimeout time.Duration

	// BackendTransport allows for custom HTTP transport to backend servers.
	// If nil, http.DefaultTransport is used.
	BackendTransport http.RoundTripper
}

ProxyConfig holds the configuration for a proxy's behavior. It defines settings for health checks and timeouts.

Directories

Path Synopsis
cmd
example-usage command

Jump to

Keyboard shortcuts

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