简介
survey 可以让你方便的在终端上构建交互式和可访问提示的应用,支持ANSI
一、内置的Validators
- Required 要求必填
- MinLength(n) 输入字符最小长度验证
- MaxLength(n) 输入字符最大长度验证
- MaxItems(n) 选项最多验证
- MinItems(n) 选项最小验证
二、安装
go get github.com/AlecAivazis/survey/v2
三、测试用例
代码模块:
package main
import (
"fmt"
"github.com/AlecAivazis/survey/v2"
)
// the questions to ask
var qs = []*survey.Question{
{
Name: "name",
Prompt: &survey.Input{Message: "What is your name?"},
Validate: survey.Required,
Transform: survey.Title,
},
{
Name: "color",
Prompt: &survey.Select{
Message: "Choose a color:",
Options: []string{"red", "blue", "green"},
Default: "red",
},
},
{
Name: "age",
Prompt: &survey.Input{Message: "How old are you?"},
},
}
func main() {
// 结果写入到结构体
answers := struct {
Name string // survey 会默认匹配首字母小写的name
FavoriteColor string `survey:"color"` // 或者你也可以用tag指定如何匹配
Age int // 如果类型不一致,survey会尝试转换
}{}
// 执行提问
err := survey.Ask(qs, &answers)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Printf("%s chose %s.", answers.Name, answers.FavoriteColor)
}
运行结果:
四、其他用法
** 文本输入**
name := ""
prompt := &survey.Input{
Message: "ping",
}
survey.AskOne(prompt, &name)
** 多行输入**
text := ""
prompt := &survey.Multiline{
Message: "ping",
}
survey.AskOne(prompt, &text)
** 密码输入**
password := ""
prompt := &survey.Password{
Message: "Please type your password",
}
survey.AskOne(prompt, &password)
** 确认**
name := false
prompt := &survey.Confirm{
Message: "Do you like pie?",
}
survey.AskOne(prompt, &name)
** 单选**
color := ""
prompt := &survey.Select{
Message: "Choose a color:",
Options: []string{"red", "blue", "green"},
}
survey.AskOne(prompt, &color)
** 多选**
days := []string{}
prompt := &survey.MultiSelect{
Message: "What days do you prefer:",
Options: []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"},
}
survey.AskOne(prompt, &days)
** 验证**
q := &survey.Question{
Prompt: &survey.Input{Message: "Hello world validation"},
Validate: func (val interface{}) error {
// 自定义验证
if str, ok := val.(string) ; !ok || len(str) > 10 {
return errors.New("This response cannot be longer than 10 characters.")
}
return nil
},
}
color := ""
prompt := &survey.Input{ Message: "Whats your name?" }
survey.AskOne(prompt, &color, survey.WithValidator(survey.Required))
小结
survey可以帮助我们快速开发出交互式命令行应用,使用简单,功能强大,文档齐全,欢迎使用
github地址:https://github.com/AlecAivazis/survey