How to set cmd *cobra.Command as a variable in the cobra library?

851 Views Asked by At

This code has two roles and each of them contains different messages according to the role.

But I took cmd *cobra.Command as a variable in the StringCode() function because I don't want it to call it everywhere as a parameter. cmd is required for this flag cmd.Flags().GetString(value). That's why I just used it in the GetString() function but it is giving me the following error.

Error

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x158 pc=0x53a318]

Code

role.go

import (
    "errors"
    "fmt"

    "github.com/spf13/cobra"
)

var Admin string
var Developer string

func StringCode(value string) string {
    var cmd *cobra.Command
    var stringResult string
    stringResult, _ = cmd.Flags().GetString(value)
    return stringResult
}

func GetRoles() []string {
    var role [2]string
    role[0] = StringCode("admin")
    role[1] = StringCode("developer")
    result := []string{role[0], role[1]}
    return result
}

func RoleCondition() {
    role := GetRoles()
    if role[0] == "bilal" {
        fmt.Println("It is an admin")
    } else if role[1] == "khan" {
        fmt.Println("It is a developer")
    } else {
        fmt.Println("wrong entry")
    }
}

// roleCmd represents the role command
var roleCmd = &cobra.Command{
    Use: "role",
    Short: `It contains different roles in a company like admin, developer, etc. These roles have different rights 
and they all function according to those roles.`,
    Args: func(cmd *cobra.Command, args []string) error {
        designation := GetRoles()
        if designation[0] == "" && designation[1] == "" && len(args) < 1 {
            return errors.New("accept(s) 1 argument, received 0")
        }
        return nil
    },
    Run: func(cmd *cobra.Command, args []string) {
        RoleCondition()
    },
}

func init() {
    rootCmd.AddCommand(roleCmd)
    roleCmd.PersistentFlags().StringVarP(&Admin, "admin", "a", "", "An admin to get access to")
    roleCmd.PersistentFlags().StringVarP(&Developer, "developer", "d", "", "A developer to get access to")
}
0

There are 0 best solutions below