JaKu01/GoArgParse

A minimal command-line argument parser

★ 0Forks 0GoGitHub ↗Compare

README

GoArgParse

GoArgParse is a minimal command-line argument parser for Go. It supports positional arguments and simple flags (short and long forms). The parser is intentionally small and easy to embed in small CLI programs.

Features

  • Positional arguments with named identifiers
  • Short (-t) and long (--test) flags that expect a following value
  • Simple API: register expected arguments/flags, call Parse(), then Get() values

Installation

As a local module, you can use it directly in your project. From the module root:

# run the example
go run ./example

Or add it as a dependency via its module path (example in go.mod):

go get github.com/Jaku01/GoArgParse

Quick usage

Register expected positional arguments and flags, then parse and retrieve values:

parser := GoArgParse.New()
parser.AddArgument("firstPositional", "string", 0)
parser.AddFlag("t", "test")
parser.AddFlag("w", "word")
parser.AddFlag("g", "go")

if err := parser.Parse(); err != nil {
    panic(err)
}

val, err := parser.Get("firstPositional")
if err != nil {
    panic(err)
}
fmt.Println("positional:", val)

val, _ = parser.Get("test")
fmt.Println("flag test:", val)

Example command-line (matches example/main.go):

# one positional argument plus flags
go run ./example somePositional -t valueForT -w valueForW -g valueForG
# or using long flags
go run ./example somePositional --test valueForT --word valueForW --go valueForG

Behavior and limitations

  • Flags must be registered with AddFlag before parsing. Each flag expects a value immediately after the flag token (no = syntax supported).
  • The parser does not perform type conversion. All values are returned as strings (stored as any).
  • The number of provided positional arguments must exactly match the number of registered positional arguments; otherwise Parse() returns an error.
  • Combined short flags (e.g. -ab) and boolean (no-value) flags are not supported by this minimal implementation.

API

  • New() / NewArgParser(args []string) — create the parser
  • AddArgument(name, type, position) — register positional argument by index
  • AddFlag(shortName, longName) — register a flag that expects a value
  • Parse() — parse the provided os.Args[1:] (or supplied args)
  • Get(name) — retrieve a parsed value by name (returns any, error if not found)

Contributors

JaKu01

Issues