proxy

package
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

Package proxy provides HTTP/HTTPS reverse proxy functionality.

It handles:

  • Dynamic routing based on hostname and path
  • TLS termination with auto-generated certificates
  • Real-time dashboard with Server-Sent Events (SSE)
  • Health check and status endpoints

Index

Constants

View Source
const (
	LeaseErrorInvalid  = "invalid"  // The request cannot be honored as written
	LeaseErrorDeclared = "declared" // The config file declares the hostname
	LeaseErrorHeld     = "held"     // Another `roji run` holds the hostname
)

Lease error codes, for a client to choose its own wording by.

View Source
const (
	KindDocker = "docker" // A container discovered on a watched network
	KindStatic = "static" // A directory declared under static_sites
	KindLocal  = "local"  // A server on the host declared under proxy_sites
)

Route kinds, as reported in RouteInfo.Kind.

View Source
const LeasePath = "/_api/leases"

LeasePath is the API endpoint `roji run` registers and gives back routes on.

View Source
const LeaseTTL = 30 * time.Second

LeaseTTL is how long a leased route lasts without being renewed.

`roji run` renews well inside it. What it bounds is how long a route outlives a `roji run` that was killed before it could give the route back.

Variables

View Source
var (
	// ErrLeaseDeclared: the config file declares the hostname. It was written
	// down deliberately, so a command started later does not take it over.
	ErrLeaseDeclared = errors.New("hostname is declared in the config file")
	// ErrLeaseHeld: another `roji run` holds the hostname and is still renewing it.
	ErrLeaseHeld = errors.New("hostname is held by another roji run")
)

Reasons a hostname cannot be leased.

Functions

func ServeStaticFile added in v0.9.0

func ServeStaticFile(w http.ResponseWriter, r *http.Request, root string, enableIndex bool, dashboardHost string)

ServeStaticFile serves a static file from the given root directory

Types

type BuildInfo added in v0.4.0

type BuildInfo struct {
	Version string `json:"version"`
	Commit  string `json:"commit"`
	Date    string `json:"date"`
	BuiltBy string `json:"built_by"`
}

BuildInfo contains build metadata

type CertInfo

type CertInfo struct {
	Exists        bool       `json:"exists"`
	ValidUntil    *time.Time `json:"valid_until,omitempty"`
	DaysRemaining *int       `json:"days_remaining,omitempty"`
	Subject       string     `json:"subject,omitempty"`
	DNSNames      []string   `json:"dns_names,omitempty"` // server cert only
}

CertInfo contains details about a specific certificate

type CertificateStatus

type CertificateStatus struct {
	AutoGenerated bool      `json:"auto_generated"`
	Directory     string    `json:"directory"`
	CA            *CertInfo `json:"ca"`
	Server        *CertInfo `json:"server"`
}

CertificateStatus contains information about TLS certificates

type ConfigReload added in v1.4.0

type ConfigReload struct {
	// ConfigPath is the file that was read: the one roji was started with,
	// which need not be the one whoever asked for the reload has been editing.
	ConfigPath string `json:"configPath"`

	// Sites lists every site the config file declares, in the order written.
	// A roji from before this field existed leaves it out.
	Sites []ReloadedSite `json:"sites"`
}

ConfigReload is what a config reload did.

type ConfigReloadFunc added in v0.9.0

type ConfigReloadFunc func() (ConfigReload, error)

ConfigReloadFunc is a callback function to reload configuration.

type ConfigReloadResponse added in v1.4.0

type ConfigReloadResponse struct {
	Status string `json:"status"` // Always "reloaded"

	// Domain is the base domain the sites were judged against. It is the
	// running roji's, which a config file edited since it started may no
	// longer agree with.
	Domain string `json:"domain"`

	ConfigReload
}

ConfigReloadResponse is the body of a successful /_api/config/reload.

type DirectoryEntry added in v0.9.0

type DirectoryEntry struct {
	Name    string
	IsDir   bool
	Size    int64
	ModTime string
	Icon    string
}

DirectoryEntry represents a file or directory in a listing

