config

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MTLSModeRequired = "required" // Rejects connections without a valid certificate
	MTLSModeOptional = "optional" // Validates a certificate if one is sent but also accepts connections without one
	MTLSModeDisabled = "disabled" // Doesn't ask for a certificate
)

How the server handles client certificates

View Source
const (
	CacheVisibilityPublic  = "public"
	CacheVisibilityPrivate = "private"
)
View Source
const (
	ModeErrorPlainText   = "text"         // Response will be text/plain with the error message in the body
	ModeErrorNoError     = "none"         // Response will not include any data but will return status code.
	ModeErrorImage       = "image"        // Response will return an image but not the error itself
	ModeErrorImageHeader = "image+header" // Response will return an image and include the error inside x-error-message
)

Error reporting modes

View Source
const (
	AccessFormatCommon   = "common"
	AccessFormatCombined = "combined"
)

Access log formats

View Source
const (
	MainFormatPlain = "plain"
	MainFormatJSON  = "json"
)

Main log formats

View Source
const (
	AuditFormatPlain = "plain"
	AuditFormatJSON  = "json"
)

Audit log formats

View Source
const LevelAbsurd slog.Level = slog.LevelDebug - 10
View Source
const LevelTrace slog.Level = slog.LevelDebug - 5

Variables

This section is empty.

Functions

This section is empty.

Types

type AccessConfig

type AccessConfig struct {
	Console bool   // If true, write access logs to standard out. Defaults to true
	Path    string // The file location to write logs to. Log rotation is not built-in, use an external tool to avoid excessive growth. Defaults to none
	Format  string // The format to output access logs in. Applies to both standard out and file out. Possible values: common, combined. Defaults to common
}

type AuditConfig added in v0.12.0

type AuditConfig struct {
	Enabled bool     // If true, emit audit events. Defaults to false
	Console bool     // If true, write audit events to standard out. Defaults to true
	Path    string   // The file location to write audit events to. Log rotation is not built-in, use an external tool to avoid excessive growth. Defaults to none
	Format  string   // The format to output audit events in. Applies to both standard out and file out. Possible values: plain, json. Defaults to json
	Headers []string // Headers to include as attributes on audit events. Useful for a transaction/request/trace/correlation ID
}

Security relevant events: authentication and authorization failures, rate limit rejections, and configuration reloads

type BoundsConfig added in v0.11.0

type BoundsConfig struct {
	South float64
	North float64
	West  float64
	East  float64
}

type CORSConfig added in v0.12.0

type CORSConfig struct {
	Enabled          bool     // If true, apply CORS headers and answer preflight requests
	WildcardOrigin   bool     // If true, return Access-Control-Allow-Origin: * and ignore Origins
	Origins          []string // Origins to allow, optionally including scheme and port. The host may use * to match one subdomain or ** to match several. The request Origin is echoed back when it matches
	Methods          []string // Methods to report in preflight responses. Defaults to GET, HEAD, OPTIONS
	Headers          []string // Request headers to allow in preflight responses. A single entry of * echoes back whatever the browser asks for. Defaults to none
	ExposedHeaders   []string // Response headers to make readable to browser scripts. Defaults to ETag
	AllowCredentials bool     // If true, allow credentialed requests. Cannot be combined with WildcardOrigin
	MaxAge           uint     // How long (in seconds) a browser may cache a preflight response. Defaults to 0 which omits the header
}

type CacheControlConfig added in v0.12.0

type CacheControlConfig struct {
	Enabled              *bool    // If true, return a Cache-Control header on tile responses. Defaults false
	Auto                 *bool    // If false, don't derive any directive from the layer's configuration. Defaults true
	MaxAge               *uint    // How long (in seconds) a browser may reuse a tile. Returned as max-age. Replaces the derived remaining lifetime
	SharedMaxAge         *uint    // How long (in seconds) a shared cache may reuse a tile. Returned as s-maxage. Never derived
	StaleWhileRevalidate *uint    // How long (in seconds) a cache may serve an expired tile while revalidating. Returned as stale-while-revalidate. Never derived
	Visibility           string   // Either public or private. Replaces the derived visibility
	NoStore              *bool    // If true, return no-store alone. Cannot be combined with the other fields
	Extra                []string // Additional directives returned as-is. Always appended
}

type ClientConfig

type ClientConfig struct {
	UserAgent           string            // The user agent to include in outgoing http requests. Separate from Headers to avoid omitting this.
	MaxLength           int               // The maximum Content-Length to allow incoming responses. Default: 10 Megabytes
	UnknownLength       *bool             // If true, allow responses that are missing a Content-Length header. Default: false.
	ContentTypes        []string          // The content-types to allow servers to return. Anything else will be interpreted as an error
	StatusCodes         []int             // The status codes from the remote server to consider successful.  Defaults to just 200
	Headers             map[string]string // Include these headers in requests. Defaults to none
	Timeout             uint              // How long (in seconds) a request can be in flight before we cancel it and return an error
	RewriteContentTypes map[string]string // Replace ContentType's that match the key with the value. This is to handle servers returning a generic content type. Kicks in after the check that ContentType is in `ContentTypes`.
	TLS                 string            // The ID of the TLS profile used to validate remote servers. Defaults to system
	MTLS                string            // The ID of the TLS profile holding the certificate to present to remote servers
	EnableMTLS          *bool             // Whether to present a certificate to remote servers. Defaults to true if MTLS is set
}

type Config

type Config struct {
	Server           ServerConfig
	Health           HealthConfig
	Client           ClientConfig
	Logging          LogConfig
	Error            ErrorConfig
	Telemetry        TelemetryConfig
	Secret           map[string]interface{}
	Datastores       []map[string]interface{}
	TLS              []map[string]interface{} // Certificates, keys, and CAs referenced by ID from Client and Server.Encrypt
	Authentication   map[string]interface{}
	Cache            interface{} // Either a single cache or an array of caches.
	DefaultCache     string      // The id of the cache layers use when they don't specify one. Defaults to the first entry
	Analytics        map[string]interface{}
	RateLimit        map[string]interface{}
	DefaultRateLimit string // The ID of the rate limit policy layers use when they don't specify one. Defaults to the first policy
	Layers           []LayerConfig
}

func DefaultConfig

func DefaultConfig() Config

type DataType added in v0.11.0

type DataType string
const (
	DataTypeRaster  DataType = "raster"
	DataTypeMVT     DataType = "mvt"
	DataTypeMLT     DataType = "mlt"
	DataTypeUnknown DataType = "unknown"
)

type EncryptionConfig

type EncryptionConfig struct {
	TLS         string // The ID of the TLS profile supplying the certificate served to clients. Required
	MTLS        string // The ID of the TLS profile holding the CA used to validate client certificates
	MTLSMode    string // How client certificates are handled. Defaults to required if MTLS is set, otherwise disabled
	Domain      string // Deprecated: use a TLS profile with Hosts
	Cache       string // Deprecated: use an acme TLS profile with Cache
	Certificate string // Deprecated: use a pem TLS profile with CertificateFile
	KeyFile     string // Deprecated: use a pem TLS profile with KeyFile
	HTTPPort    int    // The port used for non-encrypted traffic. Required if using Let's Encrypt for ACME challenge and needs to indirectly be 80 (that is, it could be 8080 if something else redirects 80 to 8080). Everything except .well-known will be redirected to the main port when set.
}

TLS is enabled when configured, using a TLS profile

type ErrorConfig

type ErrorConfig struct {
	Mode     string        // How errors should be returned.  See the consts above for options
	Messages ErrorMessages // Patterns to use for error messages in logs and responses. Not used for utility commands.
	Images   ErrorImages   // Only used if Mode is image or image+header
	AlwaysOK bool          // If set we always return 200 regardless of what happens
}

type ErrorImages

type ErrorImages struct {
	OutOfBounds    string // A request for a zoom level or tile coordinate that's invalid for the requested layer
	Authentication string // Auth failed. Always PNG, see above.
	RateLimited    string // A rate limit rejected the request
	Provider       string // Provider specific errors
	Other          string // Catch-all for unexpected system errors

	OutOfBoundsMvt string // Vector-tile equivalent of OutOfBounds, used when the layer's data type is mvt
	RateLimitedMvt string // Vector-tile equivalent of RateLimited, used when the layer's data type is mvt
	ProviderMvt    string // Vector-tile equivalent of Provider, used when the layer's data type is mvt
	OtherMvt       string // Vector-tile equivalent of Other, used when the layer's data type is mvt

	OutOfBoundsMlt string // MapLibre Tile equivalent of OutOfBounds, used when the layer's data type is mlt
	RateLimitedMlt string // MapLibre Tile equivalent of RateLimited, used when the layer's data type is mlt
	ProviderMlt    string // MapLibre Tile equivalent of Provider, used when the layer's data type is mlt
	OtherMlt       string // MapLibre Tile equivalent of Other, used when the layer's data type is mlt
}

Images returned for various errors. Either embedded:XXX from internal/images or a path on the runtime filesystem

type ErrorMessages

