Go binding configuration and command flag made easy✨✨

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

Owner
Similar Resources

Git Add Commit - Commit made easy

 Git Add Commit - Commit made easy

Git Add Commit Commit made easy Installation Download the latest release and put the binary in your $PATH Homebrew: brew tap rawnly/tap brew i

Jul 26, 2022

A command launcher 🚀 made with ❤️

Command Launcher A command launcher 🚀 made with ❤️ Why a command launcher? At Criteo, we have many teams who provides command line applications for d

Dec 18, 2022

Substitute environment variables from command line for template driven configuration files.

Substitute  environment variables from command line for template driven configuration files.

Substitute Variables (subvars) is a small utility which provides a way to render any Go templates from command line recognizing the object being passed in and drawing attributes from the object to create wanted text. It is very useful for template driven configuration files.

Jun 3, 2022

Simple and easy to use command line application written in Go for cleaning unnecessary XCode files.

xcclear Say hello to a few extra gigabytes of space on your Mac with xcclear, a simple and easy to use command line application written in Go for clea

Dec 16, 2022

A go library for easy configure and run command chains. Such like pipelining in unix shells.

go-command-chain A go library for easy configure and run command chains. Such like pipelining in unix shells. Example cat log_file.txt | grep error |

Dec 27, 2022

It is an easy and fast tool to install your packages with just one command.

Trouxa It is an easy and fast tool to install your packages with just one command. What means "Trouxa"? In portuguese, Trouxa means something like a "

Sep 29, 2022

Portal is a quick and easy command-line file transfer utility from any computer to another 🖥️ 🌌 💻

Portal is a quick and easy command-line file transfer utility from any computer to another 🖥️ 🌌 💻

Portal is a quick and easy command-line file transfer utility from any computer to another 🖥️ 🌌 💻

Dec 27, 2022

A command line tool that builds and (re)starts your web application everytime you save a Go or template fileA command line tool that builds and (re)starts your web application everytime you save a Go or template file

# Fresh Fresh is a command line tool that builds and (re)starts your web application everytime you save a Go or template file. If the web framework yo

Nov 22, 2021

Brigodier is a command parser & dispatcher, designed and developed for command lines such as for Discord bots or Minecraft chat commands. It is a complete port from Mojang's "brigadier" into Go.

brigodier Brigodier is a command parser & dispatcher, designed and developed to provide a simple and flexible command framework. It can be used in man

Dec 15, 2022
Comments
  • 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",
    }
    
Golang library with POSIX-compliant command-line UI (CLI) and Hierarchical-configuration. Better substitute for stdlib flag.
Golang library with POSIX-compliant command-line UI (CLI) and Hierarchical-configuration. Better substitute for stdlib flag.

cmdr cmdr is a POSIX-compliant, command-line UI (CLI) library in Golang. It is a getopt-like parser of command-line options, be compatible with the ge

Oct 28, 2022
mass-binding-target is a command line tool for generating binding target list by search plot files from disk.

mass-binding-target mass-binding-target is a command line tool for generating binding target list by search plot files from disk. Build Go 1.13 or new

Nov 5, 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

Dec 29, 2022
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

Sep 26, 2022
Docli - Command-line interfaces made easy
Docli - Command-line interfaces made easy

Docli Docli is a declarative language for describing command-line interfaces in Go programs. It cuts down the boilerplate to the bare minimum, so you

Aug 20, 2022
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

Dec 28, 2022
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

Oct 4, 2022
A collection of CLI argument types for the Go `flag` package.

flagvar A collection of CLI argument types for the flag package. import "github.com/sgreben/flagvar" Or just copy & paste what you need. It's public d

Sep 26, 2022
Drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.

Description pflag is a drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags. pflag is compatible with the GNU extensions to

Dec 30, 2022
Utility CLI to convert Spring Boot Yaml configuration into external configuration

boot-config-export Utility CLI to convert Spring Boot Yaml configuration into external configuration (as environment variables). The variables are tra

Nov 17, 2021