Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to read command parameters in Go language

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge of how to read command parameters in Go language. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

This article describes how the Go language accepts command-line arguments in three ways, and completes a simple mathematical calculation. For the convenience of demonstration, the final command-line result is something like this:

# input./calc add 1 2# output3# input./calc sub 1 2# out-1# input./calc mul 10 20# out200

The three methods used are:

Built-in os package read command parameters

Built-in flag package read command parameters

Cli framework reads command parameters

0. Have historical experience

If you are familiar with Python and Shell scripts, you can compare:

Python

Import sysargs = sys.argv# args is a list # the first value represents the file name # except the first, the other values are accepted parameters

Shell

If [$#-ne 2]; then echo "Usage: $0 param1 pram2" exit 1finame=$1age=$2echo $nameecho $age# `$0` indicates the file name #` $1` indicates the first parameter # `$2` represents the second parameter

Can see some commonalities, receive parameters, generally parsed out is an array (list, slice), the first element represents the file name, the remaining parameters represent the received parameters.

OK, so in order to achieve the function of "simple mathematical calculation", read the command line parameters: for example,. / calc add 1 2

The first element in addition to the file name: parses to operations that perform mathematical operations, such as add, sub, mul, sqrt

The remaining parameters indicate the value of the operation.

Note: the parameters read on the command line are generally strings, and data type conversion is required for numerical calculation.

That's probably the way of thinking.

1. OS gets command line parameters

Os.Args# is an accepted parameter and is a sliced strconv.Atoi # that converts string values to integer strconv.Itoa#, integer to string strconv.ParseFloat#, string values to floating-point var help = func () {fmt.Println ("Usage for calc tool.") Fmt.Println ("= =") fmt.Println ("add 12, return 3") fmt.Println ("sub 12, return-1") fmt.Println ("mul 12, return 2") fmt.Println ("sqrt 2, return 1.4142135623730951")} func CalcByOs () error {args: = os.Args if len (args) < 3 | args = nil {help () return nil} operate: = args [1] switch operate {case "add": {rt: = 0 number_one Err1: = strconv.Atoi (args [2]) number_two, err2: = strconv.Atoi (args [3]) if err1 = = nil & & err2 = = nil {rt = number_one + number_two fmt.Println ("Result", rt)}} case "sub": {rt: = 0 number_one, err1: = strconv.Atoi (args [2]) number_two Err2: = strconv.Atoi (args [3]) if err1 = = nil & & err2 = = nil {rt + = number_one-number_two fmt.Println ("Result", rt)}} case "mul": {rt: = 1 number_one, err1: = strconv.Atoi (args [2]) number_two, err2: = strconv.Atoi (args [3]) if err1 = = nil & & err2 = = nil {rt = number_one * number_two fmt.Println ("Result") Rt)} case "sqrt": {rt: = float64 (0) if len (args)! = 3 {fmt.Println ("Usage: sqrt 2, return 1.4142135623730951") return nil} number_one, err: = strconv.ParseFloat (args [2], 64) if err = = nil {rt = math.Sqrt (number_one) fmt.Println ("Result", rt)} default: help ()} return nil}

The final effect is probably:

. / calc add 1 2Result 3=./calc sub 1 2Result-1=./calc mul 10 20Result 200=./calc sqrt 2Result 1.4142135623730951

2. Flag gets command line parameters

The flag package is more convenient to read parameters than os. You can customize the types of parameters passed in, such as string, integer, floating point, default parameter settings, etc.

The basic usage is as follows:

Var operate stringflag.StringVar (& operate, "o", "add", "operation for calc")

# explain

Bind operate variables, name= "o", value= "add", usage= "operation for calc"

It can also be defined as a pointer variable.

Var operate: = flag.String ("o", "add", "operation for calc")

You can also customize the flag type

After all variables have been registered, call flag.Parse () to parse the command line arguments. If it is the way to bind variables, use variables to operate directly.

If you use pointer variables, you need to use * operate like this.

Flag.Args () represents all command line argument sets received, which is also a slice

For index, value: = range flag.Args {fmt.Println (index, value)} func CalcByFlag () error {var operation string var numberone float64 var numbertwo float64 flag.StringVar (& operation, "o", "add", "operation for this tool") flag.Float64Var (& numberone, "N1", 0, "The first number") flag.Float64Var (& numbertwo, "N2", 0, "The second number") flag.Parse () fmt.Println (numberone Numbertwo) if operation = = "add" {rt: = numberone + numbertwo fmt.Println ("Result", rt)} else if operation = = "sub" {rt: = numberone-numbertwo fmt.Println ("Result", rt)} else if operation = = "mul" {rt: = numberone * numbertwo fmt.Println ("Result", rt)} else if operation = "sqrt" {rt: = math.Sqrt (numberone) fmt.Println ("Result", rt)} else {help ()} return nil}

The final results are as follows:

. / calc-o add-N1-N2 2Result 3==./calc-o sub-n12-N2 3Result-1==./calc-o mul-N1 10-N2 20Result 200==./calc-o sqrt-N1 2Result 1.4142135623730951

3. CLI framework

Cli is a popular command line framework in the industry.

So you first need to install:

A simple example of go get github.com/urfave/cli# is as follows: package mainimport ("fmt"os"github.com/urfave/cli") func main () {app: = cli.NewApp () app.Name = "boom" app.Usage = "make an explosive entrance" app.Action = func (c * cli.Context) error {fmt.Println ("boom! I say!") Return nil} app.Run (os.Args)}

Well, in order to achieve the function of "simple mathematical calculation", how should we achieve it?

Mainly use the Flag function in the framework to set the parameters

App.Flags = [] cli.Flag {cli.StringFlag {Name: "operation, o", Value: "add", Usage: "calc operation",}, cli.Float64Flag {Name: "numberone, N1", Value: 0, Usage: "numberone for operation",}, cli.Float64Flag {Name: "numbertwo, N2", Value: 0, Usage: "numbertwo for operation",},}

As you can see, we used three parameters: operation, numberone, and numbertwo

The type, default value, and alias (abbreviation) of the parameter are also defined.

So how to implement parameter manipulation in this framework: mainly to override the app.Action method

App.Action = func (c * cli.Context) error {operation: = c.String ("operation") numberone: = c.Float64 ("numberone") numbertwo: = c.Float64 ("numbertwo") / / fmt.Println (operation, numberone, numbertwo) if operation = = "add" {rt: = numberone + numbertwo fmt.Println ("Result", rt)} else if operation = "sub" {rt: = numberone-numbertwo fmt.Println ("Result") Rt)} else if operation = = "mul" {rt: = numberone * numbertwo fmt.Println ("Result", rt)} else if operation = = "sqrt" {rt: = math.Sqrt (numberone) fmt.Println ("Result", rt)} else {help ()} return nil} # judge operation parameters Perform that kind of operation. Then write the corresponding operation func CalcByCli () {app: = cli.NewApp () app.Name = "calc with go" app.Usage = "calc tool operate by go" app.Version = "0.1.0" app.Flags = [] cli.Flag {cli.StringFlag {Name: "operation, o", Value: "add", Usage: "calc operation",}, cli.Float64Flag {Name: "numberone, N1", Value: 0, Usage: "numberone for operation" }, cli.Float64Flag {Name: "numbertwo, N2", Value: 0, Usage: "numbertwo for operation",} app.Action = func (c * cli.Context) error {operation: = c.String ("operation") numberone: = c.Float64 ("numberone") numbertwo: = c.Float64 ("numbertwo") / / fmt.Println (operation, numberone, numbertwo) if operation = "add" {rt: = numberone + numbertwo fmt.Println ("Result") Rt)} else if operation = = "sub" {rt: = numberone-numbertwo fmt.Println ("Result", rt)} else if operation = = "mul" {rt: = numberone * numbertwo fmt.Println ("Result", rt)} else if operation = = "sqrt" {rt: = math.Sqrt (numberone) fmt.Println ("Result", rt)} else {help ()} return nil} app.Run (os.Args)}

