Search code examples
goinputgo-cobra

How to accept input in a single line using cobra library in Go


I am writing a code in go language using cobra, currently the input Im giving is :

 Calc add 
           Enter the Number of inputs
           2
           Enter the Numbers
           2
           4
 Output: Sum is : 6

In this those who are familiar with cobra, Calc is my project and add is the command Im using,I want the input to be given as Calc add N2 2 4( in a single line) and the output should be displayed, where N is a variable that identifies the Number of inputs and 2 4 are the numbers to be added.

CODE FOR THE ADD COMMAND:

package cmd

import (
    "fmt"

    "github.com/spf13/cobra"
)

// addCmd represents the add command
var addCmd = &cobra.Command{
    Use:   "add",
    Short: "Addition value of given Numbers",

    Run: func(cmd *cobra.Command, args []string) {
        length := 0
    fmt.Println("Enter the number of inputs")
    fmt.Scanln(&length)
    fmt.Println("Enter the inputs")
    numbers := make([]int, length)
    for i := 0; i < length; i++ {
        fmt.Scanln(&numbers[i])
    }
      fmt.Println(numbers)

      sum:=0

for _, numbers := range numbers {

sum += numbers

}

fmt.Println("The Sum :",sum)


 },
}

func init() {
    RootCmd.AddCommand(addCmd)


}

P


Solution

  • This will fulfill your purpose. Take your number in a flag --input. Give other numbers to add as arguments.

    func NewCmd() *cobra.Command {
        var input int
        c := &cobra.Command{
            Use:   "add",
            Short: "Addition value of given Numbers",
    
            Run: func(cmd *cobra.Command, args []string) {
                if len(args) != input {
                    fmt.Println(fmt.Sprintf("You need to provide %v number to sum up", input))
                    os.Exit(1)
                }
                numbers := make([]int, input)
                for i := 0; i < input; i++ {
                    num, _ := strconv.Atoi(args[i])
                    numbers[i] = num
                }
                sum := 0
                for _, numbers := range numbers {
                    sum += numbers
                }
                fmt.Println("The Sum :", sum)
            },
        }
        c.Flags().IntVar(&input, "input", 0, "Number of input")
        return c
    }
    
    func init() {
        cmd := NewCmd()
        RootCmd.AddCommand(cmd)
    }
    

    Input:

    Calc add --input=3 6 3 6
    

    Output: The Sum : 15