Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requiring a positional argument with go-flags

I am writing a CLI tool in go and have chosen github.com/jessevdk/go-flags for the CLI arg parsing. I am trying to figure out the best way to make a positional arg mandatory. Currently, I have the following:

func main() {
    args, err := flags.Parse(&opts)
    if err != nil {
        panic(err)
    }

    if len(args) < 1 {
        panic("An s3 bucket is required")
    }
}

This works, but it doesn't result in help output being displayed, as would be the case with a flag being marked "required:true". Is there a way to replicate that behavior by manually calling a "print help" function or setting a required number of positional arguments?

like image 784
jordanm Avatar asked Dec 05 '25 17:12

jordanm


1 Answers

Would using os.Args help? Eg:

package main

import (
    "fmt"
    "os"
)

const Usage = `Usage:
%s one two
`

func main() {

    if len(os.Args) != 3 {
        fmt.Printf(Usage, os.Args[0])
        os.Exit(-1)
    }

    //run program
}

os.Args hold the command-line arguments, starting with the program name.

https://play.golang.org/p/Le9EMxmw9k

like image 119
Mark Avatar answered Dec 07 '25 15:12

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!