In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to use the flag package on the command line of Golang development. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.
1. Overview of command line tools
Daily command line operation, corresponding to many command line tools is a necessary tool to improve productivity, the mouse can make it easier for users to use and reduce the cost of user learning. For developers, keyboard operation mode can significantly improve productivity, and in some professional tools, the extensive use of shortcut keys instead of tedious mouse operations can make developers more focused on their work and improve efficiency, because keyboard operation mode is more likely to produce muscle memory.
Take Chestnut: our business research and development, a few years ago under our strong push (forced) to use git as version control, began to use the graphical "Little Turtle" tool. After several subsequent problems that are troublesome to solve, it is recommended to use the native git command line. Today, using the git command line to manipulate version control can be described as "a meal as fierce as a tiger."
Command line (keyboard) operation can improve work efficiency to a great extent, corresponding to mouse (touch screen, etc.) operation, these two modes are the mainstream ways of human-computer interaction at present.
The development language for designing a command line tool can choose the original shell or even the more primitive language C, which is easier to use and has more functions such as node, python and golang.
This article is the beginning of the development of command line tools based on golang. It is mainly based on golang's native built-in lightweight flag package implementation. The reasons for designing command line tools with golang instead of shell and python are not discussed here.
2. Flag package introduction
The flag package is used to parse command line arguments
Rather than simply using os.Args to get command-line arguments, flag can be implemented according to more general command-line usage, such as mysql-u root-p 123456. Where mysql is the name of the command line, that is, the command.-u and-p are the two parameters of the command: user name and password, followed by the corresponding parameter values. after the parameter is declared, the two parameters can be interchangeable, and the parameter values can be optionally filled in or specified according to the default (default) value.
The types of command line parameters supported by the flag package are bool, int, int64, uint, uint64, float float64, string, duration
That is, Boolean, integer, floating point, string, time period type
3. Definition of command line parameters of flag package
To define flag command line parameters, which are used to receive the parameter values entered by the command line, there are generally two ways
Flag.TypeVar (): define parameters (actually pointers), and then define pointers (addresses) that flag.TypeVar stores (binds) command-line arguments to the values of previous parameters.
Var name stringvar age intvar height float64var graduated bool// & name is to receive the parameter value / / return value after-n entered by the user's command line is a pointer / address / / to define the string type command line parameter name used to store the value of the name parameter In parentheses are variable name, flag parameter name, default value, parameter description flag.StringVar (& name, "n", "name parameter, default is empty") / / define integer command line parameter ageflag.IntVar (& age, "a", 0, "age parameter, default is 0") / / define floating point command line parameter heightflag.Float64Var (& height, "h", 0, "height parameter") Default is 0 ") / / defines the Boolean command line parameter graduatedflag.BoolVar (& graduated," g ", false," graduated parameter, default is false ")
Flag.Type (): define parameter types and variable names in the form of short variable declarations
/ / define the string type command line parameter name In parentheses are flag parameter name, default value, parameter description namePtr: = flag.String ("n", "", "name parameter, default is empty") / / define integer command line parameter ageage: = flag.Int ("a", 0, "age parameter, default is 0") / / define floating point command line parameter heightheight: = flag.Float64 ("h", 0, "height parameter") Default is 0 ") / define Boolean command line parameter graduatedgraduated:= flag.Bool (" g ", false," graduated parameter, default is false ") 4. Flag package command line parameter parsing
Fixed usage: after defining the parameters, parse the command line parameters and write them to the registered flag by calling flag.Parse (), and then parse to get the parameter values. Check the os.Args that is also called in the source code.
Source code path go/src/flag/flag.go
/ / Parse parses the command-line flags from os.Args [1:]. Must be called// after all flags are defined and before flags are accessed by the program.func Parse () {/ / Ignore errors; CommandLine is set for ExitOnError. CommandLine.Parse (os.Args [1:])}
Then look at the source code of the Parse method
Func (f * FlagSet) Parse (arguments [] string) error {f.parsed = true f.args = arguments for {seen, err: = f.parseOne () if seen {continue} if err = = nil {break} switch f.errorHandling {case ContinueOnError: return err case ExitOnError: if err = ErrHelp {os.Exit (0)} os.Exit (2) case PanicOnError: panic (err)} return nil}
The real parsing parameter is the parseOne method (omitting the source code here), and the conclusion is
When a single "-" or not "-" is encountered, parsing will stop.
Parsing stops when two consecutive "-" are encountered
Stop after Terminator "-"
When parsing parameters, the parameters are generally specified in "-", "-", and whether they are blank or not. There are several ways to combine them as follows.
-flag xxx space and one-symbol-- flag xxx space and two-symbol-flag=xxx equal sign and one-symbol-- flag=xxx equal sign and two-symbol
Among them, the-flag xxx method is the most commonly used. If the parameter is Boolean, it can only be specified with the equal sign.
5. Flag package command line help
By default, the flag package prints the corresponding help information according to the defined command line parameters if you do not enter the parameters when in use.
Such help information can be overridden to change the default Usage.
Package mainimport ("flag"fmt") func main () {var host string var port int var verbor bool var help bool / / bind command line arguments and variable relations flag.StringVar (& host, "H", "127.0.0.1", "ssh host") flag.IntVar (& port, "P", 22, "ssh port") flag.BoolVar (& verbor, "v", false "detail log") flag.BoolVar (& help, "h", false "help") / / Custom-h flag.Usage = func () {fmt.Println (`Usage: flag [- H addr] [- p port] [- v] Options: `) flag.PrintDefaults ()} / / parse the command line parameter flag.Parse () if help {flag.Usage ()} else {fmt.Println (host, port) Verbor)} / * ➜go run flag_args.go-hUsage: flag [- H addr] [- p port] [- v] Options:-H string ssh host (default "127.0.0.1")-P int ssh port (default 22)-h help-v detail log * / 6, flag defines short and long parameters
To put it simply, short parameters and long parameters, for example, when we use certain commands, we can enter-V or-- version to view the command version. In this case, flag does not support it by default, but it can be achieved by sharing the same variable with two options, that is, by setting different options for the same variable, the order of the parameters is not fixed at the time of initialization, so you also need to ensure that they have the same default value.
Package mainimport ("fmt"flag") var logLevel stringfunc init () {const (defaultLogLevel = "DEBUG" usage = "set log level") flag.StringVar (& logLevel, "log_level", defaultLogLevel, usage) flag.StringVar (& logLevel, "l", defaultLogLevel, usage + "(shorthand)")} func main () {flag.Parse () fmt.Println ("log level:", logLevel)}
This can be achieved by declaring public constants through const and using them in default values and help information
7. Example
Implement the command to recursively calculate the file md5 under the calculation string or directory, similar to the md5sum command of linux
Bufio is used to read files in batches to prevent high resource consumption when the file is too large.
Package mainimport ("bufio"crypto/md5"flag"fmt"io"os"strings") func md5reader (reader * bufio.Reader) string {/ / hasher: = md5.New () / / define MD5 hash calculator bytes: = make ([] byte, 1024 / 1024 / 10) / read the file for {n in batches Err: = reader.Read (bytes) if err! = nil {if err! = io.EOF {return ""} break} else {hasher.Write (bytes [: n])}} return fmt.Sprintf ("% x", hasher.Sum (nil))} func md5file (path string) (string, error) {file, err: = os.Open (path) if err! = nil {return ", err} else {defer file.Close () return md5reader (bufio.NewReader (file)) Nil}} func md5str (txt string) (string, error) {return md5reader (bufio.NewReader (strings.NewReader (txt), nil / / return fmt.Sprintf ("% x", md5.Sum ([] byte (txt)} func main () {txt: = flag.String ("s", "," md5 txt ") path: = flag.String (" f ","," file path ") help: = flag.Bool (" h ", false) "help") flag.Usage = func () {fmt.Println (`Usage: md5 [- s 123abc] [- f path] Options: `) flag.PrintDefaults ()} flag.Parse () if * help | | * txt = = "" & * path = "" {flag.Usage ()} else {var md5 string var err error if * path! = "" {md5, err = md5file (* path)} else {md5 Err = md5str (* txt)} if err! = nil {fmt.Println (err)} else {fmt.Println (md5)}
Compile and generate binaries
➜go build-o md5go-x md5_bufio.go➜ ll md5go-rwxr-xr-x 1 ssgeek staff 1.9m Oct 2 00:54 md5go
Test use
➜. / md5go-h Usage: md5 [- s 123abc] [- f path] Options:-f string file path-h help-s string md5 txt➜. / md5go-s 123456e10adc3949ba59abbe56e057f20f883e ➜. / md5go-f md5_bufio.go8607a07cbb98cec0e9abe14b0db0bee6 on "how to use the flag package of Golang Development Command Line" is here. I hope the above content can be of some help to you. So that you can learn more knowledge, if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.