goflagbuilder

package module
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2018 License: MIT Imports: 7 Imported by: 0

README

GoFlagBuilder

GoFlagBuilder provides simple tools to construct command line flags and a file parser to manipulate a given structure. It uses reflection to traverse a potentially hierarchical object of structs and maps and install handlers in Go's standard flag package. Constructed parsers scan given documents line by line and apply key/value pairs found.

Constructed flags have the form Foo=..., Bar=..., Obj.Field=... and so on. Maps and exposed fields of structs with primitive types are consumed, so in this case Foo and Bar might be map keys or public struct fields to a primitive. Nested maps and structs are followed, producing dot-notation hierarchical keys such as Obj.Field.

Primitive types understood by GoFlagBuilder include bool, float64, int64, int, string, uint64, and uint. Slices of these primitive types are supported as well.

Primitive fields in the given object and sub-objects must be settable. In general this means structs should be passed in as pointers. Maps may also be set directly.

Build Status GoDoc Go Report Card

Example

A very simple example:

package main

import (
	"flag"
	"log"

	"github.com/BellerophonMobile/goflagbuilder/v2"
)

type server struct {
	Domain string
	Port   int
}

func Example_Simple() {

	myserver := &server{}

	// Construct the flags
	if err := From(myserver); err != nil {
		log.Fatal("Error: " + err.Error())
	}

	// Read from the command line to establish the param
	flag.Parse()

}

This would establish the command line flags "-Port" and "-Domain".

A more elaborate example including nested structures and using the parser is available here. There are also a series of tests in the package outlining exactly what input structures are valid.

Major Release Changelog

  • 2018/08/16: Release 2.0! Simplified package a bit, split config file parsing to its own sub-package. Added a new sub-package to read environment variables.
  • 2014/11/03: Release 1.0! Though not mature at all, we consider GoFlagBuilder to be usable.

License

GoFlagBuilder is provided under the open source MIT license:

The MIT License (MIT)

Copyright (c) 2018 Bellerophon Mobile

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Overview

Package goflagbuilder constructs command line flags and a file parser to manipulate a given structure. It uses reflection to traverse a potentially hierarchical object of structs and maps and install handlers in Go's standard flag package. Constructed parsers scan given documents line by line and apply any key/value pairs found.

Constructed flags have the form Foo=..., Bar=...,Obj.Field=... and so on. Maps and exposed fields of structs with primitive types are consumed, so in this case Foo and Bar might be map keys or public struct fields to a primitive. Nested maps and structs are followed, producing dot-notation hierarchical keys such as Obj.Field.

Primitive types understood by goflagbuilder include bool, float64, int64, int, string, uint64, and uint.

Primitive fields in the given object and sub-objects must be settable. In general this means structs should be passed in as pointers. Maps may also be set directly.

Struct fields may have a "help" struct tag, which will set the usage string for the corresponding flag.

Example (Extended)
package main

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

	"github.com/BellerophonMobile/goflagbuilder/v2/conf"
	"github.com/BellerophonMobile/goflagbuilder/v2/env"
)

type foocomponent struct {
	Domain string
	Port   int
}

type nestedstruct struct {
	Index float64
}

type barcomponent struct {
	Label  string
	Nested *nestedstruct
}

func main() {
	// Create some sample data
	masterconf := make(map[string]interface{})

	masterconf["Foo"] = &foocomponent{
		Domain: "example.com",
		Port:   9999,
	}

	masterconf["Bar"] = &barcomponent{
		Label: "Bar Component",
		Nested: &nestedstruct{
			Index: 79.3,
		},
	}

	// Construct the flags
	if err := From(masterconf); err != nil {
		log.Fatal("CONSTRUCTION ERROR:", err)
	}

	// Read from a config file
	reader := strings.NewReader(`
		# Comment
		Foo.Port = 1234
		Bar.Nested.Index=7.9 # SuccesS!
	`)
	if err := conf.Parse(reader, nil); err != nil {
		log.Fatal("Error:", err)
	}

	// Override settings from the environment
	if err := env.Parse(nil); err != nil {
		log.Fatal("Error:", err)
	}

	// Override settings from the command line
	flag.Parse()

	// Output our data
	fmt.Println(masterconf["Foo"].(*foocomponent).Port)
	fmt.Println(masterconf["Bar"].(*barcomponent).Nested.Index)
}
Output:

1234
7.9
Example (Simple)
package main

import (
	"flag"
	"log"
)

type server struct {
	Domain string
	Port   int
}

func main() {
	myserver := &server{}

	// Construct the flags
	if err := From(myserver); err != nil {
		log.Fatal("Error: " + err.Error())
	}

	// Read from the command line to establish the param
	flag.Parse()
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func From

func From(configuration interface{}) error

From populates the top-level default flags with hierarchical fields from the given object. It simply calls Into() with configuration on a facade of the top-level flag package functions, and returns the resultant Parser or error.

func Into

func Into(flags FlagSet, configuration interface{}) error

Into populates the given flag set with hierarchical fields from the given object. It returns a Parser that may be used to read those same flags from a configuration file.

Types

type FlagSet

type FlagSet interface {
	Var(value flag.Value, name string, usage string)
}

FlagSet is the interface for handling flags identified by GoFlagBuilder. FlagSet objects from Go's standard flag package meet this specification and are the intended primary target, in addition to an internal facade in front of the flag package's top level function, and the GoFlagBuilder Parser.

Directories

Path Synopsis
Package conf provides a simple configuration file format that reads values backed by a flag.FlagSet.
Package conf provides a simple configuration file format that reads values backed by a flag.FlagSet.
Package env provides a means to read environment variables into values backed by a flag.FlagSet.
Package env provides a means to read environment variables into values backed by a flag.FlagSet.

Jump to

Keyboard shortcuts

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