SoFunction
Updated on 2025-03-05

Summary of several methods of reading command parameters in Go language

Preface

For a beginner, if you want to be familiar with the characteristics of Go language as soon as possible, you mainly focus on operational learning methods, such as writing a simple mathematical calculator, reading command line parameters, and performing mathematical operations.

This article describes how Go language accepts command line parameters and completes a simple mathematical calculation for convenience of demonstration. The final command line result is roughly as follows:

# input 
./calc add 1 2
# output
3

# input
./calc sub 1 2
# out
-1

# input
./calc mul 10 20
# out
200

Three ways to use are:

  • Built-in os package read command parameters
  • Built-in flag package read command parameters
  • cli framework read command parameters

0. Have historical experience

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

Python

import sys

args = 

# args is a list# The first value represents the file name# Except for the first one,Other values ​​are accepted parameters

Shell

if [ $# -ne 2 ]; then
 echo "Usage: $0 param1 pram2"
 exit 1
fi
name=$1
age=$2

echo $name
echo $age
# `$0` means file name# `$1` represents the first parameter# `$2` Indicates the second parameter

Some common features can be seen. The received parameters are generally parsed into an array (list, slice). The first element represents the file name, and the remaining parameters represent the received parameters.

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

The first element except the file name: parsed into mathematical operations, such as: add, sub, mul, sqrt
The remaining parameters represent: the value of the operation

Notice:The parameters read by the command line are generally strings, and numerical calculations require data type conversion.

This is probably the idea.

1. OS get command line parameters



# For the accepted parameter, it is a slice
 

# Convert string values ​​to integers


# Convert integers to strings


# Convert string values ​​to floating point types
var help = func () {
 ("Usage for calc tool.")
 ("====================================================")
 ("add 1 2, return 3")
 ("sub 1 2, return -1")
 ("mul 1 2, return 2")
 ("sqrt 2, return 1.4142135623730951")
}


func CalcByOs() error {
 args := 
 if len(args) < 3 || args == nil {
 help()
 return nil
 }
 operate := args[1]
 switch operate {
 case "add":{
  rt := 0
  number_one, err1 := (args[2])
  number_two, err2 := (args[3])
  if err1 == nil && err2 == nil {
  rt = number_one + number_two
  ("Result ", rt)
  }
 }
 case "sub":
 {
  rt := 0
  number_one, err1 := (args[2])
  number_two, err2 := (args[3])
  if err1 == nil && err2 == nil {
  rt += number_one - number_two
  ("Result ", rt)
  }
 }
 case "mul":
 {
  rt := 1
  number_one, err1 := (args[2])
  number_two, err2 := (args[3])
  if err1 == nil && err2 == nil {
  rt = number_one * number_two
  ("Result ", rt)
  }
 }
 case "sqrt":
 {
  rt := float64(0)
  if len(args) != 3 {
  ("Usage: sqrt 2, return 1.4142135623730951")
  return nil
  }
  number_one, err := (args[2], 64)
  if err == nil {
  rt = (number_one)
  ("Result ", rt)
  }
 }
 default:
 help()

 }
 return nil
}

The final effect is probably:

./calc add 1 2
Result 3

====================

./calc sub 1 2
Result -1

====================

./calc mul 10 20
Result 200

===================

./calc sqrt 2
Result 1.4142135623730951

2. flag get command line parameters

The flag package is more convenient than os to read parameters. You can customize the types of incoming parameters: such as strings, integers, floating point types, default parameter settings, etc.

The basic usage methods are as follows:

var operate string

(&operate,"o", "add", "operation for calc")

# explain

Bind the operating variable, name="o", value="add" , usage="operation for calc"

It can also be defined as a pointer variable

var operate := ("o", "add", "operation for calc")

You can also customize the flag type

After all variables are registered, call () to parse the command line parameters. If it is a method of binding variables, use the variables directly to operate.
If you use pointer variable type, *operate is required.

() represents all command line parameter sets received, and is also a slice

for index, value := range  {
 (index, value)
}
func CalcByFlag() error {
 var operation string
 var numberone float64
 var numbertwo float64
 (&operation, "o", "add", "operation for this tool")
 flag.Float64Var(&numberone, "n1", 0, "The first number")
 flag.Float64Var(&numbertwo, "n2", 0, "The second number")
 ()
 (numberone, numbertwo)
 if operation == "add" {
 rt := numberone + numbertwo
 ("Result ", rt)
 } else if operation == "sub" {
 rt := numberone - numbertwo
 ("Result ", rt)
 } else if operation == "mul" {
 rt := numberone * numbertwo
 ("Result ", rt)
 } else if operation == "sqrt" {
 rt := (numberone)
 ("Result ", rt)
 } else {
 help()
 }
 return nil
}

The final result is as follows:

./calc -o add -n1 1 -n2 2
Result 3

=============================

./calc -o sub -n1 2 -n2 3
Result -1

============================

./calc -o mul -n1 10 -n2 20
Result 200

===========================

./calc -o sqrt -n1 2
Result 1.4142135623730951

3. CLI framework

cliIt is a relatively popular command line framework in the industry.

So you need to install first:

go get /urfave/cli
# A simple example is as follows:package main

import (
 "fmt"
 "os"

 "/urfave/cli"
)

func main() {
 app := ()
  = "boom"
  = "make an explosive entrance"
  = func(c *) error {
 ("boom! I say!")
 return nil
 }

 ()
}

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

Mainly use the Flag function in the framework to set parameters

 = [] {
 {
 Name: "operation, o",
 Value: "add",
 Usage: "calc operation",
 },
 cli.Float64Flag{
 Name: "numberone, n1",
 Value: 0,
 Usage: "number one for operation",
 },
 cli.Float64Flag{
 Name: "numbertwo, n2",
 Value: 0,
 Usage: "number two for operation",
 },
}

It can be seen that we used three parameters: operation, number, numberwo

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

So how to implement parameter operations in this framework: mainly rewrite method

 = func(c *) error {
 operation := ("operation")
 numberone := c.Float64("numberone")
 numbertwo := c.Float64("numbertwo")
 //(operation, numberone, numbertwo)
 if operation == "add" {
 rt := numberone + numbertwo
 ("Result ", rt)
 } else if operation == "sub" {
 rt := numberone - numbertwo
 ("Result ", rt)
 } else if operation == "mul" {
 rt := numberone * numbertwo
 ("Result ", rt)
 } else if operation == "sqrt" {
 rt := (numberone)
 ("Result ", rt)
 } else {
 help()
 }
 return nil
}

# right operation Make judgments on parameters,What kind of operation is performed,Then write the corresponding operation
func CalcByCli(){
 app := ()
  = "calc with go"
  = "calc tool operate by go"
  = "0.1.0"
  = []  {
  {
   Name: "operation, o",
   Value: "add",
   Usage: "calc operation",
  },
  cli.Float64Flag{
   Name: "numberone, n1",
   Value: 0,
   Usage: "number one for operation",
  },
  cli.Float64Flag{
   Name: "numbertwo, n2",
   Value: 0,
   Usage: "number two for operation",
  },
 }
  = func(c *) error {
  operation := ("operation")
  numberone := c.Float64("numberone")
  numbertwo := c.Float64("numbertwo")
  //(operation, numberone, numbertwo)
  if operation == "add" {
   rt := numberone + numbertwo
   ("Result ", rt)
  } else if operation == "sub" {
   rt := numberone - numbertwo
   ("Result ", rt)
  } else if operation == "mul" {
   rt := numberone * numbertwo
   ("Result ", rt)
  } else if operation == "sqrt" {
   rt := (numberone)
   ("Result ", rt)
  } else {
   help()
  }
  return nil
 }
 ()
}

The final effect of calling this function is as follows:

./calc -o add --n1 12 --n2 12
Result 24

===================================

./calc -o sub --n1 100 --n2 200
Result -100

===================================

./calc -o mul --n1 10 --n2 20
Result 200

===================================

./calc -o sqrt --n1 2
Result 1.4142135623730951

4 Others

Knowing how to read command line parameters can achieve something more interesting.

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

There are also some query interfaces, such as Youdao Cloud Translation Interface, where you can implement the translation function.

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

For example, some music interfaces realize music information query.

Not one by one.

The following implements an interface that calls the free weather query interface to implement the command line to query weather.

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

A simple GET operation is as follows:

func Requests(url string) (string, error) {
 response, err := (url)
 if err != nil {
  return "", err
 }
 defer ()
 body, _ := ()
 return string(body), nil
}

The free API URL is as follows:

/open/api/weather/?city=Beijing

The result returned is a Json format data

{
 "status": 200,
 "data": {
  "wendu": "29",
  "ganmao": "All weather conditions are suitable and the chances of colds are low. But please avoid being in an air-conditioned room for a long time to prevent colds.",
  "forecast": [
   {
    "fengxiang": "south wind",
    "fengli": "Level 3-4",
    "high": "High temperature 32℃",
    "type": "partly cloudy",
    "low": "Low temperature 17℃",
    "date": "Tuesday, 16th"
   },
   {
    "fengxiang": "south wind",
    "fengli": "Breeze Level",
    "high": "High temperature 34℃",
    "type": "clear",
    "low": "Low temperature 19℃",
    "date": "Wednesday, 17th"
   },
   {
    "fengxiang": "south wind",
    "fengli": "Breeze Level",
    "high": "High temperature 35℃",
    "type": "clear",
    "low": "Low temperature 22℃",
    "date": "Thursday, 18th"
   },
   {
    "fengxiang": "south wind",
    "fengli": "Breeze Level",
    "high": "High temperature 35℃",
    "type": "partly cloudy",
    "low": "Low temperature 22℃",
    "date": "Friday, 19th"
   },
   {
    "fengxiang": "south wind",
    "fengli": "Level 3-4",
    "high": "High temperature 34℃",
    "type": "clear",
    "low": "Low temperature 21℃",
    "date": "Saturday, 20th"
   }
  ],
  "yesterday": {
   "fl": "breeze",
   "fx": "south wind",
   "high": "High temperature 28℃",
   "type": "clear",
   "low": "Low temperature 15℃",
   "date": "Monday, 15th"
  },
  "aqi": "72",
  "city": "Beijing"
 },
 "message": "OK"
}

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

package main

import (
  "fmt"
  "os"
 "encoding/json"
  "/urfave/cli"
  "net/http"
  "io/ioutil"
  //"/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 `json:"fl"`
  Type string `json:"type"`
  Notice string `json:"notice"`
}

func main() {
  const apiURL = "/open/api/weather/?city="
  app := ()
   = "weather-cli"
   = "Weather Forecast Mini Program"

   = []{
    {
      Name: "city, c",
      Value: "Shanghai",
      Usage: "Chinese name of city",
    },
    {
      Name: "day, d",
      Value: "today",
      Usage: "Optional: Today, Yesterday, Prediction",
    },
    {
      Name: "Author, r",
      Value: "xiewei",
      Usage: "Author name",
    },
  }

   = func(c *) error {
    city := ("city")
    day := ("day")

    var body, err = Requests(apiURL + city)
    if err != nil {
      ("err was %v", err)
      return nil
    }

    var r Response
    err = ([]byte(body), &amp;r)
    if err != nil {
      ("\nError message: %v", err)
      return nil
    }
    if  != 200 {
      ("The error occurred when getting the weather API, %s", )
      return nil
    }
    Print(day, r)
    return nil
  }
  ()

}


func Print(day string, r Response) {
  ("City:", )
  if day == "today" {
    ("humidity:", )
    ("Air Quality:", )
    ("Kind tips:", )
  } else if day == "yesterday" {
    ("date:", )
    ("temperature:", , )
    ("Wind volume:", , )
    ("weather:", )
    ("Kind tips:", )
  } else if day == "predict" {
    ("====================================")
    for _, item := range  {
      ("date:", )
      ("temperature:", , )
      ("Wind volume:", , )
      ("weather:", )
      ("Kind tips:", )
      ("====================================")
    }
  } else {
    ("...")
  }

}
func Requests(url string) (string, error) {
  response, err := (url)
  if err != nil {
    return "", err
  }
  defer ()
  body, _ := ()
  return string(body), nil
}

The final effect is roughly as follows:

./weather -c Shanghai

City: Shanghai
humidity: 80%
Air quality: Mild contamination
Kind tips: child、Elderly and heart、People with respiratory diseases should reduce long-term or high-intensity outdoor exercise


================================
./weaather -c Shanghai -d yesterday

City: Shanghai
date: 28Tuesday
temperature: Low temperature 12.0℃ high temperature 19.0℃
Air volume: Southwest wind &lt;3class
weather: Light rain
Kind tips: A misty rainy day,Like to listen to music alone the most

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.