Go binding configuration and command flag made easy✨✨

Overview

go-binder

License: MIT Go Reference

Binding configuration and command flag made easy!

You can use multiple keys tag to simplify the look like this (supported feature**):

// single tag key
type MyConfig struct {
    Token string `json:token_json" xml:"token_xml" arg:"token" env:"token" environ:"TOKEN"`
}
// multiple tag keys
type MyConfig struct {
    Token string `json xml bson yaml toml arg env:"token" environ:"TOKEN"`
}

Below is default mapping implementation of binder.RegisterCmdArgs = defaultRegisterCmdArgsFlagStd that use standard golang flag package to perform command flag.

The is a placeholder for parent key, binder.BindArgs(Loaded, "my") this case will be replaced with my, if there's field with type struct in the component, it'll be replaced to my..

Tag Go Code Description
arg:"token" flag.StringVar(val, ".token", *val, argUsage) Used for binding flag with contextual key
argx:"token" flag.StringVar(val, "token", *val, argUsage) Used for binding flag
bind:"log" No equivalent Used for binder to differ struct parent sub context .log.
env:"token" os env(".token") Used for binding to environment variable with contextual key
environ:"token" os env("token") Used for binding to environment
usage:"" Used as argUsage Description for flag

Other:

  • arg and argx (dedicated) basically has same function.
  • env and environ (dedicated) basically has same function.
  • Currently you can't have dedicated key for configuration because the way it parsed is from Unmarshaller that results in map[string]interface{}, but this definitely possible to implement.

More thing you can learn from the example below.

Example

package main

import (
    "flag"
    "fmt"
    "os"

    "github.com/ii64/go-binder/binder"
    "github.com/pkg/errors"
)

type MyConfig struct {
    Token string `json xml bson yaml toml arg:"token,omitempty" env:"TOKEN" environ:"TOKEN"`
    Count int    `json xml bson yaml toml arg:"count,omitempty" env:"COUNT" usage:"this is the usage"`

    Ktes *int
    Sub  **struct {
        Hello    *string
        SubOfSub struct {
            InSub **bool
        }
        PtrOfSub *struct {
            YourName **string `json xml bson yaml toml bind:"your_name,omitempty" env:"COUNT" usage:"this is the usage"`
        }
    }
    Log struct {
        SubLog       int
        Directory    string
        Filename     string `json xml bson yaml toml arg:"filename" env:"FILENAME"`
        DedicatedArg string `json xml bson yaml toml argx:"dedicatedArg" env:"DEDICATED_ARG"`
    } `json xml bson yaml toml arg env bind:"log"`
}
var (
    configFile = os    env("CONFIG_FILE")
    Loaded     *MyConfig
)

func registerToBinder() {
    Loaded = &MyConfig{
        Token: "some default value",
        Count: 121,
    }
    binder.BindArgsConf(Loaded, "my")
}

func main() {
    var err error
    if configFile == "" {
        configFile = "config.json"
    }
    binder.LoadConfig = binder.LoadConfigJSON(configFile)
    binder.SaveConfig = binder.SaveConfigJSON(configFile)
    binder.SaveOnClose = true
    // register component to binder
    registerToBinder()
    // perform binding
    if err = binder.Init(); err != nil {
        if errors.Is(err, os.ErrNotExist) {
            if err = binder.Save(); err != nil {
                panic(err)
            }
        } else {
            panic(err)
        }
    }
    flag.Parse()
    // reflect back to component
    binder.In()
    defer binder.Close()

    // runtime
    fmt.Printf("%+#v\n", Loaded)
}

Output help:

$ main -h
Usage of main:
  -dedicatedArg string

  -my.Sub.Hello string

  -my.count int
        this is the usage (default 121)
  -my.log.Directory string

  -my.log.filename string

  -my.token string
         (default "some default value")

Output JSON:

{
    "my": {
        "token": "some default value",
        "count": 121,
        "Ktes": 0,
        "Sub": {
            "Hello": "",
            "SubOfSub": {
                "InSub": false
            },
            "PtrOfSub": {
                "your_name": ""
            }
        },
        "log": {
            "SubLog": 0,
            "Directory": "",
            "filename": "",
            "dedicatedArg": ""
        }
    }
}

Output TOML:

[my]
  token = "some default value"
  count = 121
  Ktes = 0
  [my.Sub]
    Hello = ""
    [my.Sub.SubOfSub]
      InSub = false
    [my.Sub.PtrOfSub]
      your_name = ""
  [my.log]
    SubLog = 0
    Directory = ""
    filename = ""
    dedicatedArg = ""

Output YAML:

my:
  token: some default value
  count: 121
  ktes: 0
  sub:
    hello: ""
    subofsub:
      insub: false
    ptrofsub:
      your_name: ""
  log:
    sublog: 0
    directory: ""
    filename: ""
    dedicatedArg: ""

Note

Contributions are welcome

**) Reverted feature as from 1.16 but found it useful

License

License: MIT

