Go语言学习: survey 包 / ipt / 交互 list/select

一个可以产生交互式 ui 的 golang 包
更新于: 2024-11-28 09:35:12

安装

go get -u github.com/AlecAivazis/survey/v2

main.go

package main

import (
  "fmt"
	"github.com/AlecAivazis/survey/v2"
)

func BuildCommandList(values []string) {
	// the answers will be written to this struct
	answers := struct {
		Module string `survey:"module"`
	}{}

	// the questions to ask
	var qs = []*survey.Question{
		{
			Name: "module",
			Prompt: &survey.Select{
				Message: "Choose a module:",
				Options: values,
			},
		},
	}

	// perform the questions
	err := survey.Ask(qs, &answers)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	fmt.Println("submodule: ", answers.Module);
}


func main() {
  values := []string{"auth", "blog", "core", "user"}
  BuildCommandList(values)
}

支持 struct

支持更复杂的情况,通过 transform 的思路

package main

import (
	"fmt"

	"github.com/AlecAivazis/survey/v2"
)

type ColorOption struct {
	Name  string
	Value string
}

func main() {
	// Define struct options
	options := []ColorOption{
		{"Red", "#FF0000"},
		{"Blue", "#0000FF"},
		{"Green", "#00FF00"},
	}

	// Create a slice of display names for the options
	displayOptions := make([]string, len(options))
	for i, opt := range options {
		displayOptions[i] = opt.Name
	}

	var selected string

	// Ask user with struct-based options
	err := survey.AskOne(&survey.Select{
		Message: "Choose a color:",
		Options: displayOptions,
	}, &selected)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	// Map the selected display name back to the struct
	var chosenOption *ColorOption
	for _, opt := range options {
		if opt.Name == selected {
			chosenOption = &opt
			break
		}
	}

	if chosenOption != nil {
		fmt.Printf("You chose %s with value %s.\n", chosenOption.Name, chosenOption.Value)
	} else {
		fmt.Println("Invalid selection")
	}
}