Documentation

Overview

Package flagenv helps with parsing environment into flags.

Example

Code:

package main

import (
	"flag"
	"fmt"
	"htdvisser.dev/exp/flagenv"
	"os"
)

func main() {
	flag.Bool("debug", false, "enable debug mode")

	// Environment: DEBUG=1

	if err := flagenv.NewParser().ParseEnv(flag.CommandLine); err != nil {
		fmt.Fprintln(os.Stderr, err)
		flag.Usage()
		os.Exit(2)
	}

	flag.Parse()
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Parser

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

Parser parses environment into flags.

func NewParser

func NewParser(options ...ParserOption) *Parser

NewParser returns a new Parser with the given options.

func (*Parser) ParseEnv

func (p *Parser) ParseEnv(flagSet *flag.FlagSet) error

ParseEnv parses the environment for the given FlagSet.

type ParserOption

type ParserOption interface {
	// contains filtered or unexported methods
}

ParserOption configures a Parser.

func Filter

func Filter(filter func(key string) bool) ParserOption

Filter returns a ParserOption that makes the Parser only consider flags for which the given filter func returns true.

func Prefixes

func Prefixes(prefixes ...string) ParserOption

Prefixes returns a ParserOption that makes the Parser consider the given prefixes. It replaces configured characters in the prefix with underscores (see also ReplaceWithUnderscore). It does not add an underscore between the prefix and the flag name, so make sure to add an underscore if needed.

Example

Code:

package main

import (
	"flag"
	"fmt"
	"htdvisser.dev/exp/flagenv"
	"os"
)

func main() {
	flag.Bool("debug", false, "enable debug mode")

	// Environment: FOO_DEBUG=1

	if err := flagenv.NewParser(flagenv.Prefixes("FOO_")).ParseEnv(flag.CommandLine); err != nil {
		fmt.Fprintln(os.Stderr, err)
		flag.Usage()
		os.Exit(2)
	}

	flag.Parse()
}

func ReplaceWithUnderscore

func ReplaceWithUnderscore(chars ...string) ParserOption

ReplaceWithUnderscore returns a ParserOption that makes the Parser replace the given characters with underscores.

Source Files