This is a creation in Article, where the information may have evolved or changed.
When deploying Golang projects, it is unavoidable to set some parameters through the command line, so how do you manipulate command-line arguments in Golang? You can use the OS library and the flag library.
Golang OS library get command line arguments
The OS can use the variable args to get command parameters, OS. Args returns an array of strings, where the first parameter is the execution of the file itself.
package mainimport ( "fmt" "os")func main() { fmt.Println(os.Args)}
$./cmd-user= "Root" after compilation execution
[./cmd-user=root]
This way, it is more time-consuming and cumbersome to package itself. Golang provides a flag library, which makes it easy to manipulate named row parameters and describes the use of flag below.
Golang flag get Command line arguments
Use flag to manipulate command-line arguments, supported in the following format: Flag. INT, Flag. Bool, Flag. The format of a function such as String is the same, the first parameter represents the parameter name, the second parameter represents a default value, and the third parameter represents the usage description and description. Flag. The first parameter of a function such as Stringvar is replaced with the variable address, followed by the parameter and flag. string is the same.
-id=1--id=1-id 1--id 1
It's very convenient.
Execute:
$ go Run flag.go-id=2-name= "Golang" Ok:falseid:2port:: 8080name:golang
Use the-h parameter to view Help for use:
$ go Run Flag.go-h-id=0:id-name= "123": Name-ok=false:is ok-port= ": 8080": http Listen port