type ErrorMessages struct {
	NotAuthorized           string
	ParamRequired           string
	InvalidParam            string
	RangeError              string
	ServerError             string
	ProviderError           string
	ParamsBothOrNeither     string
	ParamsMutuallyExclusive string
	ParamRequiresParam      string
	OneOfRequired           string
	EnumError               string
	ScriptError             string
	Timeout                 string
	ParamRegex              string
	MustBeUnique            string
	TileNotFound            string
	RateLimited             string
}

A poor-man's i18n that also avoids magic strings. Could become static constants if nobody uses it

type ForwardedConfig added in v0.14.0

type ForwardedConfig struct {
	Trusted []string               // IPs or CIDR ranges of proxies whose forwarding headers are believed. Defaults to private, loopback, and link-local ranges
	Headers ForwardedHeadersConfig // Which headers to read from a trusted proxy
	Depth   uint                   // How many proxies set or append the Host, Proto, Port, and Prefix headers. Defaults to 1
}

type ForwardedHeadersConfig added in v0.14.0

type ForwardedHeadersConfig struct {
	For    string // The client IP. Defaults to X-Forwarded-For
	Host   string // The host the client requested. Defaults to X-Forwarded-Host
	Proto  string // Either http or https. Defaults to X-Forwarded-Proto
	Port   string // Ignored when the host includes a port. Defaults to X-Forwarded-Port
	Prefix string // The path tilegroxy is served under. Defaults to X-Forwarded-Prefix
}

The headers trusted proxies report the original request in

type HealthConfig added in v0.8.0

type HealthConfig struct {
	Enabled bool             // If set to false the port isn't bound to. Defaults false
	Port    int              // The port to serve health on. Defaults to 3000
	Host    string           // The host to bind to. Defaults to 0.0.0.0
	Checks  []map[string]any // An array defining the specific checks to perform.
}

type LayerConfig

type LayerConfig struct {
	ID             string                     // A distinct identifier for this layer. If no pattern is defined this is used to match against the layer name. Also used
	Pattern        string                     // A pattern to match against for layer names in incoming requests. Includes placeholders from which values can be extracted when matching. Not regular expressions, placeholders are simply wrapped in curly braces
	ParamValidator map[string]string          // A mapping of regular expressions to use for each value extracted from the pattern. Keys must match the placeholders in pattern. This is external from the pattern itself to keep parsing the pattern simple and less error prone. If a key of "*" is defined it applies to all placeholders
	ParamMap       map[string][]ParamMapEntry // Optional. Rewrites placeholder values before providers see them. Unlisted values don't match unless a default entry exists
	Provider       map[string]any             // Raw config parameters for the provider to use. Name determines the specific schema
	SkipCache      bool                       // If true, don't use the cache
	SkipAnalytics  bool                       // If true, successful requests for this layer don't produce analytics events
	RateLimit      string                     // Optional. The ID of the rate limit policy for this layer instead of the default
	SkipRateLimit  bool                       // If true, requests for this layer are never checked against or counted by a rate limit
	Client         *ClientConfig              // If specified, the default Client is overridden.
	LayerMetadata  `mapstructure:",squash" yaml:",inline"`
	Examples       []string            // Optional. Concrete layer names used to generate TileJSON documents for a `pattern` layer. Has no effect on a layer identified by a plain id
	CacheVersion   string              // Optional. Allows invalidating cache entries when changed. Prefixed into cache keys but not he actual layer name
	Cache          string              // Optional. The id of a top-level cache to use instead of the default
	AllowCoalesce  *bool               // Optional. Whether two requests that come in at the same time for the same tile should be combined. Defaults to auto, which is determined by whether caching is enabled
	CacheControl   *CacheControlConfig // Optional. Overrides the server's Cache-Control block field by field for this layer
}

type LayerMetadata added in v0.13.0

type LayerMetadata struct {
	DataType         DataType     // Optional. Declares this layer's data type. Must not contradict the type the provider reports; required if Bounds is set and the provider's type is unknown
	MinZoom          *int         // Optional. Requests below this zoom are rejected as out of bounds. nil means no lower limit
	MaxZoom          *int         // Optional. Requests above this zoom are rejected as out of bounds. nil means no upper limit
	Bounds           BoundsConfig // Optional. Wraps this layer's provider in crop/cropmvt, restricting it to this geographic area
	TileJSONMetadata `mapstructure:",squash" yaml:",inline"`
}

A layer's tiles as configured by the operator. Zoom and bounds are enforced, the rest overrides what the provider reports

type LogConfig

type LogConfig struct {
	Access AccessConfig
	Main   MainConfig
	Audit  AuditConfig
}

type MainConfig

type MainConfig struct {
	Console bool     // If true, write access logs to standard out. Defaults to true
	Path    string   // The file location to write logs to. Log rotation is not built-in, use an external tool to avoid excessive growth. Defaults to none
	Format  string   // The format to output access logs in. Applies to both standard out and file out. Possible values: plain, json. Defaults to plain
	Level   string   // logging level. one of: debug, info, warn, error, trace, absurd
	Request string   // Can be "true", "false" or "auto". If false, don't include any extra attributes based on request parameters (excluding the ones requested below). If auto (default) it defaults true if format is json, false otherwise
	Headers []string // Headers to include in the logs. Useful for a transaction/request/trace/correlation ID or user identifiers
}

type ParamMapEntry added in v0.15.0

type ParamMapEntry struct {
	From    string // A value accepted from the incoming layer name
	To      string // The value providers see in its place. On a default entry, leave empty to pass the value through unchanged
	Default bool   // If true, applies to every value no other entry lists. Only one per placeholder and it must not have From
}

type ServerConfig

type ServerConfig struct {
	Encrypt      *EncryptionConfig  // Whether and how to use TLS. Defaults to none AKA no encryption.
	TileJSON     TileJSONConfig     // Whether to enable endpoints that describe layers using the TileJSON format
	CORS         CORSConfig         // Whether and how to return cross-origin resource sharing headers
	CacheControl CacheControlConfig // Whether and how to return a Cache-Control header on tile responses
	Forwarded    ForwardedConfig    // Which proxies in front of tilegroxy to trust for the client IP, host, protocol, and port
	BindHost     string             // IP address to bind HTTP server to
	Port         int                // Port to bind HTTP server to
	RootPath     string             // Root HTTP Path to apply to all endpoints. Defaults to /
	TilePath     string             // HTTP Path to serve tiles under (in addition to RootPath). Defaults to tiles which means /tiles/{layer}/{z}/{x}/{y}.
	DocsPath     string             // HTTP Path for accessing the documentation website. Defaults to docs
	Headers      map[string]string  // Include these headers in all response from server
	Production   bool               // Controls serving splash page, documentation, x-powered-by header. Defaults to true, set false to expose them outside prod
	Timeout      uint               // How long (in seconds) a request can be in flight before we cancel it and return an error
	Gzip         bool               // Whether to apply gzip compression. Not super helpful when just serving up raster images

	ShutdownTimeout uint // How long (in seconds) the whole shutdown sequence gets. Defaults to Timeout plus DrainDelay.
	DrainDelay      uint // How long (in seconds) to report unready before draining. Defaults to 5, set 0 when a preStop hook covers it.
}

type TelemetryConfig added in v0.6.0

type TelemetryConfig struct {
	Enabled bool
}

type TileJSONConfig added in v0.11.0

type TileJSONConfig struct {
	Enabled   bool     // If true, serve TileJSON documents for eligible layers. Defaults false
	IndexPath string   // The HTTP path, relative to RootPath, that serves a TileJSON index listing every eligible layer. Defaults to tilejson.json
	BaseURLs  []string // Overrides the scheme, host, and path prefix used to build the `tiles` URLs in a document, instead of reading it from forwarding headers or the request itself. Each entry produces one URL in the `tiles` array
}

TileJSON documents describing configured layers

type TileJSONMetadata added in v0.13.0

type TileJSONMetadata struct {
	Description  string        `json:"description,omitempty"`   // Optional. Populates the `description` field
	Attribution  string        `json:"attribution,omitempty"`   // Optional. Populates the `attribution` field
	Version      string        `json:"version,omitempty"`       // Optional. Populates the `version` field
	Center       []float64     `json:"center,omitempty"`        // Optional. Populates the `center` field as longitude, latitude, zoom
	VectorLayers []VectorLayer `json:"vector_layers,omitempty"` // Optional. Populates the `vector_layers` field, describing the source layers in vector tiles
}

Copied as-is into a layer's TileJSON document. No effect unless TileJSON is enabled

type VectorLayer added in v0.13.0

type VectorLayer struct {
	ID          string            `json:"id"`
	Fields      map[string]string `json:"fields"`
	Description string            `json:"description,omitempty"`
	MinZoom     *int              `json:"minzoom,omitempty"`
	MaxZoom     *int              `json:"maxzoom,omitempty"`
}

Per the TileJSON 3.0.0 vector_layers entry

func (VectorLayer) MarshalJSON added in v0.13.0

func (v VectorLayer) MarshalJSON() ([]byte, error)

The spec requires fields to be an object, so nil is written as {} rather than null

Jump to

Keyboard shortcuts

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