type DockerStatus

type DockerStatus struct {
	Connected  bool     `json:"connected"`
	Networks   []string `json:"networks"`
	APIVersion string   `json:"api_version,omitempty"`
}

DockerStatus contains Docker connection information

type Handler

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

Handler is the main HTTP handler for the reverse proxy

func NewHandler

func NewHandler(router *Router, dockerClient *docker.Client, dashboardHost string, baseDomain string, statusConfig *StatusConfig, projectStore *project.Store) *Handler

NewHandler creates a new proxy handler

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler

func (*Handler) SetConfigReloader added in v0.9.0

func (h *Handler) SetConfigReloader(fn ConfigReloadFunc)

SetConfigReloader sets the callback function for reloading configuration

type LeaseError added in v1.4.0

type LeaseError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

LeaseError is the body of a refused lease request.

type LeaseRequest added in v1.4.0

type LeaseRequest struct {
	// Host is the name as the user gave it, resolved like a site in the config
	// file: "web" becomes "web.{domain}".
	Host string `json:"host"`

	// Port is where the dev server listens. A port and not a URL: the target is
	// always this machine, so the endpoint cannot be made to point a hostname
	// at anything else.
	Port int `json:"port"`

	// Owner identifies the `roji run` asking, so that only it renews or gives
	// back what it registered.
	Owner string `json:"owner"`
}

LeaseRequest asks for a hostname to be routed to a port on this machine.

type LeaseResponse added in v1.4.0

type LeaseResponse struct {
	Hostname string `json:"hostname"`
	URL      string `json:"url"`

	// CertCovered is false when roji's certificate is not valid for the
	// hostname, which a browser will refuse.
	CertCovered bool `json:"certCovered"`

	// Hides names the Docker service that was answering on the hostname and no
	// longer does, empty when there is none.
	Hides string `json:"hides,omitempty"`
}

LeaseResponse describes a route that was leased or renewed.

type LocalBackend added in v1.4.0

type LocalBackend struct {
	Target    *url.URL          // Where the server listens, e.g. http://127.0.0.1:8787
	BasicAuth *config.BasicAuth // Basic authentication (optional)
	Tunnel    bool              // Published through the tunnel

	// Temporary marks a route `roji run` leased rather than one the config
	// file declares: it goes away when the command does.
	Temporary bool
}

LocalBackend is a server already listening on the host, such as a dev server started outside Docker, that the config file gives a hostname to.

type LogBuffer added in v0.6.0

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

LogBuffer is a thread-safe ring buffer for request logs

func NewLogBuffer added in v0.6.0

func NewLogBuffer(capacity int) *LogBuffer

NewLogBuffer creates a new log buffer with the specified capacity

func (*LogBuffer) Add added in v0.6.0

func (lb *LogBuffer) Add(log RequestLog)

Add adds a new log entry to the buffer

func (*LogBuffer) Clear added in v0.6.0

func (lb *LogBuffer) Clear()

Clear removes all logs from the buffer

func (*LogBuffer) List added in v0.6.0

func (lb *LogBuffer) List() []RequestLog

List returns all logs in the buffer (oldest first)

func (*LogBuffer) ListFiltered added in v0.7.0

func (lb *LogBuffer) ListFiltered(filter LogFilter) []RequestLog

ListFiltered returns logs matching the filter criteria

func (*LogBuffer) ListRecent added in v0.6.0

func (lb *LogBuffer) ListRecent(n int) []RequestLog

ListRecent returns the most recent n logs (newest first)

func (*LogBuffer) Subscribe added in v0.6.0

func (lb *LogBuffer) Subscribe() (chan RequestLog, func())

Subscribe creates a channel that receives new log entries

func (*LogBuffer) SubscriberCount added in v0.6.0

func (lb *LogBuffer) SubscriberCount() int

SubscriberCount returns the number of active subscribers

type LogFilter added in v0.7.0

type LogFilter struct {
	From    time.Time // Start time (inclusive)
	To      time.Time // End time (inclusive)
	Service string    // Filter by service name
	Host    string    // Filter by host
	Method  string    // Filter by HTTP method
}

