util

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2020 License: Apache-2.0 Imports: 21 Imported by: 15

Documentation

Overview

Package util contains utility functions for Panto.

Option

Use Option to define configuration options for your program. This allows quick and consistent bindings for configuration file options, flags and environment variables.

Start by configuring an option for your program.

var nameOption = util.Option{
	Name:    "name",
	Default: "World",
	Usage:   "the name of the person you wish to greet",
	Env:     "HELLO_NAME",
	Flag:    "name",
	Short:   "n",
}

At init time, add the option to your program.

func init() {
	// Add name option
	if err := util.AddOption(nameOption, pflag.CommandLine); err != nil {
		panic(err)
	}
}

When running your executable, bind your option and parse the flags.

func main() {
	// Bind env var and flag to viper
	util.BindOption(nameOption, pflag.CommandLine)

	// Parse command-line flags
	pflag.Parse()

	// Read configuration file
	viper.SetConfigName("hello")
	viper.AddConfigPath(".")
	viper.SetConfigType("yaml")
	viper.ReadInConfig()

	fmt.Println("Hello", viper.GetString(nameOption.Name))
}

Example usage:

$ ./hello
Hello World

$ ./hello -h
Usage of ./hello:
  -n, --name string   the name of the person you wish to greet (default "World")
pflag: help requested

$ ./hello --name="Steve"
Hello Steve

$ HELLO_NAME="Brooklyn" ./hello
Hello Brooklyn

$ HELLO_NAME="Brooklyn" ./hello --name="Steve"
Hello Steve

$ echo 'name: "Sunshine"' > hello.yaml
$ ./hello
Hello Sunshine

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddOption

func AddOption(opt Option, flags *pflag.FlagSet) error

AddOption adds an option to the program. If opt.Default is set, it sets the default value in viper. If flags is not nil and opt.Flag is set, the option is configuration-only. If opt.Name is empty, and opt.Flag is set, the option is flag-only. Use this when setting up flags and configuration options, typically at init time.

func AddressHasPort added in v0.2.0

func AddressHasPort(address string) bool

AddressHasPort markes sure the provided address has the host:port format

func Base64Decode

func Base64Decode(s string) (u uuid.UUID, err error)

Base64Decode decodes a url-safe base64 string with no padding to a UUID.

func Base64Encode

func Base64Encode(u uuid.UUID) string

Base64Encode encodes a UUID to a url-safe base64 string with no padding.

func BindOption

func BindOption(opt Option, flags *pflag.FlagSet) error

BindOption binds the environment variables and flags to viper. Use this when running the executable, typically at the start of a cobra command.

func Contains

func Contains(l []string, s string) bool

Contains returns true if a string slice contains the given string, false otherwise

func ExpandAbs added in v0.2.0

func ExpandAbs(path string) (string, error)

ExpandAbs expands ~ components in paths, if any, then calls filepath.Abs, returning an absolute path with no ~ components. If path is empty, just return an empty path.

func GetJoinedMetadata added in v0.9.0

func GetJoinedMetadata(md metadata.MD, k string) (string, bool)

GetJoinedMetadata extracts a value from gRPC metadata, for a (case-insensitive) key, if it exists, and joins all the values in one string. Returns ("", false) if the key does not exist.

func LiveTest

func LiveTest(t *testing.T) bool

LiveTest tests if the environment variable for live testing is set. "Live" testing means that the unit tests will rely on an existing instance of the TSDB at localhost:8086

func MarshalJSON added in v0.3.0

func MarshalJSON(in map[string]interface{}) ([]byte, error)

MarshalJSON takes a Go map and returns a JSON string with `null` values filtered out as undefined

func NextPageToken

func NextPageToken(req proto.Message, a ...interface{}) (string, error)

NextPageToken creates a `next_page_token` for a paginated response from a request, and adds additional data. `req` must be a protobuf message containing a `PageToken` field. Returns a URL-safe base64 encoded string.

func UnmarshalAndValidateParameters added in v0.3.0

func UnmarshalAndValidateParameters(in []byte, ref []Parameter) (map[string]interface{}, error)

UnmarshalAndValidateParameters takes a JSON key-value map, makes sure the list of parameters complies with the schema, and returns a Go map with resolved typed. `null` values are treated as undefined

func UnmarshalJSON added in v0.3.0

func UnmarshalJSON(data []byte, v interface{}) error

UnmarshalJSON is a thin wrapper around "encoding/json".Decoder.Decode, that configures the decoder to use json.Number instead of forcing conversion to float64.

func ValidatePageToken

func ValidatePageToken(token string, req proto.Message, a ...interface{}) (bool, error)

ValidatePageToken validates a page token against a request. It decodes the given token, verifies it matches the request, and stores the extra data into successive arguments. Arguments must be pointers. Behavior is undefined if the arguments do not match the encoded buffer. Returns true if the token matches the request.

Types

type Hash added in v0.9.0

type Hash [32]byte

Hash is the type for hashed password

func HashPassword added in v0.9.0

func HashPassword(password string, salt Salt) (hash Hash, err error)

HashPassword encodes a password using argon2

type Option

type Option struct {
	Name    string      // The name of the option. Supports viper nesting using dot '.' in names.
	Default interface{} // The default value of the option. Mandatory, as the default value is used to infer the option type.
	Usage   string      // A description of the option.

	Flag  string // The name of the command-line flag.
	Short string // A shorthand for the flag (optional).

	Env string // An environment variable to bind this option to (optional).

	Optional bool // True when the option is not required (by default, an option is required)
}

Option describes a confifuration option for the program.

type Parameter added in v0.3.0

type Parameter struct {
	Name        string      `json:"name"`
	Type        string      `json:"type"`
	Description string      `json:"description"`
	Mandatory   bool        `json:"mandatory"`
	Placeholder interface{} `json:"placeholder"`
	Default     interface{} `json:"default"`
}

Parameter is a description of a field in the configuration JSONs

func (*Parameter) UnmarshalJSON added in v0.3.0

func (p *Parameter) UnmarshalJSON(b []byte) error

UnmarshalJSON is a custom unmarshal function for Parameter

type ParameterValidationError added in v0.3.0

type ParameterValidationError struct {
	Errors []ParameterValidationErrorDetails
}

ParameterValidationError is an error returned by UnmarshalAndValidateParameters if one or more parameters failed to validate.

func (*ParameterValidationError) Error added in v0.3.0

func (err *ParameterValidationError) Error() string

type ParameterValidationErrorDetails added in v0.3.0

type ParameterValidationErrorDetails struct {
	Name    string // Parameter name
	Message string // Parameter-related error message
}

ParameterValidationErrorDetails is a validation error for a single Parameter

type Salt added in v0.9.0

type Salt [32]byte

Salt is the type for hashed password salt

func GenerateSalt added in v0.9.0

func GenerateSalt() (Salt, error)

GenerateSalt creates a new salt to hash a password

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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