console

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2025 License: BSD-3-Clause Imports: 9 Imported by: 4

README


This package provides a set of tools for reading and validating user input from the terminal in Go applications. It supports reading hidden input (for passwords), numeric and decimal input, and selection from a list of values. Additionally, it offers mechanisms for retries, input validation with regular expressions, and setting default values.

Features:

  • Read Hidden Input: For sensitive data like passwords.
  • Validate Input: With regular expressions or custom constraints.
  • Read and Validate Numbers: Supports ranges for numeric inputs.
  • Select from Options: Simplifies prompting for a selection from predefined values.
  • Retry Mechanism: Allows multiple attempts for valid input.
  • Customizable Prompts: Set custom messages and formats for inputs.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecimalParser

func DecimalParser(input string, decimals int, vmin, vmax *float64) (float64, error)

DecimalParser converts the input string to a float and rounds it to the specified number of decimal places. It also validates the parsed float against optional minimum and maximum limits. Returns the rounded float or an error if the input is invalid or out of range.

func NumberParser

func NumberParser(input string, vmin, vmax *int64) (int64, error)

NumberParser converts the input string to an integer and validates it against optional minimum and maximum limits. Returns the parsed integer or an error if the input is invalid or out of range.

func RegexParser

func RegexParser(input string, regex string) (string, error)

RegexParser validates the input string using a provided regular expression. It returns the input if it matches the regex or an error if the input is invalid.

Types

type Console

type Console struct {
	Prompt string // Prompt is the string used to prompt the user.
	Trials int    // Trials defines how many input attempts are allowed.
	// contains filtered or unexported fields
}

Console handles input prompts and validation.

func New

func New(hnd Handler) (*Console, error)

New creates a new Console instance with the provided Handler. Returns an error if the handler is nil.

func NewTermConsole

func NewTermConsole() (*Console, error)

NewTermConsole creates a Console instance using a terminal handler. Returns an error if the terminal handler cannot be created.

func (*Console) Close

func (c *Console) Close() error

Close closes the console handler.

func (*Console) ConfirmValue

func (c *Console) ConfirmValue(msg, chkVal string) error

ConfirmValue prompts the user to input a specific value (e.g., for confirmation). It will compare the input with the provided check value.

func (*Console) Hidden

func (c *Console) Hidden() *Console

Hidden masks the input (useful for sensitive information like passwords).

func (*Console) ReadDecimal

func (c *Console) ReadDecimal(msg string, decimals int, defVal float64, limits ...float64) (float64, error)

ReadDecimal prompts the user for a decimal value with optional precision and limits.

func (*Console) ReadNumber

func (c *Console) ReadNumber(msg string, defVal int64, limits ...int64) (int64, error)

ReadNumber prompts the user for an integer value with optional minimum and maximum limits.

func (*Console) ReadValue

func (c *Console) ReadValue(msg string, defVal string) (string, error)

ReadValue prompts the user for a string value with an optional default. If the input is empty and not required, it returns the default.

Example
package main

import (
	"fmt"

	"github.com/exonlabs/go-utils/pkg/console"
)

func main() {
	con, _ := console.NewTermConsole()
	defer con.Close()

	// read input with optional value
	name, _ := con.ReadValue("Enter your name", "Anonymous")
	fmt.Println(name)

	// read required input
	name, _ = con.Required().ReadValue("Enter your name", "")
	fmt.Println(name)

	// read a required input with echo off (hidden input)
	passwd, _ := con.Hidden().Required().ReadValue("Enter password", "")
	fmt.Println(passwd)
}
Output:

func (*Console) Regex

func (c *Console) Regex(regex string) *Console

Regex sets a regular expression to validate the input.

func (*Console) Required

func (c *Console) Required() *Console

Required marks the input as mandatory.

func (*Console) SelectValue

func (c *Console) SelectValue(msg string, values []string, defVal string) (string, error)

SelectValue prompts the user to choose from a list of string values.

Example
package main

import (
	"fmt"

	"github.com/exonlabs/go-utils/pkg/console"
)

func main() {
	con, _ := console.NewTermConsole()
	defer con.Close()

	color, _ := con.SelectValue("Select color?",
		[]string{"Red", "Blue", "Green"}, "Red")
	fmt.Println(color)
}
Output:

func (*Console) SelectYesNo

func (c *Console) SelectYesNo(msg string, defVal string) (bool, error)

SelectYesNo prompts the user for a yes/no selection. Returns true for "y" and false for "n".

Example
package main

import (
	"fmt"

	"github.com/exonlabs/go-utils/pkg/console"
)

func main() {
	con, _ := console.NewTermConsole()
	defer con.Close()

	yes, _ := con.SelectYesNo("Continue?", "y")
	fmt.Println(yes)
}
Output:

type Handler

type Handler interface {
	Read(string) (string, error)       // Read reads input with a prompt.
	ReadHidden(string) (string, error) // ReadHidden reads input without echoing (for passwords).
	Write(string) error                // Write outputs a formatted message to the console.
	Close() error                      // Close cleans up any resources used by the handler.
}

Handler defines the interface for reading and writing from/to the console. It includes methods to read regular and hidden input, write output, and close the handler.

type TermHandler

type TermHandler struct {
	// contains filtered or unexported fields
}

TermHandler is a terminal-based implementation of the Handler interface. It uses the 'golang.org/x/term' package for reading input from the terminal.

func NewTermHandler

func NewTermHandler() (*TermHandler, error)

NewTermHandler creates and returns a new TermHandler for reading from and writing to the terminal.

func (*TermHandler) Close

func (h *TermHandler) Close() error

Close implements the Handler interface but does not need to perform any action for TermHandler.

func (*TermHandler) Read

func (h *TermHandler) Read(msg string) (string, error)

Read prompts the user for input and returns the trimmed result. It sets the terminal to raw mode while reading.

func (*TermHandler) ReadHidden

func (h *TermHandler) ReadHidden(msg string) (string, error)

ReadHidden prompts the user for hidden input (e.g., for passwords) without echoing it back to the terminal.

func (*TermHandler) Write

func (h *TermHandler) Write(msg string) error

Write writes a message to the console.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