Help us shape the future of Go! Take the 2026 Go Developer Survey

axon

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 5, 2026 License: MIT Imports: 4 Imported by: 0

README

Axon

Axon is a lightweight Go library for building interactive command-line applications, providing simple and easy-to-use terminal interaction features.

Features

  • Simple and easy-to-use API, focused on providing quality terminal interaction experiences
  • Supports multiple interaction methods: standard questions, confirmations, password input, phone number input, single select, multi select, searchable select, keyboard select, multiline text, typed inputs, dangerous confirmations, form wizards, progress bars, and spinners
  • Built-in data validation and formatting functions
  • Support for default values
  • Each interaction mode has its own interface and default implementation, making implementations easy to replace
  • Automatic masking of phone numbers to protect user privacy
  • Colored output support for enhanced visual experience

Millisecond Mirror Configuration Tool Screenshot

Installation

go get github.com/muleiwu/axon

Quick Start

package main

import (
	"fmt"
	"github.com/muleiwu/axon"
	"github.com/muleiwu/axon/pkg/question"
)

func main() {
	// Standard question
	name := axon.Question("Please enter your name: ", "")
	fmt.Printf("Hello, %s!\n", name)
	
	// Confirmation question
	proceed := axon.Confirm("Continue? (y/n) ", true)
	if proceed {
		fmt.Println("Continuing...")
	} else {
		fmt.Println("Cancelled")
		return
	}
	
	// Password input (hidden display)
	password := axon.Password("Please enter password: ", "")
	fmt.Println("Password saved")
	
	// Phone number (with validation and masking)
	phone := axon.PhoneNumber("Please enter mobile number: ", "")
	fmt.Println("Mobile number saved")
	
	// Selection list
	items := []question.SelectionItem{
		{Label: "Option 1", Description: "This is the first option", Value: "option1"},
		{Label: "Option 2", Description: "This is the second option", Value: "option2"},
		{Label: "Option 3", Description: "This is the third option", Value: "option3"},
	}
	selected := axon.Selection("Please select an option:", items)
	
	if selected == "exit" {
		fmt.Println("You chose to exit")
	} else {
		fmt.Printf("You selected: %s\n", selected)
	}

	// Multi select
	selectedValues := axon.MultiSelect("Please select options:", items)
	fmt.Printf("You selected: %v\n", selectedValues)

	// Typed inputs
	age := axon.Number("Please enter age: ", 18)
	email := axon.Email("Please enter email: ", "")
	fmt.Println(age, email)

	// Form wizard
	result := axon.Form("Create user", []axon.FormField{
		{Name: "name", Question: "Name: ", Kind: axon.FieldText, Required: true},
		{Name: "email", Question: "Email: ", Kind: axon.FieldEmail, Required: true},
		{Name: "admin", Question: "Admin? ", Kind: axon.FieldConfirm},
	})
	fmt.Printf("%#v\n", result)
}

API Reference

Standard Question
func Question(question string, defaultValue string) string

Ask the user a standard question and get text input.

  • question: The question text to display to the user
  • defaultValue: Default value, used when the user presses enter directly
  • Returns: The string entered by the user
Confirmation Question
func Confirm(question string, defaultValue bool) bool

Ask the user a confirmation question to get a yes/no answer.

  • question: The question text to display to the user
  • defaultValue: Default value, used when the user presses enter directly
  • Returns: The user's selection result (true/false)
Password Input
func Password(question string, defaultValue string) string

Ask the user for a password, which will be hidden during input.

  • question: The question text to display to the user
  • defaultValue: Default value, used when the user presses enter directly
  • Returns: The password string entered by the user
Phone Number Input
func PhoneNumber(question string, defaultValue string) string

Ask the user for a phone number, with format validation. The input is automatically masked to protect user privacy.

  • question: The question text to display to the user
  • defaultValue: Default value, used when the user presses enter directly
  • Returns: The validated phone number string
Selection List
func Selection(question string, items []SelectionItem) string

Let the user select an item from a list.

  • question: The question text to display to the user
  • items: The list of selection items
  • Returns: The Value of the selected item, or "exit" if the user chooses to exit
Multi Select
func MultiSelect(question string, items []SelectionItem) []string

Let the user select multiple items. In a terminal, use Arrow keys to move, Space to toggle, Enter to finish, and q to exit. j/k navigation and a select/clear all are also supported as shortcuts. Piped input and SetInput continue to support 1,3-5 and all; exiting returns an empty slice.

Search Select
func SearchSelect(question string, items []SelectionItem) string

Filter options by keyword first, then ask the user to select from the matches.

