Promptui教學:快速建立 Go 語言的交互式介面

更新於 發佈於 閱讀時間約 24 分鐘


raw-image

👨‍💻簡介

今天來介紹一個自己開發後端蠻常用的一個 package,promptui,拿來做menu真的很方便,promptui有兩個主要的輸入模式:

  1. Prompt:跳出單行使用者輸入。
  2. Select:提供一個選項列表供使用者選擇。

Prompt

prompt是一個struct,當執行Run時會返回輸入的結果

type Prompt struct {
// Label is the value displayed on the command line prompt.
//
// The value for Label can be a simple string or a struct that will need to be accessed by dot notation
// inside the templates. For example, `{{ .Name }}` will display the name property of a struct.
Label interface{}

// Default is the initial value for the prompt. This value will be displayed next to the prompt's label
// and the user will be able to view or change it depending on the options.
Default string

// AllowEdit lets the user edit the default value. If false, any key press
// other than <Enter> automatically clears the default value.
AllowEdit bool

// Validate is an optional function that fill be used against the entered value in the prompt to validate it.
Validate ValidateFunc

// Mask is an optional rune that sets which character to display instead of the entered characters. This
// allows hiding private information like passwords.
Mask rune

// HideEntered sets whether to hide the text after the user has pressed enter.
HideEntered bool

// Templates can be used to customize the prompt output. If nil is passed, the
// default templates are used. See the PromptTemplates docs for more info.
Templates *PromptTemplates

// IsConfirm makes the prompt ask for a yes or no ([Y/N]) question rather than request an input. When set,
// most properties related to input will be ignored.
IsConfirm bool

// IsVimMode enables vi-like movements (hjkl) and editing.
IsVimMode bool

// the Pointer defines how to render the cursor.
Pointer Pointer

Stdin io.ReadCloser
Stdout io.WriteCloser
}

語法如下:

func (*promptui.Prompt).Run() (string, error)
package main

import (
"fmt"
"github.com/manifoldco/promptui"
)
func main() {

prompt := promptui.Prompt{
Label: "Anything",
}
result, err := prompt.Run()
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}

fmt.Printf("You typed %q\n", result)
}

確認(Confirm)

建立一個確認提示,使用者可以選擇是或否。

package main

import (
"fmt"
"github.com/manifoldco/promptui"
)

func main() {
prompt := promptui.Prompt{
Label: "Delete all resources",
IsConfirm: true,
}

_, err := prompt.Run()

if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}

fmt.Printf("Resources deleted")
}

自定義提示(Custom Prompt)

這個功能是讓使用者可以自己定義提示的外觀和行為。例如,你可以更改提示的顏色,標籤和其他設定。

package main

import (
"fmt"
"errors"
"github.com/manifoldco/promptui"
)

func main() {
prompt := promptui.Prompt{
Label: "Enter your name",
Validate: func(input string) error {
if len(input) < 3 {
return errors.New("Name must have more than 3 characters")
}
return nil
},
}

result, err := prompt.Run()

if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}

fmt.Printf("Hello %q\n", result)
}

提示預設值(Prompt Default)

Promptui 支援設定提示的預設值。

package main

import (
"fmt"
"github.com/manifoldco/promptui"
)

func main() {
prompt := promptui.Prompt{
Label: "Enter your name",
Default: "Alan",
}

result, err := prompt.Run()

if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}

fmt.Printf("Hello %q\n", result)
}

密碼提示(Password Prompt)

Promptui 可以用來建立一個密碼提示,其中使用者輸入的文本將被掩蓋。

package main

import (
"fmt"
"github.com/manifoldco/promptui"
)

func main() {
prompt := promptui.Prompt{
Label: "Enter Password",
Mask: '*',
}

result, err := prompt.Run()

if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}

fmt.Printf("Password entered: %q\n", result)
}

Select

Select也是一個struct,與Prompt不同的是當執行Run時會返回index以及選中的結果

type Select struct {
// Label is the text displayed on top of the list to direct input. The IconInitial value "?" will be
// appended automatically to the label so it does not need to be added.
//
// The value for Label can be a simple string or a struct that will need to be accessed by dot notation
// inside the templates. For example, `{{ .Name }}` will display the name property of a struct.
Label interface{}

// Items are the items to display inside the list. It expect a slice of any kind of values, including strings.
//
// If using a slice of strings, promptui will use those strings directly into its base templates or the
// provided templates. If using any other type in the slice, it will attempt to transform it into a string
// before giving it to its templates. Custom templates will override this behavior if using the dot notation
// inside the templates.
//
// For example, `{{ .Name }}` will display the name property of a struct.
Items interface{}

// Size is the number of items that should appear on the select before scrolling is necessary. Defaults to 5.
Size int

// CursorPos is the initial position of the cursor.
CursorPos int

// IsVimMode sets whether to use vim mode when using readline in the command prompt. Look at
// https://godoc.org/github.com/chzyer/readline#Config for more information on readline.
IsVimMode bool

// HideHelp sets whether to hide help information.
HideHelp bool

// HideSelected sets whether to hide the text displayed after an item is successfully selected.
HideSelected bool

// Templates can be used to customize the select output. If nil is passed, the
// default templates are used. See the SelectTemplates docs for more info.
Templates *SelectTemplates

// Keys is the set of keys used in select mode to control the command line interface. See the SelectKeys docs for
// more info.
Keys *SelectKeys

// Searcher is a function that can be implemented to refine the base searching algorithm in selects.
//
// Search is a function that will receive the searched term and the item's index and should return a boolean
// for whether or not the terms are alike. It is unimplemented by default and search will not work unless
// it is implemented.
Searcher list.Searcher

// StartInSearchMode sets whether or not the select mode should start in search mode or selection mode.
// For search mode to work, the Search property must be implemented.
StartInSearchMode bool

list *list.List

// A function that determines how to render the cursor
Pointer Pointer

Stdin io.ReadCloser
Stdout io.WriteCloser
}

語法如下:

func (*promptui.Select).Run() (int, string, error)
func (*promptui.Select).RunCursorAt(cursorPos int, scroll int) (int, string, error)
func (*promptui.Select).ScrollPosition() int
package main

import (
"fmt"
"github.com/manifoldco/promptui"
)

func main() {
prompt := promptui.Select{
Label: "Select Day",
Items: []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday"},
}
_, result, err := prompt.Run()
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}
fmt.Printf("You choose %q\n", result)
}

自定義選擇(Custom Select)

除了基本的選擇提示外,Promptui 還允許使用者自定義選擇列表的外觀和行為。

package main

import (
"fmt"
"github.com/manifoldco/promptui"
)

func main() {
prompt := promptui.Select{
Label: "Choose Color",
Items: []string{"Red", "Blue", "Green"},
Templates: &promptui.SelectTemplates{
Label: "{{ . }}?",
Active: "\U0001F336 {{ . | red }}",
Inactive: " {{ . | cyan }}",
Selected: "\U0001F336 {{ . | red | cyan }}",
},
}

_, result, err := prompt.Run()

if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}

fmt.Printf("You choose %q\n", result)
}

選擇添加(Select Add)

Promptui 還允許使用者在選擇提示中添加新的選項。

package main

import (
"fmt"
"github.com/manifoldco/promptui"
)

func main() {
items := []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
prompt := promptui.SelectWithAdd{
Label: "What day is it?",
Items: items,
AddLabel: "Other",
}
idx, result, err := prompt.Run()

if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}
if idx == len(items) {
fmt.Printf("You chose to add %q\n", result)
} else {
fmt.Printf("You chose %q\n", result)
}
}

📚Reference

留言
avatar-img
留言分享你的想法!
avatar-img
Alan的開發者天地
18會員
83內容數
golang
Alan的開發者天地的其他內容
2023/10/04
👨‍💻 簡介 最近想要透過小實作來撰寫筆記,達到做中學的效果,因此就來實作個小爬蟲順便結合前面學到的package做一個小複習。
Thumbnail
2023/10/04
👨‍💻 簡介 最近想要透過小實作來撰寫筆記,達到做中學的效果,因此就來實作個小爬蟲順便結合前面學到的package做一個小複習。
Thumbnail
2023/09/26
👨‍💻 簡介 在處理string時,正則表達式是一個非常有用的工具。Go語言的regexp package 可以使用正則表達式,用來執行如檢查string是否匹配某個模式、提取匹配的subString等操作。
Thumbnail
2023/09/26
👨‍💻 簡介 在處理string時,正則表達式是一個非常有用的工具。Go語言的regexp package 可以使用正則表達式,用來執行如檢查string是否匹配某個模式、提取匹配的subString等操作。
Thumbnail
2023/09/22
👨‍💻 簡介 一開始介紹基本資料型別時有稍微提到一點string的處理,今天介紹string的一些操作,像是檢查的功能、修改的功能、比較的功能等等。
Thumbnail
2023/09/22
👨‍💻 簡介 一開始介紹基本資料型別時有稍微提到一點string的處理,今天介紹string的一些操作,像是檢查的功能、修改的功能、比較的功能等等。
Thumbnail
看更多
你可能也想看
Thumbnail
大家好,我是一名眼科醫師,也是一位孩子的媽 身為眼科醫師的我,我知道視力發展對孩子來說有多關鍵。 每到開學季時,診間便充斥著許多憂心忡忡的家屬。近年來看診中,兒童提早近視、眼睛疲勞的案例明顯增加,除了3C使用過度,最常被忽略的,就是照明品質。 然而作為一位媽媽,孩子能在安全、舒適的環境
Thumbnail
大家好,我是一名眼科醫師,也是一位孩子的媽 身為眼科醫師的我,我知道視力發展對孩子來說有多關鍵。 每到開學季時,診間便充斥著許多憂心忡忡的家屬。近年來看診中,兒童提早近視、眼睛疲勞的案例明顯增加,除了3C使用過度,最常被忽略的,就是照明品質。 然而作為一位媽媽,孩子能在安全、舒適的環境
Thumbnail
我的「媽」呀! 母親節即將到來,vocus 邀請你寫下屬於你的「媽」故事——不管是紀錄爆笑的日常,或是一直想對她表達的感謝,又或者,是你這輩子最想聽她說出的一句話。 也歡迎你曬出合照,分享照片背後的點點滴滴 ♥️ 透過創作,將這份情感表達出來吧!🥹
Thumbnail
我的「媽」呀! 母親節即將到來,vocus 邀請你寫下屬於你的「媽」故事——不管是紀錄爆笑的日常,或是一直想對她表達的感謝,又或者,是你這輩子最想聽她說出的一句話。 也歡迎你曬出合照,分享照片背後的點點滴滴 ♥️ 透過創作,將這份情感表達出來吧!🥹
Thumbnail
👨‍💻 簡介 最近想要透過小實作來撰寫筆記,達到做中學的效果,因此就來實作個小爬蟲順便結合前面學到的package做一個小複習。
Thumbnail
👨‍💻 簡介 最近想要透過小實作來撰寫筆記,達到做中學的效果,因此就來實作個小爬蟲順便結合前面學到的package做一個小複習。
Thumbnail
👨‍💻簡介 今天來介紹一個自己開發後端蠻常用的一個 package,promptui,拿來做menu真的很方便,promptui有兩個主要的輸入模式: Prompt:跳出單行使用者輸入。 Select:提供一個選項列表供使用者選擇。
Thumbnail
👨‍💻簡介 今天來介紹一個自己開發後端蠻常用的一個 package,promptui,拿來做menu真的很方便,promptui有兩個主要的輸入模式: Prompt:跳出單行使用者輸入。 Select:提供一個選項列表供使用者選擇。
Thumbnail
👨‍💻 簡介 在處理string時,正則表達式是一個非常有用的工具。Go語言的regexp package 可以使用正則表達式,用來執行如檢查string是否匹配某個模式、提取匹配的subString等操作。
Thumbnail
👨‍💻 簡介 在處理string時,正則表達式是一個非常有用的工具。Go語言的regexp package 可以使用正則表達式,用來執行如檢查string是否匹配某個模式、提取匹配的subString等操作。
Thumbnail
👨‍💻 簡介 一開始介紹基本資料型別時有稍微提到一點string的處理,今天介紹string的一些操作,像是檢查的功能、修改的功能、比較的功能等等。
Thumbnail
👨‍💻 簡介 一開始介紹基本資料型別時有稍微提到一點string的處理,今天介紹string的一些操作,像是檢查的功能、修改的功能、比較的功能等等。
Thumbnail
👨‍💻 簡介 昨天講到 os package,今天繼續補充 os package底下的 exec package,這個package主要用來執行外部指令和處理指令的輸入和輸出,包括如何設定指令、執行指令以及處理輸出等等。
Thumbnail
👨‍💻 簡介 昨天講到 os package,今天繼續補充 os package底下的 exec package,這個package主要用來執行外部指令和處理指令的輸入和輸出,包括如何設定指令、執行指令以及處理輸出等等。
Thumbnail
您是否苦於網路資訊爆炸嗎? 教學何其多,但卻無法好好選擇的困境呢? 歡迎加入「🔒 阿Han的軟體心法實戰營」, 這裡不給您冗餘的雜訊, 單刀直入直接送您重點, 避開選擇障礙的困境, 讓您獲得業界標準的開發起手式, 成為Top 1的頂尖人才。 我們是不是常常看到一些很厲害的專案, 只要「pip i
Thumbnail
您是否苦於網路資訊爆炸嗎? 教學何其多,但卻無法好好選擇的困境呢? 歡迎加入「🔒 阿Han的軟體心法實戰營」, 這裡不給您冗餘的雜訊, 單刀直入直接送您重點, 避開選擇障礙的困境, 讓您獲得業界標準的開發起手式, 成為Top 1的頂尖人才。 我們是不是常常看到一些很厲害的專案, 只要「pip i
Thumbnail
👨‍💻簡介 在 Go 語言中,函數(Function)是一個強大且重要的概念,就像食譜一樣,告訴你應該如何處理食材,最後得到一道美味的料理。經過哪些程序讓程式更有組織性和可讀性。函數可幫助你將程式碼區塊組織成可重複使用的元件,進而執行特定的任務。
Thumbnail
👨‍💻簡介 在 Go 語言中,函數(Function)是一個強大且重要的概念,就像食譜一樣,告訴你應該如何處理食材,最後得到一道美味的料理。經過哪些程序讓程式更有組織性和可讀性。函數可幫助你將程式碼區塊組織成可重複使用的元件,進而執行特定的任務。
Thumbnail
👨‍💻簡介 在這篇文章裡,會簡單介紹幾個關鍵的基本概念和語法結構,加快上手這門程式語言。
Thumbnail
👨‍💻簡介 在這篇文章裡,會簡單介紹幾個關鍵的基本概念和語法結構,加快上手這門程式語言。
Thumbnail
這篇文章我們將深入如何利用chatgpt模擬 Python 終端 在ChatGPT 的幫助下,可以構建一個功能完備的 Python 終端模擬器 啟動 ChatGPT 並開始使用我們的 Python 終端 Prompt: I want you to act as a Python terminal,
Thumbnail
這篇文章我們將深入如何利用chatgpt模擬 Python 終端 在ChatGPT 的幫助下,可以構建一個功能完備的 Python 終端模擬器 啟動 ChatGPT 並開始使用我們的 Python 終端 Prompt: I want you to act as a Python terminal,
追蹤感興趣的內容從 Google News 追蹤更多 vocus 的最新精選內容追蹤 Google News