The final effect of calling this function is as follows:

. / calc-o add-- N1 12-- N2 12Result 24==./calc-o sub-- N1 100-- N2 200Result-100==./calc-o mul-- N1 10-- N2 20Result 200==./calc-o sqrt-- N1 2Result 1.4142135623730951

4 other

Knowing how to read command-line arguments can do something more interesting.

For example, there are many free API interfaces on the Internet, such as the API interface for querying weather and lunar calendar.

There are also some query interfaces, such as youdao cloud translation interface, you can achieve the translation function.

Or the interface of scallop to realize the function of querying words.

For example, some music interfaces to achieve music information query.

No, one by one.

The following is to implement a command line to query the weather by calling the free weather query interface.

How does GO make HTTP access? The built-in net/http can be implemented

A simple GET operation is as follows:

Func Requests (url string) (string, error) {response, err: = http.Get (url) if err! = nil {return ", err} defer response.Body.Close () body, _: = ioutil.ReadAll (response.Body) return string (body), nil}

The free API URL is as follows:

Http://www.sojson.com/open/api/weather/json.shtml?city= Beijing

The result returned is a data in Json format

{"status": 200,200, "data": {"wendu": "29", "ganmao": "the weather conditions are suitable and the incidence of colds is low. But please avoid staying in an air-conditioned room for a long time to avoid catching a cold." , "forecast": [{"fengxiang": "Nanfeng", "fengli": "3-4", "high": "High temperature 32 ℃", "type": "cloudy", "low": "low temperature 17 ℃", "date": "Tuesday, 16th"}, {"fengxiang": "Nanfeng", "fengli": "breeze" "high": "34 ℃", "type": "Qing", "low": "19 ℃", "date": "Wednesday 17"}, {"fengxiang": "Nanfeng", "fengli": "breeze", "high": "35 ℃", "type": "Qing", "low": "22 ℃" "date": "Thursday, 18th"}, {"fengxiang": "South Wind", "fengli": "Light Wind", "high": "High temperature 35 ℃", "type": "cloudy", "low": "low temperature 22 ℃", "date": "Friday 19th"}, {"fengxiang": "South Wind" "fengli": "3-4", "high": "High temperature 34 ℃", "type": "Qing", "low": "low temperature 21 ℃", "date": "20th Saturday"}], "yesterday": {"fl": "Breeze", "fx": "South Wind", "high": "High temperature 28 ℃", "type": "Qing" "low": "low temperature 15 ℃", "date": "Monday 15th"}, "aqi": "72", "city": "Beijing"}, "message": "OK"}

So our task is to pass in the name of the "city" and parse the returned Json data.

Package mainimport ("fmt", "os", "encoding/json", "github.com/urfave/cli", "net/http", "io/ioutil" / / "github.com/modood/table") type Response struct {Status int `json: "status" `CityName string `json: "city" `Data Data `json: "data" `Date string `json: "date" `Message string `json: "message" `Count int `json: "count" `} type Data struct {ShiDu string `json: "shidu" `Quality String `json: "quality" `Ganmao string `json: "ganmao" `Yesterday Day `json: "yesterday" `Forecast [] Day `json: "forecast" `} type Day struct {Date string `json: "date" `Sunrise string `json: "sunrise" `High string `json: "high" `Low string `json: "low" `Sunset string `json: "sunset" `Aqi float32 `json: "aqi" `Fx string `json: "fx" `Fl string `Fl string: "json `json:" Fl string "`fl `fl:" json "`fl"` fl: "fl" `} Func main () {const apiURL = "http://www.sojson.com/open/api/weather/json.shtml?city=" app: = cli.NewApp () app.Name =" weather-cli "app.Usage =" weather forecast Mini Program "app.Flags = [] cli.Flag {cli.StringFlag {Name:" city C ", Value:" Shanghai ", Usage:" City Chinese name ",}, cli.StringFlag {Name:" day, d ", Value:" Today ", Usage:" optional: today, yesterday, Forecast ",}, cli.StringFlag {Name:" Author, r ", Value:" xiewei ", Usage:" Author name ",} } app.Action = func (c * cli.Context) error {city: = c.String ("city") day: = c.String ("day") var body, err = Requests (apiURL + city) if err! = nil {fmt.Printf ("err was% v", err) return nil} var r Response err = json.Unmarshal ([] byte (body)) & r) if err! = nil {fmt.Printf ("\ nError message:% v", err) return nil} if r.Status! = 200 {fmt.Printf ("error occurred in getting weather API,% s", r.Message) return nil} Print (day, r) return nil} app.Run (os.Args)} func Print (day string, r Response) {fmt.Println ("City:" R.CityName) if day = "Today" {fmt.Println ("humidity:", r.Data.ShiDu) fmt.Println ("Air quality:", r.Data.Quality) fmt.Println ("warm reminder:", r.Data.Ganmao)} else if day = = "yesterday" {fmt.Println ("date:", r.Data.Yesterday.Date) fmt.Println ("temperature:", r.Data.Yesterday.Low) R.Data.Yesterday.High) fmt.Println ("Air volume:", r.Data.Yesterday.Fx, r.Data.Yesterday.Fl) fmt.Println ("Weather:", r.Data.Yesterday.Type) fmt.Println ("warm reminder:", r.Data.Yesterday.Notice)} else if day = = "Forecast" {fmt.Println ("=") for _, item: = range r.Data.Forecast {fmt.Println ("date:" Item.Date) fmt.Println ("temperature:", item.Low, item.High) fmt.Println ("Air Volume:", item.Fx, item.Fl) fmt.Println ("Weather:", item.Type) fmt.Println ("warm Tip:", item.Notice) fmt.Println ("=")}} else {fmt.Println ("...")} func Requests (url string) (string, error) {response Err: = http.Get (url) if err! = nil {return ", err} defer response.Body.Close () body, _: = ioutil.ReadAll (response.Body) return string (body), nil}

The final effect is roughly as follows:

/ weather-c Shanghai City: Shanghai humidity: 80% Air quality: mild pollution warm Tip: children, the elderly and people with heart and respiratory diseases should reduce long-term or intensive outdoor exercise =. / weaather-c Shanghai-d yesterday city: Shanghai date: 28th Tuesday temperature: low temperature 12.0 ℃ high temperature 19.0 ℃ air volume: southwest wind

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report