本文主要是介绍go之bubbletea可视化操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一 简介
bubbletea是一个简单、小巧、可以非常方便地用来编写 TUI(terminal User Interface,控制台界面程序)程序的框架。内置简单的事件处理机制,可以对外部事件做出响应,如键盘按键。
二 快速使用
bubbletea程序都需要有一个实现bubbletea.Model接口的类型:
type Model interface {
// Init is the first function that will be called. It returns an optional
// initial command. To not perform an initial command return nil.
//Init 是第一个被调用的函数。它返回一个可选的
//初始命令。不执行初始命令返回 nil。Init() Cmd//Update is called when a message is received. Use it to inspect messages//and, in response, update the model and/or send a command.
//收到消息时调用更新。用它来检查消息
//并且,作为响应,更新模型和/或发送命令。Update(Msg) (Model, Cmd)// View renders the program's UI, which is just a string. The view is
// rendered after every Update.
//View 渲染程序的 UI,它只是一个字符串。观点是
//每次更新后渲染。View() string
}
Init()
方法在程序启动时会立刻调用,它会做一些初始化工作,并返回一个Cmd告诉bubbletea要执行什么命令;
Update()
方法用来响应外部事件,返回一个修改后的模型,和想要bubbletea执行的命令;
View()
方法用于返回在控制台上显示的文本字符串。
package mainimport ("fmt"tea "github.com/charmbracelet/bubbletea""os"
)
//需要实现init update view三个方法
type model struct {items []stringindex int}func (m model) Init() tea.Cmd {return nil
}func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {switch msg := msg.(type) {case tea.KeyMsg:switch msg.String() {//当输入q或者ctrl+c 退出case "ctrl+c", "q":return m, tea.Quit// 如果是up 光标向上移动case "up":if m.index > 0 {m.index--}//如果是down 光标向下移动case "down":if m.index < len(m.items)-1 {m.index++}//如果是enter 处理事件case "enter":fmt.Println(m.items[m.index])return m,tea.Quit}}return m, nil
}
//渲染列表
func (m model) View() string {s := "欢迎来到k8s可视化系统\n\n"for i, item := range m.items {selected := " "if m.index == i {selected = "»"}s += fmt.Sprintf("%s %s\n", selected, item)}s += "\n按Q退出\n"return s
}
func main() {var initModel = model{items: []string{"我要看POD", "给我列出deployment", "我想看configmap"},}cmd := tea.NewProgram(initModel)if err := cmd.Start(); err != nil {fmt.Println("start failed:", err)os.Exit(1)}
}
ctrl+c
或q
:退出程序;
up
或k
:向上移动光标;
down
或j
:向下移动光标;
enter
或:切换光标处事项的完成状态。
处理ctrl+c
或q
按键时,返回一个特殊的tea.Quit
,通知bubbletea
需要退出程序。
这篇关于go之bubbletea可视化操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!