Movatterモバイル変換


[0]ホーム

URL:


Notice  The highest tagged major version isv4.

ff

packagemodule
v3.4.0Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2023 License:Apache-2.0Imports:12Imported by:333

Details

Repository

github.com/peterbourgon/ff

Links

README

ffgo.dev referenceLatest ReleaseBuild Status

ff stands for flags-first, and provides an opinionated way to populate aflag.FlagSet with configuration data fromthe environment. By default, it parses only from the command line, but you canenable parsing from environment variables (lower priority) and/or aconfiguration file (lowest priority).

Building a commandline application in the style ofkubectl ordocker?Considerpackage ffcli,a natural companion to, and extension of, package ff.

Usage

Define a flag.FlagSet in your func main.

import ("flag""os""time""github.com/peterbourgon/ff/v3")func main() {fs := flag.NewFlagSet("my-program", flag.ContinueOnError)var (listenAddr = fs.String("listen-addr", "localhost:8080", "listen address")refresh    = fs.Duration("refresh", 15*time.Second, "refresh interval")debug      = fs.Bool("debug", false, "log debug information")_          = fs.String("config", "", "config file (optional)"))

Then, call ff.Parse instead of fs.Parse.Optionsare available to control parse behavior.

err := ff.Parse(fs, os.Args[1:],ff.WithEnvVarPrefix("MY_PROGRAM"),ff.WithConfigFileFlag("config"),ff.WithConfigFileParser(ff.PlainParser),)

This example will parse flags from the commandline args, just like regularpackage flag, with the highest priority. (The flag's default value will be usedonly if the flag remains unset after parsing all provided sources ofconfiguration.)

Additionally, the example will look in the environment for variables with aMY_PROGRAM prefix. Flag names are capitalized, and separator characters areconverted to underscores. In this case, for example,MY_PROGRAM_LISTEN_ADDRwould match tolisten-addr.

Finally, if a-config file is specified, the example will try to parse itusing the PlainParser, which expects files in this format.

listen-addr localhost:8080refresh 30sdebug true

You could also use the JSONParser, which expects a JSON object.

{"listen-addr": "localhost:8080","refresh": "30s","debug": true}

Or, you could write your own config file parser.

// ConfigFileParser interprets the config file represented by the reader// and calls the set function for each parsed flag pair.type ConfigFileParser func(r io.Reader, set func(name, value string) error) error

Flags and env vars

One common use case is to allow configuration from both flags and env vars.

package mainimport ("flag""fmt""os""github.com/peterbourgon/ff/v3")func main() {fs := flag.NewFlagSet("myservice", flag.ContinueOnError)var (port  = fs.Int("port", 8080, "listen port for server (also via PORT)")debug = fs.Bool("debug", false, "log debug information (also via DEBUG)"))if err := ff.Parse(fs, os.Args[1:], ff.WithEnvVars()); err != nil {fmt.Fprintf(os.Stderr, "error: %v\n", err)os.Exit(1)}fmt.Printf("port %d, debug %v\n", *port, *debug)}
$ env PORT=9090 myserviceport 9090, debug false$ env PORT=9090 DEBUG=1 myservice -port=1234port 1234, debug true

Error handling

In general, you should call flag.NewFlagSet with the flag.ContinueOnError errorhandling strategy, which, somewhat confusingly, is the only way that ff.Parse canreturn errors. (The other strategies terminate the program on error. Rude!) Thisisthe only way to detect certain types of parse failures, in addition tobeing good practice in general.

Documentation

Overview

Package ff is a flags-first helper package for configuring programs.

Runtime configuration must always be specified as commandline flags, so thatthe configuration surface area of a program is self-describing. Package ffprovides an easy way to populate those flags from environment variables andconfig files.

See the README athttps://github.com/peterbourgon/ff for more information.

Index

Constants

This section is empty.

Variables

View Source
var WithEnvVarNoPrefix =WithEnvVars

WithEnvVarNoPrefix is an alias for WithEnvVars.

DEPRECATED: prefer WithEnvVars.

Functions

funcEnvParseradded inv3.3.0

func EnvParser(rio.Reader, set func(name, valuestring)error)error

EnvParser is a parser for .env files. Each line is tokenized on the first `=`character. The first token is interpreted as the flag name, and the secondtoken is interpreted as the value. Both tokens are trimmed of leading andtrailing whitespace. If the value is "double quoted", control characters like`\n` are expanded. Lines beginning with `#` are interpreted as comments.

EnvParser respects WithEnvVarPrefix, e.g. an .env file containing `A_B=c`will set a flag named "b" if Parse is called with WithEnvVarPrefix("A").

funcJSONParser

func JSONParser(rio.Reader, set func(name, valuestring)error)error

JSONParser is a helper function that uses a default JSONParseConfig.

funcParse

func Parse(fs *flag.FlagSet, args []string, options ...Option)error

Parse the flags in the flag set from the provided (presumably commandline)args. Additional options may be provided to have Parse also read from aconfig file, and/or environment variables, in that priority order.

funcPlainParser

func PlainParser(rio.Reader, set func(name, valuestring)error)error

PlainParser is a parser for config files in an extremely simple format. Eachline is tokenized as a single key/value pair. The first whitespace-delimitedtoken in the line is interpreted as the flag name, and all remaining tokensare interpreted as the value. Any leading hyphens on the flag name areignored.

Types

typeConfigFileParser

type ConfigFileParser func(rio.Reader, set func(name, valuestring)error)error

ConfigFileParser interprets the config file represented by the readerand calls the set function for each parsed flag pair.

typeContext

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

Context contains private fields used during parsing.

typeJSONParseConfigadded inv3.4.0

type JSONParseConfig struct {// Delimiter is used when concatenating nested node keys into a flag name.// The default delimiter is ".".Delimiterstring}

JSONParseConfig collects parameters for the JSON config file parser.

func (*JSONParseConfig)Parseadded inv3.4.0

func (pc *JSONParseConfig) Parse(rio.Reader, set func(name, valuestring)error)error

Parse a JSON document from the provided io.Reader, using the provided setfunction to set flag values. Flag names are derived from the node names andtheir key/value pairs.

typeJSONParseError

type JSONParseError struct {Innererror}

JSONParseError wraps all errors originating from the JSONParser.

func (JSONParseError)Error

func (eJSONParseError) Error()string

Error implenents the error interface.

func (JSONParseError)Unwrap

func (eJSONParseError) Unwrap()error

Unwrap implements the errors.Wrapper interface, allowing errors.Is anderrors.As to work with JSONParseErrors.

typeOption

type Option func(*Context)

Option controls some aspect of Parse behavior.

funcWithAllowMissingConfigFile

func WithAllowMissingConfigFile(allowbool)Option

WithAllowMissingConfigFile tells Parse to permit the case where a config fileis specified but doesn't exist.

By default, missing config files cause Parse to fail.

funcWithConfigFile

func WithConfigFile(filenamestring)Option

WithConfigFile tells Parse to read the provided filename as a config file.Requires WithConfigFileParser, and overrides WithConfigFileFlag. Becauseconfig files should generally be user-specifiable, this option should rarelybe used; prefer WithConfigFileFlag.

funcWithConfigFileFlag

func WithConfigFileFlag(flagnamestring)Option

WithConfigFileFlag tells Parse to treat the flag with the given name as aconfig file. Requires WithConfigFileParser, and is overridden byWithConfigFile.

To specify a default config file, provide it as the default value of thecorresponding flag. See also: WithAllowMissingConfigFile.

funcWithConfigFileParser

func WithConfigFileParser(pConfigFileParser)Option

WithConfigFileParser tells Parse how to interpret the config file providedvia WithConfigFile or WithConfigFileFlag.

funcWithConfigFileViaadded inv3.1.0

func WithConfigFileVia(filename *string)Option

WithConfigFileVia tells Parse to read the provided filename as a config file.Requires WithConfigFileParser, and overrides WithConfigFileFlag. This isuseful for sharing a single root level flag for config files among multipleffcli subcommands.

funcWithEnvVarPrefix

func WithEnvVarPrefix(prefixstring)Option

WithEnvVarPrefix is like WithEnvVars, but only considers environmentvariables beginning with the given prefix followed by an underscore. Thatprefix (and underscore) are removed before matching to flag names. Thisoption is also respected by the EnvParser config file parser.

By default, flags are not set from environment variables at all.

funcWithEnvVarSplit

func WithEnvVarSplit(delimiterstring)Option

WithEnvVarSplit tells Parse to split environment variables on the givendelimiter, and to make a call to Set on the corresponding flag with eachsplit token.

funcWithEnvVarsadded inv3.3.0

func WithEnvVars()Option

WithEnvVars tells Parse to set flags from environment variables. Flagnames are matched to environment variables by capitalizing the flag name, andreplacing separator characters like periods or hyphens with underscores.

By default, flags are not set from environment variables at all.

funcWithFilesystemadded inv3.3.2

func WithFilesystem(fsembed.FS)Option

WithFilesystem tells Parse to use the provided filesystem when accessingfiles on disk, for example when reading a config file. By default, the hostfilesystem is used, viaos.Open.

funcWithIgnoreUndefined

func WithIgnoreUndefined(ignorebool)Option

WithIgnoreUndefined tells Parse to ignore undefined flags that it encountersin config files. By default, if Parse encounters an undefined flag in aconfig file, it will return an error. Note that this setting does not applyto undefined flags passed as arguments.

typeStringConversionError

type StringConversionError struct {Value interface{}}

StringConversionError was returned by config file parsers in certain cases.

DEPRECATED: this error is no longer returned by anything.

func (StringConversionError)Error

Error implements the error interface.

Source Files

View all Source files

Directories

PathSynopsis
Package ffcli is for building declarative commandline applications.
Package ffcli is for building declarative commandline applications.
Package fftest provides unit test helpers.
Package fftest provides unit test helpers.
Package fftoml provides a TOML config file paser.
Package fftoml provides a TOML config file paser.
Package ffyaml provides a YAML config file parser.
Package ffyaml provides a YAML config file parser.
Package internal provides private helpers used by various module packages.
Package internal provides private helpers used by various module packages.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp