Golang : Print how to use flag for your application example
Just a short tutorial on how to usage flag
package to check for the number of flag arguments require by your application. If the flag is misspelled or has missing parameters, print out the application usage instruction.
Here you go!
package main
import (
"flag"
"fmt"
"os"
)
func usage() {
fmt.Printf("usage : %s -inputValue=123\n", os.Args[0])
os.Exit(0)
}
var input = flag.String("inputValue", "", "String value to display")
func main() {
flag.Usage = usage
flag.Parse()
//fmt.Println("Args : ", flag.NFlag())
if flag.NFlag() == 0 {
usage()
os.Exit(-1)
}
fmt.Println("String value to display is : ", *input)
}
Sample output:
$ ./usageflags -inputValue=xzyy 123
String value to display is : xzyy
$ ./usageflags -inputValue=" asjjdd 123 adsqd"
String value to display is : asjjdd 123 adsqd
$ ./usageflags -inputValue=2121121 -fff
flag provided but not defined: -fff
$ ./usageflags
usage : ./usageflags -inputValue=123
If you prefer not to use the flag
package, os
package can do the same as well, but os
package can only handle direct parameter/arguments. Here is a code fragment on how to use os
package to display your application usage instruction.
if len(os.Args) <= 2 {
fmt.Printf("USAGE : %s <target_directory> <target_filename or part of filename> \n", os.Args[0])
os.Exit(0)
}
targetDirectory := os.Args[1] // get the target directory
fileName := os.Args[2:] // to handle wildcard such as filename*.go
Happy coding!
Reference:
https://www.socketloop.com/references/golang-flag-nflag-function-example
See also : Golang : Find files by name - cross platform example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+20k Golang : How to get struct tag and use field name to retrieve data?
+27.3k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+16.3k Golang : Execute terminal command to remote machine example
+8.5k Golang : Another camera capture GUI application with GTK and OpenCV
+7.3k Linux : How to fix Brother HL-1110 printing blank page problem
+6.9k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+9.6k Random number generation with crypto/rand in Go
+9.2k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+6.6k Golang : Reverse by word
+10k Golang : Test a slice of integers for odd and even numbers
+6.6k Golang : Experimental emojis or emoticons icons programming language
+10.8k Golang : Sieve of Eratosthenes algorithm