LogFilter defines criteria for filtering logs

type ProxyStatus

type ProxyStatus struct {
	RoutesCount    int    `json:"routes_count"`
	DashboardHost  string `json:"dashboard_host"`
	BaseDomain     string `json:"base_domain"`
	HTTPPort       int    `json:"http_port"`
	HTTPSPort      int    `json:"https_port"`
	SSESubscribers int    `json:"sse_subscribers"`
}

ProxyStatus contains proxy configuration and state

type RedirectHandler

type RedirectHandler struct {
	HTTPSPort int
}

RedirectHandler redirects HTTP to HTTPS

func (*RedirectHandler) ServeHTTP

func (h *RedirectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler for HTTP->HTTPS redirect

type ReloadedSite added in v1.4.0

type ReloadedSite struct {
	Hostname string `json:"hostname"`
	Kind     string `json:"kind"` // KindStatic or KindLocal

	// Target is the static site's root or the proxy site's target: see
	// config.DeclaredSite.Where.
	Target string `json:"target"`

	// Skipped is one of config's SiteSkip codes when the site was not
	// registered, and empty when it was. Detail then says why, in English. A
	// client meeting a code it does not know has Detail to show.
	Skipped string `json:"skipped,omitempty"`
	Detail  string `json:"detail,omitempty"`

	// The site is registered and one of these will not work: browsers reject
	// the hostname, or the tunnel it asks for has no public name to give it.
	CertUncovered bool `json:"certUncovered,omitempty"`
	Unpublishable bool `json:"unpublishable,omitempty"`
}

ReloadedSite says what a config reload did with one site the config file declares. It is what `roji config reload` reports from: without it, a site that was left out shows up only in roji's own log, and the reload looks like it worked.

type RequestLog added in v0.6.0

type RequestLog struct {
	ID        int64     `json:"id"`
	Timestamp time.Time `json:"timestamp"`
	Method    string    `json:"method"`
	Host      string    `json:"host"`
	Path      string    `json:"path"`
	Status    int       `json:"status"`
	Duration  int64     `json:"duration_ms"` // milliseconds
	Service   string    `json:"service"`
	IsMock    bool      `json:"is_mock,omitempty"`
}

RequestLog represents a single request log entry

type Route

type Route struct {
	Hostname      string
	PathPrefix    string
	Backend       *docker.Backend
	StaticBackend *StaticBackend // A directory served from disk
	LocalBackend  *LocalBackend  // A server on the host
}

Route represents a single route configuration. Exactly one of the three backends is set.

func (*Route) BasicAuth added in v1.4.0

func (route *Route) BasicAuth() *config.BasicAuth

BasicAuth returns the credentials the route asks for, or nil for none.

func (*Route) Kind added in v1.4.0

func (route *Route) Kind() string

Kind names which backend the route has.

func (*Route) Published added in v1.4.0

func (route *Route) Published() bool

Published reports whether the route opted in to the tunnel: a Docker route with the roji.tunnel label, a declared one with its `tunnel` key. There is no other way in, so this is the one question the tunnel guard asks of a route.

func (*Route) ServiceName added in v1.4.0

func (route *Route) ServiceName() string

ServiceName is what the route is called in logs and listings. Declared routes have no service, so they go by their kind.

func (*Route) Temporary added in v1.4.0

func (route *Route) Temporary() bool

Temporary reports whether `roji run` leased the route, as opposed to the config file declaring it or Docker running it.

type RouteEvent added in v0.4.0

type RouteEvent struct {
	Type   string      `json:"type"`   // "routes"
	Routes []RouteInfo `json:"routes"` // Current route list
}

RouteEvent represents a route change event for SSE subscribers

type RouteInfo

type RouteInfo struct {
	// Kind is one of KindDocker, KindStatic and KindLocal. Which of the fields
	// below mean anything follows from it.
	Kind          string `json:"kind"`
	Hostname      string `json:"hostname"`
	PathPrefix    string `json:"pathPrefix,omitempty"`
	Target        string `json:"target"`
	ContainerID   string `json:"containerId,omitempty"`
	ContainerName string `json:"containerName,omitempty"`
	ServiceName   string `json:"serviceName"`
	ProjectName   string `json:"projectName,omitempty"`
	Warning       string `json:"warning,omitempty"`
	Network       string `json:"network,omitempty"`
	IndexEnabled  bool   `json:"indexEnabled,omitempty"` // For static sites: directory listing enabled
	Temporary     bool   `json:"temporary,omitempty"`    // For local routes: registered by `roji run`, gone when it exits
	HasBasicAuth  bool   `json:"hasBasicAuth,omitempty"` // Whether basic auth is enabled
	// TunnelURL is the address a route answers to from the internet, empty for
	// one that does not. It is the only spelling of "published": a route that
	// opted in while no tunnel is configured reaches nobody, and saying so twice
	// invites the two answers to disagree.
	TunnelURL string `json:"tunnelUrl,omitempty"`
}

RouteInfo is a display-friendly route representation

func (RouteInfo) String

func (ri RouteInfo) String() string

type Router

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

Router manages routes and provides thread-safe access

func NewRouter

func NewRouter() *Router

NewRouter creates a new route manager

func (*Router) AddBackend

func (r *Router) AddBackend(backend *docker.Backend)

AddBackend adds or updates a route for a backend

func (*Router) ExpireLeases added in v1.4.0

func (r *Router) ExpireLeases()

ExpireLeases removes the leases that have lapsed and tells subscribers when it removed any. Routing does not depend on it — see liveLease — but the dashboard does, since nothing else announces that a route is gone.

func (*Router) Lease added in v1.4.0

func (r *Router) Lease(hostname string, target *url.URL, owner string) (hidden *Route, err error)

Lease routes hostname to target on behalf of owner until LeaseTTL passes without another call. Calling again as the same owner renews the lease, and is how a lease held when roji restarted comes back.

It returns the Docker route the lease hides, if any, for the caller to tell whoever asked.

func (*Router) ListRoutes

func (r *Router) ListRoutes() []RouteInfo

ListRoutes returns all current routes for display

func (*Router) Lookup

func (r *Router) Lookup(hostname, path string) *Route

Lookup finds a Docker route for a given hostname and path. Use Resolve to find what actually serves a request.

func (*Router) LookupDeclared added in v1.4.0

func (r *Router) LookupDeclared(hostname string) *Route

LookupDeclared finds the route the config file declares for a hostname

func (*Router) Release added in v1.4.0

func (r *Router) Release(hostname, owner string)

Release gives up the lease owner holds on hostname. Anything else — no lease, or one that has since passed to another owner — is left alone, so a `roji run` exiting late cannot take down its successor's route.

func (*Router) RemoveBackend

func (r *Router) RemoveBackend(containerID string)

RemoveBackend removes routes for a container

func (*Router) RemoveProject

func (r *Router) RemoveProject(projectName string)

RemoveProject removes all routes for a given project

func (*Router) ReplaceDeclared added in v1.4.0

func (r *Router) ReplaceDeclared(routes []*Route)

ReplaceDeclared swaps the whole set of declared routes — those with a StaticBackend or a LocalBackend — for routes. It is the only way in: startup registers what the config file says and a reload registers what it says now. A declared route is keyed by hostname alone, so a PathPrefix on one is ignored.

One step rather than a clear followed by adds: in the gap between the two, a request for a declared hostname falls through to whatever Docker route the declaration was hiding.

func (*Router) Resolve added in v1.4.0

func (r *Router) Resolve(hostname, path string) *Route

Resolve finds the route that serves a hostname and path, which is the order of precedence in one place: a declared route owns its hostname outright, and only a hostname the config file does not name goes to the Docker routes.

func (*Router) RunLeaseExpiry added in v1.4.0

func (r *Router) RunLeaseExpiry(ctx context.Context, interval time.Duration)

RunLeaseExpiry calls ExpireLeases every interval until ctx is done.

func (*Router) SetTunnelDomains added in v1.2.0

func (r *Router) SetTunnelDomains(domains TunnelDomains)

SetTunnelDomains records the domain mapping so ListRoutes can name the public URL of each published route. Called once at startup, before serving.

func (*Router) Subscribe added in v0.4.0

func (r *Router) Subscribe(ctx context.Context) (<-chan RouteEvent, func())

Subscribe creates a new SSE subscriber and returns the event channel and cleanup function. The cleanup function must be called when the subscriber disconnects.

func (*Router) SubscriberCount added in v0.4.0

func (r *Router) SubscriberCount() int

SubscriberCount returns the number of active SSE subscribers

type StaticBackend added in v0.9.0

type StaticBackend struct {
	Root      string            // Absolute path to root directory
	Index     bool              // Enable directory listing
	BasicAuth *config.BasicAuth // Basic authentication (optional)
	Tunnel    bool              // Published through the tunnel
}

StaticBackend represents a static file hosting configuration

type StatusConfig

type StatusConfig struct {
	Version       string
	Commit        string
	Date          string
	BuiltBy       string
	StartTime     time.Time
	CertsDir      string
	AutoGenerated bool
	Networks      []string // Docker networks being watched
	BaseDomain    string
	HTTPPort      int
	HTTPSPort     int
}

StatusConfig contains configuration for the status endpoint

type StatusResponse

type StatusResponse struct {
	Build         BuildInfo         `json:"build"`
	UptimeSeconds int64             `json:"uptime_seconds"`
	Certificates  CertificateStatus `json:"certificates"`
	Docker        DockerStatus      `json:"docker"`
	Proxy         ProxyStatus       `json:"proxy"`
	Health        string            `json:"health"`
}

StatusResponse represents the overall status of roji

type Subscriber added in v0.4.0

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

Subscriber represents an SSE subscriber

type TunnelDomains added in v1.2.0

type TunnelDomains struct {
	Base   string // Local base domain, e.g. "dev.localhost"
	Public string // Cloudflare zone, e.g. "example.com"
}

TunnelDomains translates between the hostname a route answers to locally and the one it answers to from the internet.

The two differ only in their suffix: "web.dev.localhost" is published as "web.example.com". Keeping the local name as the routing key means the tunnel changes nothing about how routes are stored, matched, or shown.

func (TunnelDomains) Configured added in v1.2.0

func (d TunnelDomains) Configured() bool

Configured reports whether both halves of the mapping are known.

func (TunnelDomains) ToLocal added in v1.2.0

func (d TunnelDomains) ToLocal(public string) (string, bool)

ToLocal returns the local hostname a public one stands for.

func (TunnelDomains) ToPublic added in v1.2.0

func (d TunnelDomains) ToPublic(local string) (string, bool)

ToPublic returns the hostname a local route answers to from the internet.

type TunnelHandler added in v1.2.0

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

TunnelHandler guards the listener cloudflared connects to, and hands what survives to the ordinary proxy handler.

Everything roji serves locally is reachable without credentials, which is safe only because v1.1.0 made it listen on loopback alone. A tunnel undoes that for whatever it publishes, so this decides what "whatever" means:

  • the dashboard and its API are never published. `/_api/projects/{name}/up` starts containers and `/_api/logs` reads traffic, both unauthenticated
  • a route is published only if it says so: `roji.tunnel=true` on a container, `tunnel: true` on a site declared in the config file

cloudflared connects from 127.0.0.1 like any local browser, so no property of the request tells the two apart. The separate listener does, which is why the tunnel gets a port of its own rather than sharing the main one.

func NewTunnelHandler added in v1.2.0

func NewTunnelHandler(inner http.Handler, router *Router, domains TunnelDomains, dashboardHost string) *TunnelHandler

NewTunnelHandler wraps inner with the tunnel guard.

func (*TunnelHandler) ServeHTTP added in v1.2.0

func (h *TunnelHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

Jump to

Keyboard shortcuts

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