Location>code7788 >text

Interactive CLI Development in Go: An Introduction to the survey Library

Popularity:458 ℃/2024-09-03 14:04:18

When building command line tools, a good user interaction experience is critical. Especially in scenarios that require complex input with the user, traditional command line arguments and flags can seem clunky./AlecAivazis/survey/v2 is a library designed for the Go language, specifically for building interactive command line interfaces. It provides a variety of user input methods to make your CLI tools easier to use and friendlier.

One,survey What is it?

survey is a Go library designed to collect user input through interactive prompts. It provides a rich set of prompt types, including text input, selection menus, confirmation prompts, multiple selections, etc., which greatly facilitates developers' ability to implement user interaction in command-line tools.

Key Features:

  • simple and easy to use: Complex user interaction logic can be implemented in a few lines of code.
  • Multiple cue types: Supports text input, selection, confirmation, multi-selection, password input, etc.
  • verification mechanism: Provides input validation to ensure the validity of user input.
  • Defaults and Customization: Supports default values and highly customizable prompt behaviors.

II. Installationsurvey

To use thesurveyThe first thing you need to do is to install it:

go get -u /AlecAivazis/survey/v2

After the installation is complete, you can import it in your project:

import "/AlecAivazis/survey/v2"

III. Examples of use

1. Simple text input

The most basic usage scenario is to collect text input from the user. For example, we want to ask the user for their name:

package main

import (
    "fmt"
    "/AlecAivazis/survey/v2"
)

func main() {
    var name string
    prompt := &{
        Message: "What is your name?",
    }
    (prompt, &name)

    ("Hello, %s!\n", name)
}

In this example, the A text input prompt is created and the user's input is stored in thename in the variable.

2. Selection of menus

Sometimes we need the user to select one of a set of options. This can be done using the

var color string
prompt := &{
    Message: "Choose a color:",
    Options: []string{"Red", "Blue", "Green", "Yellow"},
}
(prompt, &color)

("You chose %s!\n", color)

A menu will be displayed that the user can select using the up and down arrow keys.

3. Recognizing the prompt

When you need the user to confirm the operation, you can use the

var confirm bool
prompt := &{
    Message: "Do you want to proceed?",
}
(prompt, &confirm)

if confirm {
    ("Proceeding...")
} else {
    ("Operation canceled.")
}

provides a simpleyes/no Hints, applicable to operation confirmation.

4. Multiple choice

If you need the user to select more than one option, you can use the

var languages []string
prompt := &{
    Message: "What programming languages do you know?",
    Options: []string{"Go", "Python", "JavaScript", "Rust"},
}
(prompt, &languages)

("You selected: %v\n", languages)

In this example, the user can select multiple programming languages and the results will be stored as slices.

5. Password entry

For sensitive information, such as password entry, you can use the, the user's input will not be displayed on the screen:

var password string
prompt := &{
    Message: "Enter your password:",
}
(prompt, &password)

("Password received.")

Ideal for handling sensitive information entered by users.

IV. Input validation

survey Validation of user input is also supported to ensure that the input meets expectations. For example, the user is asked to enter a valid e-mail address:

package main

import (
    "fmt"
    "/AlecAivazis/survey/v2"
    "strings"
)

func main() {
    var email string
    prompt := &{
        Message: "Enter your email:",
    }
    (prompt, &email, (), (func(val interface{}) error {
        if str, ok := val.(string); ok {
            if !(str, "@") {
                return ("invalid email address")
            }
        }
        return nil
    }))

    ("Email entered: %s\n", email)
}

Here, we use the Add a custom validation function to ensure that the user input is a valid email address.

V. IntegrationCobra utilization

survey associate withCobra used in combination to create more complex command-line applications. For example, you can use theCobra commandRun method of thesurvey prompts, thus enabling interactive command parameter entry.

package main

import (
    "fmt"
    "/spf13/cobra"
    "/AlecAivazis/survey/v2"
)

var rootCmd = &{
    Use:   "myapp",
    Short: "MyApp is an interactive CLI application",
    Run: func(cmd *, args []string) {
        var name string
        var age int

        namePrompt := &{
            Message: "What is your name?",
        }
        agePrompt := &{
            Message: "How old are you?",
        }

        (namePrompt, &name)
        (agePrompt, &age)

        ("Hello, %s! You are %d years old.\n", name, age)
    },
}

func main() {
    ()
}

This example shows how theCobra Embedded in the commandsurvey, providing users with an interactive experience.


孟斯特

Disclaimer: This work usesAttribution-Noncommercial Use-Share Alike 4.0 International (CC BY-NC-SA 4.0)A license is granted and the use of it is subject to attribution.
Author: mengbin
blog: mengbin
Github: mengbin92
cnblogs: have no intention of loving the water
Munster