How to pass a String Map as a Command-Line argument in Go

Emmanuel Gautier / April 03, 2023

2 min read

As a Go developer, you may need to build command-line interface (CLI) applications that accept various types of command-line arguments, including string maps. To accomplish this task, you can use the StringToStringVarP() function in the Go flag package. Let's see how to use this function to define a string map flag and parse its value from the command-line arguments. This package is also used with cobra module. We will see later how it works with cobra.

The StringToStringVarP() function is a part of the Go flag package, which provides a simple way to define and parse command-line flags. This function takes a pointer to a map[string]string variable and assigns its value to the flag. Here's an example:

import (
    "flag"
    "fmt"
)

func main() {
    // Define a map flag
    myMapFlag := make(map[string]string)
    flag.StringToStringVarP(&myMapFlag, "my-map", "m", nil, "a string map")

    // Parse the command-line arguments
    flag.Parse()

    // Use the myMapFlag variable in your application
    fmt.Printf("myMapFlag: %v\n", myMapFlag)
}

In this example, we can use the myMapFlag variable in our application. The flag's value will be a map[string]string, with each key-value pair separated by = signs and each pair separated by , characters. For example, the command ./my-app -m key1=value1,key2=value2 would set the myMapFlag variable to map[string]string{"key1": "value1", "key2": "value2"}.

Cobra

When building a CLI application with Go, you may choose to use a third-party module like cobra to create the command-line interface. cobra provides a powerful set of tools for defining and handling command-line arguments. To use StringToStringVarP() with cobra, you can simply call the PersistentFlags().StringToStringP() function on the cobra.Command object.

import (
    "fmt"

    "github.com/spf13/cobra"
)

func main() {
    // Create a new cobra command
    cmd := &cobra.Command{
        Use: "my-app",
        Run: func(cmd *cobra.Command, args []string) {
            // Use the myMapFlag variable in your application
            fmt.Printf("myMapFlag: %v\n", myMapFlag)
        },
    }

    // Define a map flag using StringToStringP
    var myMapFlag map[string]string
    cmd.PersistentFlags().StringToStringVarP(&myMapFlag, "my-map", "m", nil, "a string map")

    // Execute the command
    if err := cmd.Execute(); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

Consulting

If you're seeking solutions to a problem or need expert advice, I'm here to help! Don't hesitate to book a call with me for a consulting session. Let's discuss your situation and find the best solution together.

Share this post
Follow the RSS feed