{"modulePath":"github.com/codedance/caddy","version":"v0.11.2","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package caddy\n\nPackage caddy implements the Caddy server manager.\n\nTo use this package:\n\n 1. Set the AppName and AppVersion variables.\n 2. Call LoadCaddyfile() to get the Caddyfile. Pass in the name of the server type (like \"http\"). Make sure the server type's package is imported (import \\_ \"github.com/mholt/caddy/caddyhttp\").\n 3. Call caddy.Start() to start Caddy. You get back an Instance, on which you can call Restart() to restart it or Stop() to stop it.\n\nYou should call Wait() on your instance to wait for all servers to quit before your process exits.\n\n## Constants\n\n```go\nconst (\n\tStartupEvent         EventName = \"startup\"\n\tShutdownEvent                  = \"shutdown\"\n\tCertRenewEvent                 = \"certrenew\"\n\tInstanceStartupEvent           = \"instancestartup\"\n\tInstanceRestartEvent           = \"instancerestart\"\n)\n```\nDefine names for the various events\n\n## Variables\n\n```go\nvar (\n\t// AppName is the name of the application.\n\tAppName string\n\n\t// AppVersion is the version of the application.\n\tAppVersion string\n\n\t// Quiet mode will not show any informative output on initialization.\n\tQuiet bool\n\n\t// PidFile is the path to the pidfile to create.\n\tPidFile string\n\n\t// GracefulTimeout is the maximum duration of a graceful shutdown.\n\tGracefulTimeout time.Duration\n)\n```\nConfigurable application parameters\n\n```go\nvar (\n\t// DefaultConfigFile is the name of the configuration file that is loaded\n\t// by default if no other file is specified.\n\tDefaultConfigFile = \"Caddyfile\"\n)\n```\n\n```go\nvar OnProcessExit []func()\n```\nOnProcessExit is a list of functions to run when the process exits -- they are ONLY for cleanup and should not block, return errors, or do anything fancy. They will be run with every signal, even if \"shutdown callbacks\" are not executed. This variable must only be modified in the main goroutine from init() functions.\n\n## Functions\n\n```go\nfunc AssetsPath() string\n```\nAssetsPath returns the path to the folder where the application may store data. If CADDYPATH env variable is set, that value is used. Otherwise, the path is the result of evaluating \"$HOME/.caddy\".\n\n```go\nfunc DescribePlugins() string\n```\nDescribePlugins returns a string describing the registered plugins.\n\n```go\nfunc EmitEvent(event EventName, info interface{})\n```\nEmitEvent executes the different hooks passing the EventType as an argument. This is a blocking function. Hook developers should use 'go' keyword if they don't want to block Caddy.\n\n```go\nfunc IsInternal(addr string) bool\n```\nIsInternal returns true if the IP of addr belongs to a private network IP range. addr must only be an IP or an IP:port combination. Loopback addresses are considered false.\n\n```go\nfunc IsLoopback(addr string) bool\n```\nIsLoopback returns true if the hostname of addr looks explicitly like a common local hostname. addr must only be a host or a host:port combination.\n\n```go\nfunc IsUpgrade() bool\n```\nIsUpgrade returns true if this process is part of an upgrade where a parent caddy process spawned this one to upgrade the binary.\n\n```go\nfunc ListPlugins() map[string][]string\n```\nListPlugins makes a list of the registered plugins, keyed by plugin type.\n\n```go\nfunc RegisterCaddyfileLoader(name string, loader Loader)\n```\nRegisterCaddyfileLoader registers loader named name.\n\n```go\nfunc RegisterClusterPlugin(name string, provider ClusterPluginConstructor)\n```\nRegisterClusterPlugin registers provider by name for facilitating cluster-wide operations like storage and synchronization.\n\n```go\nfunc RegisterEventHook(name string, hook EventHook)\n```\nRegisterEventHook plugs in hook. All the hooks should register themselves and they must have a name.\n\n```go\nfunc RegisterParsingCallback(serverType, afterDir string, callback ParsingCallback)\n```\nRegisterParsingCallback registers callback to be called after executing the directive afterDir for server type serverType.\n\n```go\nfunc RegisterPlugin(name string, plugin Plugin)\n```\nRegisterPlugin plugs in plugin. All plugins should register themselves, even if they do not perform an action associated with a directive. It is important for the process to know which plugins are available.\n\nThe plugin MUST have a name: lower case and one word. If this plugin has an action, it must be the name of the directive that invokes it. A name is always required and must be unique for the server type.\n\n```go\nfunc RegisterServerType(typeName string, srv ServerType)\n```\nRegisterServerType registers a server type srv by its name, typeName.\n\n```go\nfunc SetDefaultCaddyfileLoader(name string, loader Loader)\n```\nSetDefaultCaddyfileLoader registers loader by name as the default Caddyfile loader if no others produce a Caddyfile. If another Caddyfile loader has already been set as the default, this replaces it.\n\nDo not call RegisterCaddyfileLoader on the same loader; that would be redundant.\n\n```go\nfunc SplitCommandAndArgs(command string) (cmd string, args []string, err error)\n```\nSplitCommandAndArgs takes a command string and parses it shell-style into the command and its separate arguments.\n\n```go\nfunc Started() bool\n```\nStarted returns true if at least one instance has been started by this package. It never gets reset to false once it is set to true.\n\n```go\nfunc Stop() error\n```\nStop stops ALL servers. It blocks until they are all stopped. It does NOT execute shutdown callbacks, and it deletes all instances after stopping is completed. Do not re-use any references to old instances after calling Stop.\n\n```go\nfunc TrapSignals()\n```\nTrapSignals create signal handlers for all applicable signals for this system. If your Go program uses signals, this is a rather invasive function; best to implement them yourself in that case. Signals are not required for the caddy package to function properly, but this is a convenient way to allow the user to control this part of your program.\n\n```go\nfunc Upgrade() error\n```\nUpgrade re-launches the process, preserving the listeners for a graceful upgrade. It does NOT load new configuration; it only starts the process anew with the current config. This makes it possible to perform zero-downtime binary upgrades.\n\nTODO: For more information when debugging, see: [https://forum.golangbridge.org/t/bind-address-already-in-use-even-after-listener-closed/1510?u=matt](https://forum.golangbridge.org/t/bind-address-already-in-use-even-after-listener-closed/1510?u=matt) [https://github.com/mholt/shared-conn](https://github.com/mholt/shared-conn)\n\n```go\nfunc ValidDirectives(serverType string) []string\n```\nValidDirectives returns the list of all directives that are recognized for the server type serverType. However, not all directives may be installed. This makes it possible to give more helpful error messages, like \"did you mean ...\" or \"maybe you need to plug in ...\".\n\n```go\nfunc ValidateAndExecuteDirectives(cdyfile Input, inst *Instance, justValidate bool) error\n```\nValidateAndExecuteDirectives will load the server blocks from cdyfile by parsing it, then execute the directives configured by it and store the resulting server blocks into inst. If justValidate is true, parse callbacks will not be executed between directives, since the purpose is only to check the input for valid syntax.\n\n## Types\n\n```go\ntype AfterStartup interface {\n\tOnStartupComplete()\n}\n```\nAfterStartup is an interface that can be implemented by a server type that wants to run some code after all servers for the same Instance have started.\n\n```go\ntype CaddyfileInput struct {\n\tFilepath       string\n\tContents       []byte\n\tServerTypeName string\n}\n```\nCaddyfileInput represents a Caddyfile as input and is simply a convenient way to implement the Input interface.\n\n```go\nfunc (c CaddyfileInput) Body() []byte\n```\nBody returns c.Contents.\n\n```go\nfunc (c CaddyfileInput) Path() string\n```\nPath returns c.Filepath.\n\n```go\nfunc (c CaddyfileInput) ServerType() string\n```\nServerType returns c.ServerType.\n\n```go\ntype ClusterPluginConstructor func() (certmagic.Storage, error)\n```\nClusterPluginConstructor is a function type that is used to instantiate a new implementation of both certmagic.Storage and certmagic.Locker, which are required for successful use in cluster environments.\n\n```go\ntype Context interface {\n\t// Called after the Caddyfile is parsed into server\n\t// blocks but before the directives are executed,\n\t// this method gives you an opportunity to inspect\n\t// the server blocks and prepare for the execution\n\t// of directives. Return the server blocks (which\n\t// you may modify, if desired) and an error, if any.\n\t// The first argument is the name or path to the\n\t// configuration file (Caddyfile).\n\t//\n\t// This function can be a no-op and simply return its\n\t// input if there is nothing to do here.\n\tInspectServerBlocks(string, []caddyfile.ServerBlock) ([]caddyfile.ServerBlock, error)\n\n\t// This is what Caddy calls to make server instances.\n\t// By this time, all directives have been executed and,\n\t// presumably, the context has enough state to produce\n\t// server instances for Caddy to start.\n\tMakeServers() ([]Server, error)\n}\n```\nContext is a type which carries a server type through the load and setup phase; it maintains the state between loading the Caddyfile, then executing its directives, then making the servers for Caddy to manage. Typically, such state involves configuration structs, etc.\n\n```go\ntype Controller struct {\n\tcaddyfile.Dispenser\n\n\t// Key is the key from the top of the server block, usually\n\t// an address, hostname, or identifier of some sort.\n\tKey string\n\n\t// OncePerServerBlock is a function that executes f\n\t// exactly once per server block, no matter how many\n\t// hosts are associated with it. If it is the first\n\t// time, the function f is executed immediately\n\t// (not deferred) and may return an error which is\n\t// returned by OncePerServerBlock.\n\tOncePerServerBlock func(f func() error) error\n\n\t// ServerBlockIndex is the 0-based index of the\n\t// server block as it appeared in the input.\n\tServerBlockIndex int\n\n\t// ServerBlockKeyIndex is the 0-based index of this\n\t// key as it appeared in the input at the head of the\n\t// server block.\n\tServerBlockKeyIndex int\n\n\t// ServerBlockKeys is a list of keys that are\n\t// associated with this server block. All these\n\t// keys, consequently, share the same tokens.\n\tServerBlockKeys []string\n\n\t// ServerBlockStorage is used by a directive's\n\t// setup function to persist state between all\n\t// the keys on a server block.\n\tServerBlockStorage interface{}\n\t// contains filtered or unexported fields\n}\n```\nController is given to the setup function of directives which gives them access to be able to read tokens with which to configure themselves. It also stores state for the setup functions, can get the current context, and can be used to identify a particular server block using the Key field.\n\n```go\nfunc NewTestController(serverType, input string) *Controller\n```\nNewTestController creates a new Controller for the server type and input specified. The filename is \"Testfile\". If the server type is not empty and is plugged in, a context will be created so that the results of setup functions can be checked for correctness.\n\nUsed only for testing, but exported so plugins can use this for convenience.\n\n```go\nfunc (c *Controller) Context() Context\n```\nContext gets the context associated with the instance associated with c.\n\n```go\nfunc (c *Controller) Get(key interface{}) interface{}\n```\nGet safely gets a value from the Instance's storage.\n\n```go\nfunc (c *Controller) OnFinalShutdown(fn func() error)\n```\nOnFinalShutdown adds fn to the list of callback functions to execute when the server is about to be shut down NOT as part of a restart.\n\n```go\nfunc (c *Controller) OnFirstStartup(fn func() error)\n```\nOnFirstStartup adds fn to the list of callback functions to execute when the server is about to be started NOT as part of a restart.\n\n```go\nfunc (c *Controller) OnRestart(fn func() error)\n```\nOnRestart adds fn to the list of callback functions to execute when the server is about to be restarted.\n\n```go\nfunc (c *Controller) OnRestartFailed(fn func() error)\n```\nOnRestartFailed adds fn to the list of callback functions to execute if the server failed to restart.\n\n```go\nfunc (c *Controller) OnShutdown(fn func() error)\n```\nOnShutdown adds fn to the list of callback functions to execute when the server is about to be shut down (including restarts).\n\n```go\nfunc (c *Controller) OnStartup(fn func() error)\n```\nOnStartup adds fn to the list of callback functions to execute when the server is about to be started (including restarts).\n\n```go\nfunc (c *Controller) ServerType() string\n```\nServerType gets the name of the server type that is being set up.\n\n```go\nfunc (c *Controller) Set(key, val interface{})\n```\nSet safely sets a value on the Instance's storage.\n\n```go\ntype CtxKey string\n```\nCtxKey is a value type for use with context.WithValue.\n\n```go\ntype EventHook func(eventType EventName, eventInfo interface{}) error\n```\nEventHook is a type which holds information about a startup hook plugin.\n\n```go\ntype EventName string\n```\nEventName represents the name of an event used with event hooks.\n\n```go\ntype GracefulServer interface {\n\tServer\n\tStopper\n\n\t// Address returns the address the server should\n\t// listen on; it is used to pair the server to\n\t// its listener during a graceful/zero-downtime\n\t// restart. Thus when implementing this method,\n\t// you must not access a listener to get the\n\t// address; you must store the address the\n\t// server is to serve on some other way.\n\tAddress() string\n\n\t// WrapListener wraps a listener with the\n\t// listener middlewares configured for this\n\t// server, if any.\n\tWrapListener(net.Listener) net.Listener\n}\n```\nGracefulServer is a Server and Stopper, the stopping of which is graceful (whatever that means for the kind of server being implemented). It must be able to return the address it is configured to listen on so that its listener can be paired with it upon graceful restarts. The net.Listener that a GracefulServer creates must implement the Listener interface for restarts to be graceful (assuming the listener is for TCP).\n\n```go\ntype Input interface {\n\t// Gets the Caddyfile contents\n\tBody() []byte\n\n\t// Gets the path to the origin file\n\tPath() string\n\n\t// The type of server this input is intended for\n\tServerType() string\n}\n```\nInput represents a Caddyfile; its contents and file path (which should include the file name at the end of the path). If path does not apply (e.g. piped input) you may use any understandable value. The path is mainly used for logging, error messages, and debugging.\n\n```go\nfunc CaddyfileFromPipe(f *os.File, serverType string) (Input, error)\n```\nCaddyfileFromPipe loads the Caddyfile input from f if f is not interactive input. f is assumed to be a pipe or stream, such as os.Stdin. If f is not a pipe, no error is returned but the Input value will be nil. An error is only returned if there was an error reading the pipe, even if the length of what was read is 0.\n\n```go\nfunc DefaultInput(serverType string) Input\n```\nDefaultInput returns the default Caddyfile input to use when it is otherwise empty or missing. It uses the default host and port (depends on host, e.g. localhost is 2015, otherwise 443) and root.\n\n```go\nfunc LoadCaddyfile(serverType string) (Input, error)\n```\nLoadCaddyfile loads a Caddyfile by calling the plugged in Caddyfile loader methods. An error is returned if more than one loader returns a non-nil Caddyfile input. If no loaders load a Caddyfile, the default loader is used. If no default loader is registered or it returns nil, the server type's default Caddyfile is loaded. If the server type does not specify any default Caddyfile value, then an empty Caddyfile is returned. Consequently, this function never returns a nil value as long as there are no errors.\n\n```go\ntype Instance struct {\n\n\t// these callbacks execute when certain events occur\n\tOnFirstStartup  []func() error // starting, not as part of a restart\n\tOnStartup       []func() error // starting, even as part of a restart\n\tOnRestart       []func() error // before restart commences\n\tOnRestartFailed []func() error // if restart failed\n\tOnShutdown      []func() error // stopping, even as part of a restart\n\tOnFinalShutdown []func() error // stopping, not as part of a restart\n\n\t// storing values on an instance is preferable to\n\t// global state because these will get garbage-\n\t// collected after in-process reloads when the\n\t// old instances are destroyed; use StorageMu\n\t// to access this value safely\n\tStorage   map[interface{}]interface{}\n\tStorageMu sync.RWMutex\n\t// contains filtered or unexported fields\n}\n```\nInstance contains the state of servers created as a result of calling Start and can be used to access or control those servers. It is literally an instance of a server type. Instance values should NOT be copied. Use \\*Instance for safety.\n\n```go\nfunc Instances() []*Instance\n```\nInstances returns the list of instances.\n\n```go\nfunc Start(cdyfile Input) (*Instance, error)\n```\nStart starts Caddy with the given Caddyfile.\n\nThis function blocks until all the servers are listening.\n\n```go\nfunc (i *Instance) Caddyfile() Input\n```\nCaddyfile returns the Caddyfile used to create i.\n\n```go\nfunc (i *Instance) Restart(newCaddyfile Input) (*Instance, error)\n```\nRestart replaces the servers in i with new servers created from executing the newCaddyfile. Upon success, it returns the new instance to replace i. Upon failure, i will not be replaced.\n\n```go\nfunc (i *Instance) SaveServer(s Server, ln net.Listener)\n```\nSaveServer adds s and its associated listener ln to the internally-kept list of servers that is running. For saved servers, graceful restarts will be provided.\n\n```go\nfunc (i *Instance) Servers() []ServerListener\n```\nServers returns the ServerListeners in i.\n\n```go\nfunc (i *Instance) ShutdownCallbacks() []error\n```\nShutdownCallbacks executes all the shutdown callbacks of i, including ones that are scheduled only for the final shutdown of i. An error returned from one does not stop execution of the rest. All the non-nil errors will be returned.\n\n```go\nfunc (i *Instance) Stop() error\n```\nStop stops all servers contained in i. It does NOT execute shutdown callbacks.\n\n```go\nfunc (i *Instance) Wait()\n```\nWait blocks until all of i's servers have stopped.\n\n```go\ntype Listener interface {\n\tnet.Listener\n\tFile() (*os.File, error)\n}\n```\nListener is a net.Listener with an underlying file descriptor. A server's listener should implement this interface if it is to support zero-downtime reloads.\n\n```go\ntype Loader interface {\n\tLoad(serverType string) (Input, error)\n}\n```\nLoader is a type that can load a Caddyfile. It is passed the name of the server type. It returns an error only if something went wrong, not simply if there is no Caddyfile for this loader to load.\n\nA Loader should only load the Caddyfile if a certain condition or requirement is met, as returning a non-nil Input value along with another Loader will result in an error. In other words, loading the Caddyfile must be deliberate \u0026 deterministic, not haphazard.\n\nThe exception is the default Caddyfile loader, which will be called only if no other Caddyfile loaders return a non-nil Input. The default loader may always return an Input value.\n\n```go\ntype LoaderFunc func(serverType string) (Input, error)\n```\nLoaderFunc is a convenience type similar to http.HandlerFunc that allows you to use a plain function as a Load() method.\n\n```go\nfunc (lf LoaderFunc) Load(serverType string) (Input, error)\n```\nLoad loads a Caddyfile.\n\n```go\ntype PacketConn interface {\n\tnet.PacketConn\n\tFile() (*os.File, error)\n}\n```\nPacketConn is a net.PacketConn with an underlying file descriptor. A server's packetconn should implement this interface if it is to support zero-downtime reloads (in sofar this holds true for datagram connections).\n\n```go\ntype ParsingCallback func(Context) error\n```\nParsingCallback is a function that is called after a directive's setup functions have been executed for all the server blocks.\n\n```go\ntype Plugin struct {\n\t// ServerType is the type of server this plugin is for.\n\t// Can be empty if not applicable, or if the plugin\n\t// can associate with any server type.\n\tServerType string\n\n\t// Action is the plugin's setup function, if associated\n\t// with a directive in the Caddyfile.\n\tAction SetupFunc\n}\n```\nPlugin is a type which holds information about a plugin.\n\n```go\ntype Server interface {\n\tTCPServer\n\tUDPServer\n}\n```\nServer is a type that can listen and serve. It supports both TCP and UDP, although the UDPServer interface can be used for more than just UDP.\n\nIf the server uses TCP, it should implement TCPServer completely. If it uses UDP or some other protocol, it should implement UDPServer completely. If it uses both, both interfaces should be fully implemented. Any unimplemented methods should be made as no-ops that simply return nil values.\n\n```go\ntype ServerListener struct {\n\t// contains filtered or unexported fields\n}\n```\nServerListener pairs a server to its listener and/or packetconn.\n\n```go\nfunc (s ServerListener) Addr() net.Addr\n```\nAddr returns the listener's network address. It returns nil when it is not set.\n\n```go\nfunc (s ServerListener) LocalAddr() net.Addr\n```\nLocalAddr returns the local network address of the packetconn. It returns nil when it is not set.\n\n```go\ntype ServerType struct {\n\t// Function that returns the list of directives, in\n\t// execution order, that are valid for this server\n\t// type. Directives should be one word if possible\n\t// and lower-cased.\n\tDirectives func() []string\n\n\t// DefaultInput returns a default config input if none\n\t// is otherwise loaded. This is optional, but highly\n\t// recommended, otherwise a blank Caddyfile will be\n\t// used.\n\tDefaultInput func() Input\n\n\t// The function that produces a new server type context.\n\t// This will be called when a new Caddyfile is being\n\t// loaded, parsed, and executed independently of any\n\t// startup phases before this one. It's a way to keep\n\t// each set of server instances separate and to reduce\n\t// the amount of global state you need.\n\tNewContext func(inst *Instance) Context\n}\n```\nServerType contains information about a server type.\n\n```go\ntype SetupFunc func(c *Controller) error\n```\nSetupFunc is used to set up a plugin, or in other words, execute a directive. It will be called once per key for each server block it appears in.\n\n```go\nfunc DirectiveAction(serverType, dir string) (SetupFunc, error)\n```\nDirectiveAction gets the action for directive dir of server type serverType.\n\n```go\ntype Stopper interface {\n\t// Stop stops the server. It blocks until the\n\t// server is completely stopped.\n\tStop() error\n}\n```\nStopper is a type that can stop serving. The stop does not necessarily have to be graceful.\n\n```go\ntype TCPServer interface {\n\t// Listen starts listening by creating a new listener\n\t// and returning it. It does not start accepting\n\t// connections. For UDP-only servers, this method\n\t// can be a no-op that returns (nil, nil).\n\tListen() (net.Listener, error)\n\n\t// Serve starts serving using the provided listener.\n\t// Serve must start the server loop nearly immediately,\n\t// or at least not return any errors before the server\n\t// loop begins. Serve blocks indefinitely, or in other\n\t// words, until the server is stopped. For UDP-only\n\t// servers, this method can be a no-op that returns nil.\n\tServe(net.Listener) error\n}\n```\nTCPServer is a type that can listen and serve connections. A TCPServer must associate with exactly zero or one net.Listeners.\n\n```go\ntype UDPServer interface {\n\t// ListenPacket starts listening by creating a new packetconn\n\t// and returning it. It does not start accepting connections.\n\t// TCP-only servers may leave this method blank and return\n\t// (nil, nil).\n\tListenPacket() (net.PacketConn, error)\n\n\t// ServePacket starts serving using the provided packetconn.\n\t// ServePacket must start the server loop nearly immediately,\n\t// or at least not return any errors before the server\n\t// loop begins. ServePacket blocks indefinitely, or in other\n\t// words, until the server is stopped. For TCP-only servers,\n\t// this method can be a no-op that returns nil.\n\tServePacket(net.PacketConn) error\n}\n```\nUDPServer is a type that can listen and serve packets. A UDPServer must associate with exactly zero or one net.PacketConns.\n\n","path":"github.com/codedance/caddy","name":"caddy","synopsis":"Package caddy implements the Caddy server manager.","isRedistributable":true}
