[Golang] Read Command-line Arguments Example
On *nix system we often run the program with arguments. How do we get the command-line arguments in Go program? Please see the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // http://golang.org/pkg/flag/ package main import ( "flag" "fmt" ) var isProductonServer = flag.Bool("production", false, "if run in production mode") func main() { flag.Parse() fmt.Println("Production Mode:", *isProductonServer) } |
In the example we define a boolean flag production, which indicates whether the program runs in production mode. The default value is false, and the usage string is if run in production mode.
Now we build our program cmd.go by:
$ go build cmd.go
A binary program named cmd will be under the same directory. Try to run the binary without arguments:
$ ./cmd
Production Mode: false
Next run the binary with -production=true:
$ ./cmd -production=true
Production Mode: true
We can also read usage of the program by:
$ ./cmd -h
Usage of ./cmd:
-production=false: if run in production mode
You can also read usage by --help:
$ ./cmd --help
Usage of ./cmd:
-production=false: if run in production mode
There is another example for reading argument as string. See [3].
Source code tested on: Ubuntu Linux 14.10, Go 1.4.
References:
[1] | flag - The Go Programming Language |
[2] | Go by Example: Command-Line Flags |
[3] | [Golang] Parse Command Line Arguments - String Variable |
[4] | Flags-first package for configuration : golang |