「GoCN酷Go推荐」交互式命令行工具库survey
GoCN
共 5643字,需浏览 12分钟
·
2021-10-02 03:06
☆ 什么是 survey? ☆
survey 可以让你方便的在终端上构建交互式和可访问提示的应用,支持ANSI
☆ 安装 ☆
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内置了几种Validators
Required 要求必填 MinLength(n) 输入字符最小长度验证 MaxLength(n) 输入字符最大长度验证 MaxItems(n) 选项最多验证 MinItems(n) 选项最小验证
☆ 总结 ☆
survey可以帮助我们快速开发出交互式命令行应用,使用简单,功能强大,文档齐全,欢迎使用
☆ 参考链接☆
https://github.com/AlecAivazis/survey
《酷Go推荐》招募:
各位Gopher同学,最近我们社区打算推出一个类似GoCN每日新闻的新栏目《酷Go推荐》,主要是每周推荐一个库或者好的项目,然后写一点这个库使用方法或者优点之类的,这样可以真正的帮助到大家能够学习到
新的库,并且知道怎么用。
大概规则和每日新闻类似,如果报名人多的话每个人一个月轮到一次,欢迎大家报名!戳「阅读原文」,即可报名
扫码也可以加入 GoCN 的大家族哟~
评论