structflag

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2019 License: MIT Imports: 5 Imported by: 0

README

structflag - Flatten a go struct into flag values

GoDoc

This package provides a simple method to convert nested go structs into a flat map containing reference to the values in the struct.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type StructToFlagsConverter

type StructToFlagsConverter struct {
	// WordSeparator is used to separate child struct fields from parent structs.
	WordSeparator string
	// DescriptionTag is used to query struct tag to generate description for values.
	DescriptionTag string
	// NameConverterFunc is used to change field names before adding them to output.
	NameConverterFunc func(string) string
}

StructToFlagsConverter is useful for converting all fields in a struct to a flat map containing flag package compatible values.

func NewStructToFlagsConverter

func NewStructToFlagsConverter() *StructToFlagsConverter

NewStructToFlagsConverter returns a new converter that uses "-" for separating words, does not change field names and extracts description from "description" struct tag. The returned instance can be customized by changing fields. It can be used with flags package like this:

package main

import (
	"flag"

	"github.com/surajbarkale/structflag"
)

type extra struct {
	WrapLines bool
	Pages     []int
}
type args struct {
	Debug     bool    `description:"Enable debug mode"`
	InputFile *string `description:"Name of input file"`
	Extra     *extra
}

func main() {
	a := &args{Debug: true}
	for name, value := range structflag.DefaultStructToFlagsConverter.Convert(&a) {
		flag.Var(value, name, value.Description())
	}
	flag.PrintDefaults()
}

This program should print output:

-Debug
	Enable debug mode (default true)
-Extra-Pages

-Extra-WrapLines
		(default false)
-InputFile
	Name of input file

func (*StructToFlagsConverter) Convert

func (thiz *StructToFlagsConverter) Convert(input interface{}) map[string]Value

Convert generates the flag values compatible with the structure. You must pass a pointer to the value

type Value

type Value interface {
	flag.Getter
	Description() string
}

Value adds ability to get description for flag.Value

func NewReflectedValue

func NewReflectedValue(target reflect.Value, description string) Value

NewReflectedValue creates a new flag value that converts string into the given reflected value. Bool, Int, UInt and Float values are converted using functions from strconv package. For String values, input can be either a bare string or a valid JSON string. Arrays, maps and structures must be specified using JSON syntax.

Jump to

Keyboard shortcuts

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