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
18會員
83內容數
golang
留言0
查看全部
avatar-img
發表第一個留言支持創作者!
Alan的開發者天地 的其他內容
👨‍💻 簡介 在處理string時,正則表達式是一個非常有用的工具。Go語言的regexp package 可以使用正則表達式,用來執行如檢查string是否匹配某個模式、提取匹配的subString等操作。
👨‍💻 簡介 一開始介紹基本資料型別時有稍微提到一點string的處理,今天介紹string的一些操作,像是檢查的功能、修改的功能、比較的功能等等。
👨‍💻 簡介 昨天講到 os package,今天繼續補充 os package底下的 exec package,這個package主要用來執行外部指令和處理指令的輸入和輸出,包括如何設定指令、執行指令以及處理輸出等等。
👨‍💻 簡介 今天快速介紹一下對檔案的操作所使用的package os,包括檔案和資料夾操作等。 檔案和資料夾操作 os package 可以執行各種檔案和資料夾操作,如建立、讀取、寫入、刪除檔案,以及取得資料夾內容等。
👨‍💻簡介 在 Go 語言中,reflect package是用來檢查和操作變數的type、value和struct。常見用法有檢察 type、調用方法,以及修改變數的value。今天簡單介紹 reflect package的主要功能、使用方法和常見用法。
👨‍💻 簡介 今天的encoding/json package是我日常在開發web時很常用到的package之一,主要是用來將Go struct和 JSON 之間進行轉換。主要功能為資料序列化(marshalling)和反序列化(unmarshalling)。
👨‍💻 簡介 在處理string時,正則表達式是一個非常有用的工具。Go語言的regexp package 可以使用正則表達式,用來執行如檢查string是否匹配某個模式、提取匹配的subString等操作。
👨‍💻 簡介 一開始介紹基本資料型別時有稍微提到一點string的處理,今天介紹string的一些操作,像是檢查的功能、修改的功能、比較的功能等等。
👨‍💻 簡介 昨天講到 os package,今天繼續補充 os package底下的 exec package,這個package主要用來執行外部指令和處理指令的輸入和輸出,包括如何設定指令、執行指令以及處理輸出等等。
👨‍💻 簡介 今天快速介紹一下對檔案的操作所使用的package os,包括檔案和資料夾操作等。 檔案和資料夾操作 os package 可以執行各種檔案和資料夾操作,如建立、讀取、寫入、刪除檔案,以及取得資料夾內容等。
👨‍💻簡介 在 Go 語言中,reflect package是用來檢查和操作變數的type、value和struct。常見用法有檢察 type、調用方法,以及修改變數的value。今天簡單介紹 reflect package的主要功能、使用方法和常見用法。
👨‍💻 簡介 今天的encoding/json package是我日常在開發web時很常用到的package之一,主要是用來將Go struct和 JSON 之間進行轉換。主要功能為資料序列化(marshalling)和反序列化(unmarshalling)。
你可能也想看
Google News 追蹤
Thumbnail
就如同標題一樣,input的作用就是從使用者那裡獲取輸入,直到使用者輸入一段文本並按下 ENTER 鍵。 然而用戶輸入的數據(文本)都將作為字串被返回,並存儲在變數中。 接著我們舉個例,比如說我們在一段數據中需要獲取使用者的名稱,範例如下: name = input("請輸入你的名字:") #
Thumbnail
本文介紹了大型語言模型(LLM)中Prompt的原理及實踐,並提供了撰寫Prompt的基本框架邏輯PREP,以及加強Prompt撰寫的幾個方向:加強說明背景、角色描述和呈現風格,加強背景說明,角色描述,呈現風格以及目標受眾(TA)。同時推薦了幾個Prompt相關的參考網站。最後解答了一些快問快答。
Prompt 這個詞最近頻繁的出在我的生活中,究竟是為什麼呢?還有他帶來了什麼影響?
Thumbnail
在Python中,import是一個關鍵字,用於將其他模組或套件中的程式碼引入到當前的程式中以供使用。 這個關鍵字允許你在你的程式中使用其他地方定義的變數、函式和類等。 當你使用import時,Python會搜索指定模組或套件的位置,並將其中的程式碼載入到你的程式中,這樣你就可以在程式中使用它們
Thumbnail
<iostream> ​在之前的文章有提到過,<iostream> 是專門處理程式的輸入 (input) 以及輸出 (output) 的函式庫。輸入輸出的對象是以電腦作為主角: 輸入指的是「把資料給電腦」,輸出指的是「從電腦那邊取得資料」。 在這個系列的文章中,程式輸入指的都是從鍵盤輸入資料給電
Thumbnail
在程式開發中,協作合作專案時,利用type hint,可以快速知道函式輸入及輸出的資料型別,在後續的維護時也會更加方便及可讀。 Type hints 是Python 3.5 版本引入的功能,它允許在函數宣告中指定參數和傳回值的類型。Type hints 是一種可選的註解形式,不會影響程式碼的運行,
Thumbnail
與電腦溝通之方法說明 不須使用任何程式軟體工具,能與電腦溝通,使用Command line執行後,將依自己設定之條件,直接將結果選出,提供後續運用
Thumbnail
※ 必考題一: Command Line 工程師面試時通常不會著墨太多在此科目上,考題只考涵蓋的基本指令。 ※ 說明:Command Line是使用純文字與電腦溝通的方式,和圖形化介面 GUI是不一樣的。 ※ 常用基本指令: pwd=print the current directory:顯
Thumbnail
就如同標題一樣,input的作用就是從使用者那裡獲取輸入,直到使用者輸入一段文本並按下 ENTER 鍵。 然而用戶輸入的數據(文本)都將作為字串被返回,並存儲在變數中。 接著我們舉個例,比如說我們在一段數據中需要獲取使用者的名稱,範例如下: name = input("請輸入你的名字:") #
Thumbnail
本文介紹了大型語言模型(LLM)中Prompt的原理及實踐,並提供了撰寫Prompt的基本框架邏輯PREP,以及加強Prompt撰寫的幾個方向:加強說明背景、角色描述和呈現風格,加強背景說明,角色描述,呈現風格以及目標受眾(TA)。同時推薦了幾個Prompt相關的參考網站。最後解答了一些快問快答。
Prompt 這個詞最近頻繁的出在我的生活中,究竟是為什麼呢?還有他帶來了什麼影響?
Thumbnail
在Python中,import是一個關鍵字,用於將其他模組或套件中的程式碼引入到當前的程式中以供使用。 這個關鍵字允許你在你的程式中使用其他地方定義的變數、函式和類等。 當你使用import時,Python會搜索指定模組或套件的位置,並將其中的程式碼載入到你的程式中,這樣你就可以在程式中使用它們
Thumbnail
<iostream> ​在之前的文章有提到過,<iostream> 是專門處理程式的輸入 (input) 以及輸出 (output) 的函式庫。輸入輸出的對象是以電腦作為主角: 輸入指的是「把資料給電腦」,輸出指的是「從電腦那邊取得資料」。 在這個系列的文章中,程式輸入指的都是從鍵盤輸入資料給電
Thumbnail
在程式開發中,協作合作專案時,利用type hint,可以快速知道函式輸入及輸出的資料型別,在後續的維護時也會更加方便及可讀。 Type hints 是Python 3.5 版本引入的功能,它允許在函數宣告中指定參數和傳回值的類型。Type hints 是一種可選的註解形式,不會影響程式碼的運行,
Thumbnail
與電腦溝通之方法說明 不須使用任何程式軟體工具,能與電腦溝通,使用Command line執行後,將依自己設定之條件,直接將結果選出,提供後續運用
Thumbnail
※ 必考題一: Command Line 工程師面試時通常不會著墨太多在此科目上,考題只考涵蓋的基本指令。 ※ 說明:Command Line是使用純文字與電腦溝通的方式,和圖形化介面 GUI是不一樣的。 ※ 常用基本指令: pwd=print the current directory:顯