flago

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2020 License: MIT Imports: 5 Imported by: 1

README

PkgGoDev Go Report Card

Flago

Super simple package for binding command-line flags to your struct.

Installation

go get github.com/KimMachineGun/flago

Example

Playground

package main

import (
	"flag"
	"fmt"
	"log"
	"strings"

	"github.com/KimMachineGun/flago"
)

type Flags struct {
	A string                `flago:"a,usage of a"`
	B int                   `flago:"b,usage of b"`
	C CommaSeparatedStrings `flago:"c,usage of c"`
}

// CommaSeparatedStrings implements flag.Value.
type CommaSeparatedStrings []string

func (s *CommaSeparatedStrings) String() string {
	return strings.Join(*s, ",")
}

func (s *CommaSeparatedStrings) Set(v string) error {
	*s = strings.Split(v, ",")
	return nil
}

// go run main.go -b=360 -c=Hello,World
func main() {
	// set default values
	flags := Flags{
		A: "AB",
		B: 180,
		C: []string{"Foo", "Bar"},
	}

	err := flago.Bind(flag.CommandLine, &flags)
	if err != nil {
		log.Fatalln(err)
	}

	flag.PrintDefaults()
	// Output:
	//  -a string
	//        usage of a (default "AB")
	//  -b int
	//        usage of b (default 180)
	//  -c value
	//        usage of c (default Foo,Bar)

	flag.Parse()

	fmt.Println(flags)
	// Output: {AB 360 [Hello World]}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bind

func Bind(fs *flag.FlagSet, v interface{}) error

Bind defines flags based on the struct field tags and binds flags to the corresponding fields.

The name of field tag is 'flago' and its value is used to specify the name and usage of the flag.

If the field is a struct, flago will parse it recursively, and its field tag will be used as a prefix of the flags defined by itself.

Supported Field Types:

  • string
  • bool
  • int
  • int64
  • uint
  • uint64
  • float64
  • time.Duration
  • flag.Value

Examples:

// Name defines a 'name' flag, and its usage is skipped.
Name string `flago:"name"`

// Age defines a 'name' flag, and its usage is 'the age of gopher'.
// The name and usage specified in field tag are separated by comma.
Age int `flago:"age,the age of gopher"`

Types

type InvalidBindError

type InvalidBindError struct {
	Type reflect.Type
}

An InvalidBindError describes an invalid argument passed to Bind.

func (*InvalidBindError) Error

func (e *InvalidBindError) Error() string

Jump to

Keyboard shortcuts

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