structflag

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2022 License: MIT Imports: 7 Imported by: 0

README

structflag

define flagset with struct and reflect

features

  • Builds pflag.FlagSet by struct definition
  • Supports only a single use case (shorthand of flag package)
  • Nested structure support (example)
  • Default envvar support

install

(This package is currently under development (wip))

$ go get -v github.com/podhmo/structflag

how to use

package main

import (
	"fmt"
	"os"

	"github.com/podhmo/structflag"
)

type Options struct {
	Name    string `flag:"name" help:"name of greeting"`
	Verbose bool   `flag:"verbose" short:"v"`
}

func main() {
	options := &Options{Name: "foo"} // default value

	b := structflag.NewBuilder()
	b.Name = "hello"
	b.EnvPrefix = "X_"

	fs := b.Build(options)
	fs.Parse(os.Args[1:])

	fmt.Printf("parsed: %#+v\n", options)

}

default help message.

$ hello --help
Usage of hello:
      --name string   ENV: X_NAME	name of greeting (default "foo")
  -v, --verbose       ENV: X_VERBOSE	-
pflag: help requested
exit status 2

run it.

$ hello --verbose
parsed: &main.Options{Name:"foo", Verbose:true}
$ hello -v --name bar
parsed: &main.Options{Name:"name", Verbose:true}

# envvar support
$ X_NAME=bar hello -v
parsed: &main.Options{Name:"bar", Verbose:true}

see also ./examples

inspired by

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Binder added in v0.1.1

type Binder struct {
	*Config
}

func (*Binder) Bind added in v0.1.1

func (b *Binder) Bind(fs *flag.FlagSet, o interface{}) func(*flag.FlagSet) error

type Builder

type Builder struct {
	Name string
	*Config
}

func NewBuilder

func NewBuilder() *Builder

func (*Builder) Build

func (b *Builder) Build(o interface{}) *FlagSet

type Config added in v0.1.1

type Config struct {
	HandlingMode flag.ErrorHandling

	EnvvarSupport bool
	EnvPrefix     string
	EnvNameFunc   func(string) string

	FlagnameTags []string
	FlagNameFunc func(string) string

	ShorthandTag string
	HelpTextTag  string
}

func DefaultConfig added in v0.1.1

func DefaultConfig() *Config

type FlagSet

type FlagSet struct {
	*flag.FlagSet
	Binder *Binder
}

func (*FlagSet) Parse

func (fs *FlagSet) Parse(args []string) error

type HasHelpText added in v0.0.2

type HasHelpText interface {
	HelpText() string
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL