Documentation ¶
Index ¶
- Constants
- Variables
- func GetModuleID(instance interface{}) string
- func GetModuleName(instance interface{}) string
- func GoModule() *debug.Module
- func JoinNetworkAddress(network, host, port string) string
- func Listen(network, addr string) (net.Listener, error)
- func ListenPacket(network, addr string) (net.PacketConn, error)
- func Load(cfgJSON []byte, forceReload bool) error
- func Log() *zap.Logger
- func Modules() []string
- func RegisterModule(instance Module) error
- func Run(cfg *Config) error
- func SplitNetworkAddress(a string) (network, host, port string, err error)
- func Stop() error
- func TrapSignals()
- func Validate(cfg *Config) error
- type APIError
- type AdminConfig
- type AdminHandler
- type AdminHandlerFunc
- type AdminRoute
- type AdminRouter
- type App
- type CleanerUpper
- type Config
- type Constructor
- type Context
- func (ctx Context) App(name string) (interface{}, error)
- func (ctx Context) LoadModule(name string, rawMsg json.RawMessage) (interface{}, error)
- func (ctx Context) LoadModuleInline(moduleNameKey, moduleScope string, raw json.RawMessage) (interface{}, error)
- func (ctx Context) Logger(mod Module) *zap.Logger
- func (ctx *Context) OnCancel(f func())
- func (ctx Context) Storage() certmagic.Storage
- type CtxKey
- type CustomLog
- type Destructor
- type DiscardWriter
- type Duration
- type LogSampling
- type Logging
- type Module
- type ModuleInfo
- type ParsedAddress
- type Provisioner
- type ReplacementFunc
- type Replacer
- type StandardLibLog
- type StderrWriter
- type StdoutWriter
- type StorageConverter
- type UsagePool
- func (up *UsagePool) Delete(key interface{}) (deleted bool, err error)
- func (up *UsagePool) LoadOrNew(key interface{}, construct Constructor) (value interface{}, loaded bool, err error)
- func (up *UsagePool) LoadOrStore(key, val interface{}) (value interface{}, loaded bool)
- func (up *UsagePool) Range(f func(key, value interface{}) bool)
- type Validator
- type WriterOpener
Constants ¶
const ( ExitCodeSuccess = iota ExitCodeFailedStartup ExitCodeForceQuit ExitCodeFailedQuit )
Exit codes. Generally, you should NOT automatically restart the process if the exit code is ExitCodeFailedStartup (1).
Variables ¶
var ( // DefaultAdminListen is the address for the admin // listener, if none is specified at startup. DefaultAdminListen = "localhost:2019" // ErrInternalRedir indicates an internal redirect // and is useful when admin API handlers rewrite // the request; in that case, authentication and // authorization needs to happen again for the // rewritten request. ErrInternalRedir = fmt.Errorf("internal redirect; re-authorization required") // DefaultAdminConfig is the default configuration // for the administration endpoint. DefaultAdminConfig = &AdminConfig{ Listen: DefaultAdminListen, } )
Functions ¶
func GetModuleID ¶
func GetModuleID(instance interface{}) string
GetModuleID returns a module's ID (the last element of its name) from an instance of its value. If the value is not a module, an empty string will be returned.
func GetModuleName ¶
func GetModuleName(instance interface{}) string
GetModuleName returns a module's name from an instance of its value. If the value is not a module, an empty name will be returned.
func GoModule ¶
GoModule returns the build info of this Caddy build from debug.BuildInfo (requires Go modules). If no version information is available, a non-nil value will still be returned, but with an unknown version.
func JoinNetworkAddress ¶
JoinNetworkAddress combines network, host, and port into a single address string of the form accepted by ParseNetworkAddress(). For unix sockets, the network should be "unix" and the path to the socket should be given as the host parameter.
func Listen ¶
Listen returns a listener suitable for use in a Caddy module. Always be sure to close listeners when you are done with them.
func ListenPacket ¶
func ListenPacket(network, addr string) (net.PacketConn, error)
ListenPacket returns a net.PacketConn suitable for use in a Caddy module. Always be sure to close the PacketConn when you are done.
func Load ¶
Load loads the given config JSON and runs it only if it is different from the current config or forceReload is true.
func Modules ¶
func Modules() []string
Modules returns the names of all registered modules in ascending lexicographical order.
func RegisterModule ¶
RegisterModule registers a module by receiving a plain/empty value of the module. For registration to be properly recorded, this should be called in the init phase of runtime. Typically, the module package will do this as a side-effect of being imported. This function returns an error if the module's info is incomplete or invalid, or if the module is already registered.
func SplitNetworkAddress ¶
SplitNetworkAddress splits a into its network, host, and port components. Note that port may be a port range (:X-Y), or omitted for unix sockets.
func Stop ¶
func Stop() error
Stop stops running the current configuration. It is the antithesis of Run(). This function will log any errors that occur during the stopping of individual apps and continue to stop the others. Stop should only be called if not replacing with a new config.
func TrapSignals ¶
func TrapSignals()
TrapSignals create signal/interrupt handlers as best it can for the current OS. This is a rather invasive function to call in a Go program that captures signals already, so in that case it would be better to implement these handlers yourself.
Types ¶
type APIError ¶
APIError is a structured error that every API handler should return for consistency in logging and client responses. If Message is unset, then Err.Error() will be serialized in its place.
type AdminConfig ¶
type AdminConfig struct { Disabled bool `json:"disabled,omitempty"` Listen string `json:"listen,omitempty"` EnforceOrigin bool `json:"enforce_origin,omitempty"` Origins []string `json:"origins,omitempty"` }
AdminConfig configures the admin endpoint.
type AdminHandler ¶
type AdminHandler interface {
ServeHTTP(http.ResponseWriter, *http.Request) error
}
AdminHandler is like http.Handler except ServeHTTP may return an error.
If any handler encounters an error, it should be returned for proper handling.
type AdminHandlerFunc ¶
type AdminHandlerFunc func(http.ResponseWriter, *http.Request) error
AdminHandlerFunc is a convenience type like http.HandlerFunc.
func (AdminHandlerFunc) ServeHTTP ¶
func (f AdminHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) error
ServeHTTP implements the Handler interface.
type AdminRoute ¶
type AdminRoute struct { Pattern string Handler AdminHandler }
AdminRoute represents a route for the admin endpoint.
type AdminRouter ¶
type AdminRouter interface {
Routes() []AdminRoute
}
AdminRouter is a type which can return routes for the admin API.
type CleanerUpper ¶
type CleanerUpper interface {
Cleanup() error
}
CleanerUpper is implemented by modules which may have side-effects such as opened files, spawned goroutines, or allocated some sort of non-stack state when they were provisioned. This method should deallocate/cleanup those resources to prevent memory leaks. Cleanup should be fast and efficient. Cleanup should work even if Provision returns an error, to allow cleaning up from partial provisionings.
type Config ¶
type Config struct { Admin *AdminConfig `json:"admin,omitempty"` Logging *Logging `json:"logging,omitempty"` StorageRaw json.RawMessage `json:"storage,omitempty"` AppsRaw map[string]json.RawMessage `json:"apps,omitempty"` // contains filtered or unexported fields }
Config represents a Caddy configuration. It is the top of the module structure: all Caddy modules will be loaded, starting with this struct. In order to be loaded and run successfully, a Config and all its modules must be JSON-encodable; i.e. when filling a Config struct manually, its JSON-encodable fields (the ones with JSON struct tags, usually ending with "Raw" if they decode into a separate field) must be set so that they can be unmarshaled and provisioned. Setting the fields for the decoded values instead will result in those values being overwritten at unmarshaling/provisioning.
type Constructor ¶
type Constructor func() (Destructor, error)
Constructor is a function that returns a new value that can destruct itself when it is no longer needed.
type Context ¶
Context is a type which defines the lifetime of modules that are loaded and provides access to the parent configuration that spawned the modules which are loaded. It should be used with care and wrapped with derivation functions from the standard context package only if you don't need the Caddy specific features. These contexts are cancelled when the lifetime of the modules loaded from it is over.
Use NewContext() to get a valid value (but most modules will not actually need to do this).
func NewContext ¶
func NewContext(ctx Context) (Context, context.CancelFunc)
NewContext provides a new context derived from the given context ctx. Normally, you will not need to call this function unless you are loading modules which have a different lifespan than the ones for the context the module was provisioned with. Be sure to call the cancel func when the context is to be cleaned up so that modules which are loaded will be properly unloaded. See standard library context package's documentation.
func (Context) App ¶
App returns the configured app named name. If no app with that name is currently configured, a new empty one will be instantiated. (The app module must still be registered.)
func (Context) LoadModule ¶
func (ctx Context) LoadModule(name string, rawMsg json.RawMessage) (interface{}, error)
LoadModule decodes rawMsg into a new instance of mod and returns the value. If mod.New() does not return a pointer value, it is converted to one so that it is unmarshaled into the underlying concrete type. If mod.New is nil, an error is returned. If the module implements Validator or Provisioner interfaces, those methods are invoked to ensure the module is fully configured and valid before being used.
func (Context) LoadModuleInline ¶
func (ctx Context) LoadModuleInline(moduleNameKey, moduleScope string, raw json.RawMessage) (interface{}, error)
LoadModuleInline loads a module from a JSON raw message which decodes to a map[string]interface{}, where one of the keys is moduleNameKey and the corresponding value is the module name as a string, which can be found in the given scope.
This allows modules to be decoded into their concrete types and used when their names cannot be the unique key in a map, such as when there are multiple instances in the map or it appears in an array (where there are no custom keys). In other words, the key containing the module name is treated special/separate from all the other keys.
type CtxKey ¶
type CtxKey string
CtxKey is a value type for use with context.WithValue.
const ReplacerCtxKey CtxKey = "replacer"
ReplacerCtxKey is the context key for a replacer.
type CustomLog ¶
type CustomLog struct { WriterRaw json.RawMessage `json:"writer,omitempty"` EncoderRaw json.RawMessage `json:"encoder,omitempty"` Level string `json:"level,omitempty"` Sampling *LogSampling `json:"sampling,omitempty"` Include []string `json:"include,omitempty"` Exclude []string `json:"exclude,omitempty"` // contains filtered or unexported fields }
CustomLog represents a custom logger configuration.
type Destructor ¶
type Destructor interface {
Destruct() error
}
Destructor is a value that can clean itself up when it is deallocated.
type DiscardWriter ¶
type DiscardWriter struct{}
DiscardWriter discards all writes.
func (DiscardWriter) CaddyModule ¶
func (DiscardWriter) CaddyModule() ModuleInfo
CaddyModule returns the Caddy module information.
func (DiscardWriter) OpenWriter ¶
func (DiscardWriter) OpenWriter() (io.WriteCloser, error)
OpenWriter returns ioutil.Discard that can't be closed.
func (DiscardWriter) String ¶
func (DiscardWriter) String() string
func (DiscardWriter) WriterKey ¶
func (DiscardWriter) WriterKey() string
WriterKey returns a unique key representing discard.
type Duration ¶
Duration is a JSON-string-unmarshable duration type.
func (*Duration) UnmarshalJSON ¶
UnmarshalJSON satisfies json.Unmarshaler.
type LogSampling ¶
type LogSampling struct { Interval time.Duration `json:"interval,omitempty"` First int `json:"first,omitempty"` Thereafter int `json:"thereafter,omitempty"` }
LogSampling configures log entry sampling.
type Logging ¶
type Logging struct { Sink *StandardLibLog `json:"sink,omitempty"` Logs map[string]*CustomLog `json:"logs,omitempty"` // contains filtered or unexported fields }
Logging facilitates logging within Caddy.
type Module ¶
type Module interface { // This method indicates the type is a Caddy // module. The returned ModuleInfo must have // both a name and a constructor function. // This method must not have any side-effects. CaddyModule() ModuleInfo }
Module is a type that is used as a Caddy module.
type ModuleInfo ¶
type ModuleInfo struct { // Name is the full name of the module. It // must be unique and properly namespaced. Name string // New returns a pointer to a new, empty // instance of the module's type. The host // module which instantiates this module will // likely type-assert and invoke methods on // the returned value. This function must not // have any side-effects. New func() Module }
ModuleInfo represents a registered Caddy module.
func GetModule ¶
func GetModule(name string) (ModuleInfo, error)
GetModule returns module information from its full name.
func GetModules ¶
func GetModules(scope string) []ModuleInfo
GetModules returns all modules in the given scope/namespace. For example, a scope of "foo" returns modules named "foo.bar", "foo.loo", but not "bar", "foo.bar.loo", etc. An empty scope returns top-level modules, for example "foo" or "bar". Partial scopes are not matched (i.e. scope "foo.ba" does not match name "foo.bar").
Because modules are registered to a map, the returned slice will be sorted to keep it deterministic.
func (ModuleInfo) ID ¶
func (mi ModuleInfo) ID() string
ID returns a module's ID, which is the last element of its name.
func (ModuleInfo) Namespace ¶
func (mi ModuleInfo) Namespace() string
Namespace returns the module's namespace (scope) which is all but the last element of its name. If there is no explicit namespace in the name, the whole name is considered the namespace.
func (ModuleInfo) String ¶
func (mi ModuleInfo) String() string
type ParsedAddress ¶
ParsedAddress contains the individual components for a parsed network address of the form accepted by ParseNetworkAddress(). Network should be a network value accepted by Go's net package. Port ranges are given by [StartPort, EndPort].
func ParseNetworkAddress ¶
func ParseNetworkAddress(addr string) (ParsedAddress, error)
ParseNetworkAddress parses addr into its individual components. The input string is expected to be of the form "network/host:port-range" where any part is optional. The default network, if unspecified, is tcp. Port ranges are inclusive.
Network addresses are distinct from URLs and do not use URL syntax.
func (ParsedAddress) JoinHostPort ¶
func (pa ParsedAddress) JoinHostPort(offset uint) string
JoinHostPort is like net.JoinHostPort, but where the port is StartPort + offset.
func (ParsedAddress) PortRangeSize ¶
func (pa ParsedAddress) PortRangeSize() uint
PortRangeSize returns how many ports are in pa's port range. Port ranges are inclusive, so the size is the difference of start and end ports plus one.
func (ParsedAddress) String ¶
func (pa ParsedAddress) String() string
String reconstructs the address string to the form expected by ParseNetworkAddress().
type Provisioner ¶
Provisioner is implemented by modules which may need to perform some additional "setup" steps immediately after being loaded. Provisioning should be fast (imperceptible running time). If any side-effects result in the execution of this function (e.g. creating global state, any other allocations which require garbage collection, opening files, starting goroutines etc.), be sure to clean up properly by implementing the CleanerUpper interface to avoid leaking resources.
type ReplacementFunc ¶
ReplacementFunc is a function that returns a replacement for the given key along with true if the function is able to service that key (even if the value is blank). If the function does not recognize the key, false should be returned.
type Replacer ¶
type Replacer interface { Set(variable, value string) Delete(variable string) Map(ReplacementFunc) ReplaceAll(input, empty string) string ReplaceKnown(input, empty string) string ReplaceOrErr(input string, errOnEmpty, errOnUnknown bool) (string, error) }
Replacer can replace values in strings.
type StandardLibLog ¶
type StandardLibLog struct { WriterRaw json.RawMessage `json:"writer,omitempty"` // contains filtered or unexported fields }
StandardLibLog configures the default Go standard library global logger in the log package. This is necessary because module dependencies which are not built specifically for Caddy will use the standard logger.
type StderrWriter ¶
type StderrWriter struct{}
StderrWriter can write logs to stdout.
func (StderrWriter) CaddyModule ¶
func (StderrWriter) CaddyModule() ModuleInfo
CaddyModule returns the Caddy module information.
func (StderrWriter) OpenWriter ¶
func (StderrWriter) OpenWriter() (io.WriteCloser, error)
OpenWriter returns os.Stderr that can't be closed.
func (StderrWriter) String ¶
func (StderrWriter) String() string
func (StderrWriter) WriterKey ¶
func (StderrWriter) WriterKey() string
WriterKey returns a unique key representing stderr.
type StdoutWriter ¶
type StdoutWriter struct{}
StdoutWriter can write logs to stdout.
func (StdoutWriter) CaddyModule ¶
func (StdoutWriter) CaddyModule() ModuleInfo
CaddyModule returns the Caddy module information.
func (StdoutWriter) OpenWriter ¶
func (StdoutWriter) OpenWriter() (io.WriteCloser, error)
OpenWriter returns os.Stdout that can't be closed.
func (StdoutWriter) String ¶
func (StdoutWriter) String() string
func (StdoutWriter) WriterKey ¶
func (StdoutWriter) WriterKey() string
WriterKey returns a unique key representing stdout.
type StorageConverter ¶
StorageConverter is a type that can convert itself to a valid, usable certmagic.Storage value. (The value might be short-lived.) This interface allows us to adapt any CertMagic storage implementation into a consistent API for Caddy configuration.
type UsagePool ¶
UsagePool is a thread-safe map that pools values based on usage (reference counting). Values are only inserted if they do not already exist. There are two ways to add values to the pool:
- LoadOrStore will increment usage and store the value immediately if it does not already exist.
- LoadOrNew will atomically check for existence and construct the value immediately if it does not already exist, or increment the usage otherwise, then store that value in the pool. When the constructed value is finally deleted from the pool (when its usage reaches 0), it will be cleaned up by calling Destruct().
The use of LoadOrNew allows values to be created and reused and finally cleaned up only once, even though they may have many references throughout their lifespan. This is helpful, for example, when sharing thread-safe io.Writers that you only want to open and close once.
There is no way to overwrite existing keys in the pool without first deleting it as many times as it was stored. Deleting too many times will panic.
The implementation does not use a sync.Pool because UsagePool needs additional atomicity to run the constructor functions when creating a new value when LoadOrNew is used. (We could probably use sync.Pool but we'd still have to layer our own additional locks on top.)
An empty UsagePool is NOT safe to use; always call NewUsagePool() to make a new one.
func NewUsagePool ¶
func NewUsagePool() *UsagePool
NewUsagePool returns a new usage pool that is ready to use.
func (*UsagePool) Delete ¶
Delete decrements the usage count for key and removes the value from the underlying map if the usage is 0. It returns true if the usage count reached 0 and the value was deleted. It panics if the usage count drops below 0; always call Delete precisely as many times as LoadOrStore.
func (*UsagePool) LoadOrNew ¶
func (up *UsagePool) LoadOrNew(key interface{}, construct Constructor) (value interface{}, loaded bool, err error)
LoadOrNew loads the value associated with key from the pool if it already exists. If the key doesn't exist, it will call construct to create a new value and then stores that in the pool. An error is only returned if the constructor returns an error. The loaded or constructed value is returned. The loaded return value is true if the value already existed and was loaded, or false if it was newly constructed.
func (*UsagePool) LoadOrStore ¶
LoadOrStore loads the value associated with key from the pool if it already exists, or stores it if it does not exist. It returns the value that was either loaded or stored, and true if the value already existed and was
func (*UsagePool) Range ¶
Range iterates the pool similarly to how sync.Map.Range() does: it calls f for every key in the pool, and if f returns false, iteration is stopped. Ranging does not affect usage counts.
This method is somewhat naive and acquires a read lock on the entire pool during iteration, so do your best to make f() really fast, m'kay?
type Validator ¶
type Validator interface {
Validate() error
}
Validator is implemented by modules which can verify that their configurations are valid. This method will be called after Provision() (if implemented). Validation should always be fast (imperceptible running time) and an error should be returned only if the value's configuration is invalid.
type WriterOpener ¶
type WriterOpener interface { fmt.Stringer // WriterKey is a string that uniquely identifies this // writer configuration. It is not shown to humans. WriterKey() string // OpenWriter opens a log for writing. The writer // should be safe for concurrent use but need not // be synchronous. OpenWriter() (io.WriteCloser, error) }
WriterOpener is a module that can open a log writer. It can return a human-readable string representation of itself so that operators can understand where the logs are going.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
caddy
Package main is the entry point of the Caddy application.
|
Package main is the entry point of the Caddy application. |
modules
|
|
caddyhttp/encode
Package encode implements an encoder middleware for Caddy.
|
Package encode implements an encoder middleware for Caddy. |
caddytls/distributedstek
Package distributedstek provides TLS session ticket ephemeral keys (STEKs) in a distributed fashion by utilizing configured storage for locking and key sharing.
|
Package distributedstek provides TLS session ticket ephemeral keys (STEKs) in a distributed fashion by utilizing configured storage for locking and key sharing. |
pkg
|
|