Reputation: 85
I want to create an external function for usage display in Golang, but I don't know how to call the flag variable. This is my actual code:
package main
import (
"flag"
"fmt"
"os"
)
func Usage() {
if ArgSend {
fmt.Printf("Usage: SEND")
flag.PrintDefaults()
os.Exit(0)
} else if ArgTest {
fmt.Printf("Usage: -test")
flag.PrintDefaults()
os.Exit(0)
} else if ArgMacro {
fmt.Printf("Usage: -macro")
os.Exit(0)
} else {
fmt.Printf("Usage of: <-test|-send|-macro>\n")
os.Exit(0)
}
}
func main() {
//defaults variables
ArgTest, ArgSend, ArgMacro := false, false, false
// Args parse
flag.BoolVar(&ArgTest, "-test", false, "run test mode")
flag.BoolVar(&ArgSend, "-send", false, "run send mode")
flag.BoolVar(&ArgMacro, "-macro", false, "run macro mode")
flag.Parse()
Usage()
}
Return this error:
F:\dev\GoLang\gitlab\EasySend\tmp>go run stackoverflow.go -test
# command-line-arguments
.\stackoverflow.go:10:5: undefined: ArgSend
.\stackoverflow.go:15:12: undefined: ArgTest
.\stackoverflow.go:20:12: undefined: ArgMacro
How can I check flag parse if ArgSend is true/false?
Upvotes: 0
Views: 9137
Reputation: 6079
A couple of things wrong in your example:
There is a good example here: golang flags example and you should check godocs on flags particularly for default behavior and custom usage functions, if you have trouble modifying the example then ask again here
Updated: Sorry, as Peter pointed to in comments my answer is a little muddled and incorrect.
To Clarify, in the example provided in the "golang flags example" link given flag.Bool is used. When using flag.Bool a pointer is returned.
In the Question you use flag.BoolVar which allows you to reference a bool value. your use of flag.BoolVar in the question is in fact correct.
So all you need to do is address the scoping issue, not really clear what you are trying to do with your Usage but here is a working example that should clarify:
Note: in this example the flag vars could have stayed inside main as they are not required in the Usage function
package main
import (
"flag"
"fmt"
"os"
)
func Usage() {
// custom usage (help) output here if needed
fmt.Println("")
fmt.Println("Application Flags:")
flag.PrintDefaults()
fmt.Println("")
}
var ArgTest, ArgSend, ArgMacro bool
func main() {
// Args parse
flag.BoolVar(&ArgTest, "test", false, "run test mode")
flag.BoolVar(&ArgSend, "send", false, "run send mode")
flag.BoolVar(&ArgMacro, "macro", false, "run macro mode")
flag.Parse()
// assign custom usage function (will be shown by default if -h or --help flag is passed)
flag.Usage = Usage
// if no flags print usage (not default behaviour)
if len(os.Args) == 1 {
Usage()
}
fmt.Printf("ArgTest val: %t\n", ArgTest)
fmt.Printf("ArgSend val: %t\n", ArgSend)
fmt.Printf("ArgMacro val: %t\n", ArgMacro)
}
Upvotes: 1