Go API Documentation

github.com/caddyserver/caddy/v2/cmd

No package summary is available.

Package

Files: 9. Third party imports: 9. Imports from organisation: 1. Tests: 0. Benchmarks: 0.

Constants

Vars

Interface guard

Types

Command

Command represents a subcommand. Name, Func, and Short are required.

Field name Field type Comment
Name

string

The name of the subcommand. Must conform to the format described by the RegisterCommand() godoc. Required.

Usage

string

Usage is a brief message describing the syntax of the subcommand's flags and args. Use [] to indicate optional parameters and <> to enclose literal values intended to be replaced by the user. Do not prefix the string with "caddy" or the name of the command since these will be prepended for you; only include the actual parameters for this command.

Short

string

Short is a one-line message explaining what the command does. Should not end with punctuation. Required.

Long

string

Long is the full help text shown to the user. Will be trimmed of whitespace on both ends before being printed.

Flags

*flag.FlagSet

Flags is the flagset for command. This is ignored if CobraFunc is set.

Func

CommandFunc

Func is a function that executes a subcommand using the parsed flags. It returns an exit code and any associated error. Required if CobraFunc is not set.

CobraFunc

func(*cobra.Command)

CobraFunc allows further configuration of the command via cobra's APIs. If this is set, then Func and Flags are ignored, with the assumption that they are set in this function. A caddycmd.WrapCommandFuncForCobra helper exists to simplify porting CommandFunc to Cobra's RunE.

CommandFunc

CommandFunc is a command's function. It runs the command and returns the proper exit code along with any error that occurred.

Field name Field type Comment
type

func(Flags) (int, error)

No comment on field.

Flags

Flags wraps a FlagSet so that typed values from flags can be easily retrieved.

Field name Field type Comment

*pflag.FlagSet

No comment on field.

StringSlice

StringSlice is a flag.Value that enables repeated use of a string flag.

Field name Field type Comment
type

[]string

No comment on field.

exitError

exitError carries the exit code from CommandFunc to Main()

Field name Field type Comment
ExitCode

int

No comment on field.
Err

error

No comment on field.

moduleInfo

This type doesn't have documentation.

Field name Field type Comment
caddyModuleID

string

No comment on field.
goModule

*debug.Module

No comment on field.
err

error

No comment on field.

pluginPackage

This type doesn't have documentation.

Field name Field type Comment
Version

string

No comment on field.
Path

string

No comment on field.

rootCommandFactory

This type doesn't have documentation.

Field name Field type Comment
constructor

func() *cobra.Command

No comment on field.
options

[]func(*cobra.Command)

No comment on field.

storVal

This type doesn't have documentation.

Field name Field type Comment
StorageRaw

json.RawMessage

No comment on field.

Functions

func AdminAPIRequest

AdminAPIRequest makes an API request according to the CLI flags given, with the given HTTP method and request URI. If body is non-nil, it will be assumed to be Content-Type application/json. The caller should close the response body. Should only be used by Caddy CLI commands which need to interact with a running instance of Caddy via the admin API.

Uses: context.Context, fmt.Errorf, http.Client, http.NewRequest, http.Transport, io.LimitReader, io.ReadAll, maps.Copy, net.Conn, net.Dial.

func Commands

Commands returns a list of commands initialised by RegisterCommand

func DetermineAdminAPIAddress

DetermineAdminAPIAddress determines which admin API endpoint address should be used based on the inputs. By priority: if address is specified, then it is returned; if config is specified, then that config will be used for finding the admin address; if configFile (and configAdapter) are specified, then that config will be loaded to find the admin address; otherwise, the default admin listen address will be returned.

Uses: fmt.Errorf, json.Unmarshal.

func LoadConfig

LoadConfig loads the config from configFile and adapts it using adapterName. If adapterName is specified, configFile must be also. If no configFile is specified, it tries loading a default config file. The lack of a config file is not treated as an error, but false will be returned if there is no config available. It prints any warnings to stderr, and returns the resulting JSON config bytes along with the name of the loaded config file (if any).

func Main

Main implements the main function of the caddy command. Call this if Caddy is to be the main() of your program.

Uses: errors.As, fmt.Printf, os.Args, os.Exit.

func RegisterCommand

RegisterCommand registers the command cmd. cmd.Name must be unique and conform to the following format:

  • lowercase
  • alphanumeric and hyphen characters only
  • cannot start or end with a hyphen
  • hyphen cannot be adjacent to another hyphen

This function panics if the name is already registered, if the name does not meet the described format, or if any of the fields are missing from cmd.

This function should be used in init().

Uses: cobra.Command.

func WrapCommandFuncForCobra

WrapCommandFuncForCobra wraps a Caddy CommandFunc for use in a cobra command's RunE field.

Uses: cobra.Command.

func (*StringSlice) Set

func (*exitError) Error

Uses: fmt.Sprintf.

func (*rootCommandFactory) Build

func (*rootCommandFactory) Use

func (Flags) Bool

Bool returns the boolean representation of the flag given by name. It returns false if the flag is not a boolean type. It panics if the flag is not in the flag set.

Uses: strconv.ParseBool.

func (Flags) Duration

Duration returns the duration representation of the flag given by name. It returns false if the flag is not a duration type. It panics if the flag is not in the flag set.

func (Flags) Float64

Float64 returns the float64 representation of the flag given by name. It returns false if the flag is not a float64 type. It panics if the flag is not in the flag set.

Uses: strconv.ParseFloat.

func (Flags) Int

Int returns the integer representation of the flag given by name. It returns 0 if the flag is not an integer type. It panics if the flag is not in the flag set.

Uses: strconv.IntSize, strconv.ParseInt.

func (Flags) String

String returns the string representation of the flag given by name. It panics if the flag is not in the flag set.

func (StringSlice) String

Uses: strings.Join.

func (pluginPackage) String

Private functions

func caddyCmdToCobra

References: cobra.Command.

func cmdAdaptConfig

References: bytes.Buffer, caddyconfig.GetAdapter, fmt.Errorf, fmt.Println, fmt.Sprintf, json.Indent, os.ReadFile, zap.Int, zap.String.

func cmdAddPackage

References: fmt.Errorf.

func cmdBuildInfo

References: debug.ReadBuildInfo, fmt.Errorf, fmt.Println.

func cmdEnviron

func cmdExportStorage

References: certmagic.Storage, context.Background, errors.Is, errors.New, fmt.Errorf, fmt.Sprintf, fs.ErrNotExist, os.Create, os.File, os.Stdout, tar.Header, tar.NewWriter.

func cmdFmt

References: caddyfile.Format, caddyfile.FormattingDifference, difflib.Common, difflib.Diff, difflib.LeftOnly, difflib.RightOnly, fmt.Errorf, fmt.Print, fmt.Printf, io.ReadAll, os.ReadFile, os.Stdin, os.WriteFile, strings.Join, strings.Split.

func cmdImportStorage

References: certmagic.Storage, context.Background, errors.New, fmt.Errorf, fmt.Println, io.EOF, io.ReadAll, os.File, os.Open, os.Stdin, tar.NewReader.

func cmdListModules

References: fmt.Print, fmt.Printf, fmt.Println.

func cmdReload

References: bytes.NewReader, fmt.Errorf, http.Header, http.MethodPost.

func cmdRemovePackage

References: fmt.Errorf.

func cmdRun

References: errors.Is, fmt.Errorf, fs.ErrNotExist, io.ReadAll, net.Dial, os.Getenv, os.ReadFile, os.Stdin, runtime.GOOS, zap.Error, zap.String.

func cmdStart

References: errors.Is, exec.Command, exec.ErrDot, fmt.Errorf, fmt.Printf, log.Println, net.ErrClosed, net.Listen, os.Args, os.Stderr, os.Stdout, rand.Read.

func cmdStop

References: fmt.Errorf, http.MethodPost, zap.Error.

func cmdUpgrade

References: fmt.Errorf.

func cmdValidateConfig

References: fmt.Errorf, fmt.Println.

func cmdVersion

References: fmt.Println.

func configFileWithRespectToDefault

configFileWithRespectToDefault returns the filename to use for loading the config, based on whether a config file is already specified and a supported default config file exists.

References: caddyconfig.GetAdapter, errors.Is, fmt.Errorf, fs.ErrNotExist, os.Stat.

func determineStorage

determineStorage returns the top-level storage module from the given config. It may return nil even if no error.

References: errors.As, json.SyntaxError, json.Unmarshal, json.Valid.

func downloadBuild

References: fmt.Errorf, fmt.Sprintf, http.Get, json.NewDecoder, zap.String, zap.Strings.

func getModules

References: debug.Module, debug.ReadBuildInfo, fmt.Errorf, reflect.New, reflect.Ptr, reflect.TypeOf, reflect.ValueOf, strings.HasPrefix.

func getPluginPackages

References: fmt.Errorf.

func handleEnvFileFlag

handleEnvFileFlag loads the environment variables from the given --envfile flag if specified. This should be called as early in the command function.

References: fmt.Errorf.

func handlePingbackConn

handlePingbackConn reads from conn and ensures it matches the bytes in expect, or returns an error if it doesn't.

References: bytes.Equal, fmt.Errorf, io.LimitReader, io.ReadAll.

func init

References: cobra.Command.

func isCaddyfile

References: filepath.Base, filepath.Ext, strings.HasPrefix, strings.HasSuffix, strings.ToLower.

func listModules

References: exec.Command, os.Stderr, os.Stdout.

func loadConfigWithLogger

References: caddyconfig.Adapter, caddyconfig.GetAdapter, errors.Is, fmt.Errorf, fmt.Sprintf, fs.ErrNotExist, io.ReadAll, json.Unmarshal, os.ReadFile, os.Stdin, zap.Int, zap.NewNop, zap.String.

func loadEnvFromFile

References: certmagic.FileStorage, filepath.Join, fmt.Errorf, os.LookupEnv, os.Open, os.Setenv.

func newRootCommandFactory

func onlyVersionText

func parseEnvFile

parseEnvFile parses an env file from KEY=VALUE format. It's pretty naive. Limited value quotation is supported, but variable and command expansions are not supported.

References: bufio.NewScanner, fmt.Errorf, strings.Contains, strings.Cut, strings.HasPrefix, strings.HasSuffix, strings.ReplaceAll, strings.TrimPrefix, strings.TrimRight, strings.TrimSpace, strings.TrimSuffix.

func printEnvironment

References: fmt.Printf, fmt.Println, fmt.Sprintf, os.Environ, os.Getwd, runtime.Compiler, runtime.GOARCH, runtime.GOMAXPROCS, runtime.GOOS, runtime.NumCPU, runtime.Version.

func removeCaddyBinary

removeCaddyBinary removes the Caddy binary at the given path.

On any non-Windows OS, this simply calls os.Remove, since they should probably not exhibit any issue with processes deleting themselves.

References: os.Remove.

func setResourceLimits

References: maxprocs.Logger, maxprocs.Set, memlimit.ApplyFallback, memlimit.FromCgroup, memlimit.FromSystem, memlimit.SetGoMemLimitWithOpts, memlimit.WithLogger, memlimit.WithProvider, slog.New, zap.Error, zapslog.NewHandler.

func showVersion

References: exec.Command, os.Stderr, os.Stdout.

func splitModule

References: fmt.Errorf, strings.LastIndex.

func upgradeBuild

References: filepath.EvalSymlinks, fmt.Errorf, fmt.Print, fmt.Println, os.Executable, os.ModeSymlink, os.Rename, os.Stat, runtime.GOARCH, runtime.GOOS, url.Values, zap.Error, zap.String.

func watchConfigFile

watchConfigFile watches the config file at filename for changes and reloads the config if the file was updated. This function blocks indefinitely; it only quits if the poller has errors for long enough time. The filename passed in must be the actual config file used, not one to be discovered. Each second the config files is loaded and parsed into an object and is compared to the last config object that was loaded

References: bytes.Equal, debug.Stack, log.Printf, time.Second, time.Tick, zap.Error, zap.Logger, zap.String.

func writeCaddyBinary

References: fmt.Errorf, io.Copy, os.O_CREATE, os.O_RDWR, os.O_TRUNC, os.OpenFile, zap.String.


Tests

Files: 1. Third party imports: 0. Imports from organisation: 0. Tests: 2. Benchmarks: 0.

Test functions

TestParseEnvFile

References: reflect.DeepEqual, strings.NewReader.

Test_isCaddyfile

References: testing.T.