Issues
  • Improve tag parsing

    Improve tag parsing

    fix crash when tag is just 'json' fix return value where tag's argument was assigned to ALL previous tags.

    For example, `json xml bson yaml toml arg:"token,omitempty" env:"token"` would return:

    {
        "json": "token,omitempty",
        "xml": "token,omitempty",
        "bson": "token,omitempty",
        "yaml": "token,omitempty",
        "toml": "token,omitempty",
        "arg": "token,omitempty",
        "env": "token",
    }
    
    opened by zdima 1
Owner
Ii64人
A Student
Ii64人
CLI - A package for building command line app with go

Command line interface Screenshot Key features Lightweight and easy to use. Defines flag by tag, e.g. flag name(short or/and long), description, defau

王仕晋 607 Sep 20, 2021
CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser

CONTRIBUTIONS ONLY What does this mean? I do not have time to fix issues myself. The only way fixes or new features will be added is by people submitt

Alec Thomas 3.1k Sep 15, 2021
Flag is a simple but powerful command line option parsing library for Go support infinite level subcommand

Flag Flag is a simple but powerful commandline flag parsing library for Go. Documentation Documentation can be found at Godoc Supported features bool

null 116 Sep 6, 2021
A versatile library for building CLI applications in Go

mow.cli Package cli provides a framework to build command line applications in Go with most of the burden of arguments parsing and validation placed o

Jawher Moussa 748 Sep 5, 2021
Idiomatic Go input parsing with subcommands, positional values, and flags at any position. No required project or package layout and no external dependencies.

Sensible and fast command-line flag parsing with excellent support for subcommands and positional values. Flags can be at any position. Flaggy has no

Eric Greer 733 Sep 6, 2021
Go binding configuration and command flag made easy✨✨

✨ Binding configuration and command flag made easy! ✨ You can use multiple keys tag to simplify the look like this (supported feature**): // single ta

Ii64人 10 Aug 5, 2021
Kong is a command-line parser for Go

Kong is a command-line parser for Go Introduction Help Help as a user of a Kong application Defining help in Kong Command handling Switch on the comma

Alec Thomas 663 Sep 25, 2021
textnote is a command line tool for quickly creating and managing daily plain text notes.

textnote is a command line tool for quickly creating and managing daily plain text notes. It is designed for ease of use to encourage the practice of daily, organized note taking. textnote intentionally facilitates only the management (creation, opening, organizing, and consolidated archiving) of notes, following the philosophy that notes are best written in a text editor and not via a CLI.

Daniel Kaslovsky 148 Sep 5, 2021
The standard library flag package with its missing features

cmd Package cmd is a minimalistic library that enables easy sub commands with the standard flag library. This library extends the standard library fla

Eyal Posener 34 Sep 2, 2021
Generate flags by parsing structures

Flags based on structures. The sflags package uses structs, reflection and struct field tags to allow you specify command line options. It supports di

null 129 Sep 13, 2021
Fully featured Go (golang) command line option parser with built-in auto-completion support.

go-getoptions Go option parser inspired on the flexibility of Perl’s GetOpt::Long. Table of Contents Quick overview Examples Simple script Program wit

David Gamba 37 Sep 16, 2021
git-xargs is a command-line tool (CLI) for making updates across multiple Github repositories with a single command.

Table of contents Introduction Reference Contributing Introduction Overview git-xargs is a command-line tool (CLI) for making updates across multiple

Gruntwork 489 Sep 24, 2021
Another CLI framework for Go. It works on my machine.

Command line interface framework Go framework for rapid command line application development

Ulrich Kautz 108 May 24, 2021
kubeaudit helps you audit your Kubernetes clusters against common security controls

kubeaudit helps you audit your Kubernetes clusters against common security controls

Shopify 1k Sep 24, 2021
Argparse for golang. Just because `flag` sucks

Golang argparse Let's be honest -- Go's standard command line arguments parser flag terribly sucks. It cannot come anywhere close to the Python's argp

Alexey Kamenskiy 363 Sep 23, 2021
:cherry_blossom: A command-line fuzzy finder

fzf is a general-purpose command-line fuzzy finder. It's an interactive Unix filter for command-line that can be used with any list; files, command hi

Junegunn Choi 39.3k Sep 24, 2021
sg is the CLI tool that Sourcegraph developers can use to develop Sourcegraph.

sg is the CLI tool that Sourcegraph developers can use to develop Sourcegraph.

Sourcegraph 25 Sep 14, 2021
Query, update and convert data structures from the command line. Comparable to jq/yq but supports JSON, TOML, YAML, XML and CSV with zero runtime dependencies.

dasel Dasel (short for data-selector) allows you to query and modify data structures using selector strings. Comparable to jq / yq, but supports JSON,

Tom Wright 1.6k Sep 24, 2021
A rich tool for parsing flags and values in pure Golang

A rich tool for parsing flags and values in pure Golang. No additional library is required and you can use everywhere.

ALi.w 13 Jun 20, 2021