Keyboard Select
func KeyboardSelect(question string, items []SelectionItem) string

Navigate with arrow keys or j/k, confirm with Enter, and exit with q.

Validated Question
func ValidatedQuestion(question string, defaultValue string, validators ...Validator) string

Read text input and run one or more custom validators. Returning an error asks the user again.

Typed Inputs
func Number(question string, defaultValue int) int
func Email(question string, defaultValue string) string
func URL(question string, defaultValue string) string
func Path(question string, defaultValue string, mustExist bool) string
func DateTime(question string, defaultValue time.Time, layout string) time.Time

Read integer, email, URL, path, and time values. DateTime uses 2006-01-02 15:04:05 when layout is empty.

Multiline Text
func MultiLine(question string, defaultValue string) string

Read multiline text. Enter a single . line to finish.

Dangerous Confirmation
func DangerousConfirm(question string, expected string) bool

Return true only when the user types expected exactly. Useful for destructive operations.

Form Wizard
func Form(title string, fields []FormField) FormResult
func Wizard(title string, fields []FormField) FormResult

Collect multiple fields in order and return a map[string]any. Wizard is a semantic alias for Form.

Progress Interactions
func Spinner(message string) SpinnerController
func Progress(total int, message string) ProgressReporter

Use Spinner for indeterminate tasks and Progress for tasks with a known total.

Custom Selection Items

When creating a selection list, you can define options using the SelectionItem structure:

type SelectionItem struct {
	Label       string // The display label
	Description string // Description information
	Value       string // Actual value
	Disabled    bool   // Whether the item is disabled
}

Replacing Implementations

Each interaction mode has a dedicated interface in pkg/interfaces, and default implementations live in pkg/question. Replace any mode through its setter:

type MyQuestioner struct{}

func (MyQuestioner) Ask(question string, defaultValue string) string {
	return defaultValue
}

func main() {
	axon.SetQuestioner(MyQuestioner{})
	name := axon.Question("Please enter name: ", "axon")
	fmt.Println(name)
}

License

This project is open source under the LICENSE license.

Documentation

Index

Constants

View Source
const (
	FieldText        = prompt.FieldText
	FieldValidated   = prompt.FieldValidated
	FieldPassword    = prompt.FieldPassword
	FieldPhoneNumber = prompt.FieldPhoneNumber
	FieldEmail       = prompt.FieldEmail
	FieldURL         = prompt.FieldURL
	FieldPath        = prompt.FieldPath
	FieldNumber      = prompt.FieldNumber
	FieldDateTime    = prompt.FieldDateTime
	FieldMultiLine   = prompt.FieldMultiLine
	FieldConfirm     = prompt.FieldConfirm
	FieldSelect      = prompt.FieldSelect
	FieldMultiSelect = prompt.FieldMultiSelect
)

Variables

This section is empty.

Functions

func Confirm

func Confirm(question string, defaultValue bool) bool

Confirm 询问用户确认问题 question: 要显示给用户的问题文本 defaultValue: 默认值,当用户直接按回车时使用 返回: 用户的选择结果(true/false)

func DangerousConfirm added in v1.1.0

func DangerousConfirm(question string, expected string) bool

DangerousConfirm 要求用户输入 expected 后才返回 true。

func DateTime added in v1.1.0

func DateTime(question string, defaultValue time.Time, layout string) time.Time

DateTime 按 layout 读取时间。layout 为空时使用默认时间格式。

func Email added in v1.1.0

func Email(question string, defaultValue string) string

Email 读取并校验邮箱地址。

func KeyboardSelect added in v1.1.0

func KeyboardSelect(question string, items []SelectionItem) string

KeyboardSelect 使用键盘导航选择一项。

func MultiLine added in v1.1.0

func MultiLine(question string, defaultValue string) string

MultiLine 读取多行文本。

func MultiSelect added in v1.1.0

func MultiSelect(question string, items []SelectionItem) []string

MultiSelect 让用户从列表中选择多项,退出时返回空切片。 真实终端使用方向键移动、空格选中、回车完成;管道或 SetInput 输入继续支持 1,3-5 和 all 文本格式。

func Number added in v1.1.0

func Number(question string, defaultValue int) int

Number 读取整数输入。

func Password

func Password(question string, defaultValue string) string

Password 询问用户密码 输入过程中密码会被隐藏显示 question: 要显示给用户的问题文本 defaultValue: 默认值,当用户直接按回车时使用 返回: 用户输入的密码字符串

func Path added in v1.1.0

func Path(question string, defaultValue string, mustExist bool) string

Path 读取路径。mustExist 为 true 时要求路径存在。

func PhoneNumber

func PhoneNumber(question string, defaultValue string) string

PhoneNumber 询问用户电话号码 包含格式验证功能 question: 要显示给用户的问题文本 defaultValue: 默认值,当用户直接按回车时使用 返回: 经过验证的电话号码字符串

func Question

func Question(question string, defaultValue string) string

Question 询问用户普通问题 question: 要显示给用户的问题文本 defaultValue: 默认值,当用户直接按回车时使用 返回: 用户输入的字符串

func ResetInput added in v1.1.0

func ResetInput()

ResetInput restores the default prompt input source to os.Stdin.

func SearchSelect added in v1.1.0

func SearchSelect(question string, items []SelectionItem) string

SearchSelect 根据关键字过滤列表,再让用户选择一项。

func Selection

func Selection(question string, items []SelectionItem) string

Selection 让用户从列表中选择一项 question: 要显示给用户的问题文本 items: 选择项列表 返回: 用户选择的项目的Value,如果选择退出则返回"exit"

func SetConfirmer added in v1.1.0

func SetConfirmer(impl prompt.Confirmer)

func SetDangerousConfirmer added in v1.1.0

func SetDangerousConfirmer(impl prompt.DangerousConfirmer)

func SetDateTimeInput added in v1.1.0

func SetDateTimeInput(impl prompt.DateTimeInput)

func SetEmailInput added in v1.1.0

func SetEmailInput(impl prompt.EmailInput)

func SetFormRunner added in v1.1.0

func SetFormRunner(impl prompt.FormRunner)

func SetInput added in v1.1.0

func SetInput(input io.Reader)

SetInput replaces the input source used by the default prompt implementations. It is useful for tests and scripted/non-interactive integrations.

func SetKeyboardSelector added in v1.1.0

func SetKeyboardSelector(impl prompt.KeyboardSelector)

func SetMultiLineInput added in v1.1.0

func SetMultiLineInput(impl prompt.MultiLineInput)

func SetMultiSelector added in v1.1.0

func SetMultiSelector(impl prompt.MultiSelector)

func SetNumberInput added in v1.1.0

func SetNumberInput(impl prompt.NumberInput)

func SetPasswordReader added in v1.1.0

func SetPasswordReader(impl prompt.PasswordReader)

func SetPathInput added in v1.1.0

func SetPathInput(impl prompt.PathInput)

func SetPhoneNumberReader added in v1.1.0

func SetPhoneNumberReader(impl prompt.PhoneNumberReader)

func SetProgress added in v1.1.0

func SetProgress(impl prompt.Progress)

func SetQuestioner added in v1.1.0

func SetQuestioner(impl prompt.Questioner)

func SetSearchSelector added in v1.1.0

func SetSearchSelector(impl prompt.SearchSelector)

func SetSelector added in v1.1.0

func SetSelector(impl prompt.Selector)

func SetSpinner added in v1.1.0

func SetSpinner(impl prompt.Spinner)

func SetURLInput added in v1.1.0

func SetURLInput(impl prompt.URLInput)

func SetValidatedQuestioner added in v1.1.0

func SetValidatedQuestioner(impl prompt.ValidatedQuestioner)

func URL added in v1.1.0

func URL(question string, defaultValue string) string

URL 读取并校验 URL。

func ValidatedQuestion added in v1.1.0

func ValidatedQuestion(question string, defaultValue string, validators ...Validator) string

ValidatedQuestion 询问用户普通问题,并使用自定义校验器校验输入。

Types

type FieldKind added in v1.1.0

type FieldKind = prompt.FieldKind

type FormField added in v1.1.0

type FormField = prompt.FormField

type FormResult added in v1.1.0

type FormResult = prompt.FormResult

func Form added in v1.1.0

func Form(title string, fields []FormField) FormResult

Form 执行多字段表单。

func Wizard added in v1.1.0

func Wizard(title string, fields []FormField) FormResult

Wizard 是 Form 的语义化别名。

type ProgressReporter added in v1.1.0

type ProgressReporter = prompt.ProgressReporter

func Progress added in v1.1.0

func Progress(total int, message string) ProgressReporter

Progress 启动一个命令行进度条。

type SelectionItem added in v1.1.0

type SelectionItem = prompt.SelectionItem

type SpinnerController added in v1.1.0

type SpinnerController = prompt.SpinnerController

func Spinner added in v1.1.0

func Spinner(message string) SpinnerController

Spinner 启动一个命令行 spinner。

type Validator added in v1.1.0

type Validator = prompt.Validator

Directories

Path Synopsis
pkg

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL