Documentation
¶
Overview ¶
Package console provides enhanced terminal I/O utilities for Go applications. It offers colored output, interactive prompts, text formatting, and UTF-8 text padding.
The package wraps fatih/color for ANSI color support and adds:
- Thread-safe color management with multiple color types
- UTF-8 aware text padding (left, right, center)
- Interactive user prompts with type validation
- Hierarchical output with indentation
- Buffer writing for testing and non-terminal output
Example usage:
import (
"github.com/fatih/color"
"github.com/nabbar/golib/console"
)
// Set colors
console.SetColor(console.ColorPrint, int(color.FgCyan), int(color.Bold))
// Print colored text
console.ColorPrint.Println("Hello, World!")
// Get user input
name, _ := console.PromptString("Enter your name")
// Format text
title := console.PadCenter("My App", 40, "=")
Index ¶
- Constants
- func DelColor(id ColorType)
- func GetColor(id ColorType) *color.Color
- func PadCenter(str string, len int, pad string) string
- func PadLeft(str string, len int, pad string) string
- func PadRight(str string, len int, pad string) string
- func PrintTabf(tablLevel int, format string, args ...interface{})
- func PromptBool(text string) (bool, error)
- func PromptInt(text string) (int64, error)
- func PromptPassword(text string) (string, error)
- func PromptString(text string) (string, error)
- func PromptUrl(text string) (*url.URL, error)
- func SetColor(id ColorType, value ...int)
- type ColorType
- func (c ColorType) BuffPrintf(buff io.Writer, format string, args ...interface{}) (int, error)
- func (c ColorType) Print(text string)
- func (c ColorType) PrintLnf(format string, args ...interface{})
- func (c ColorType) Printf(format string, args ...interface{})
- func (c ColorType) Println(text string)
- func (c ColorType) SetColor(col *color.Color)
- func (c ColorType) Sprintf(format string, args ...interface{}) string
Constants ¶
const ( // ErrorParamEmpty indicates that required parameters were not provided or are empty. ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgConsole // ErrorColorIOFprintf indicates a failure to write formatted output to an io.Writer. ErrorColorIOFprintf // ErrorColorBufWrite indicates a failure to write data to a buffer. ErrorColorBufWrite // ErrorColorBufUndefined indicates that a required buffer was nil or not defined. // This occurs when BuffPrintf is called with a nil io.Writer. ErrorColorBufUndefined )
Error codes for the console package. These codes are registered with the golib/errors package for structured error handling.
Variables ¶
This section is empty.
Functions ¶
func DelColor ¶ added in v1.19.0
func DelColor(id ColorType)
DelColor removes the color configuration for a ColorType. After deletion, the ColorType will use an empty color (no coloring).
Parameters:
- id: The ColorType to remove
Thread-safe: Can be called concurrently from multiple goroutines.
Example:
console.DelColor(console.ColorPrint)
func GetColor ¶ added in v1.19.0
GetColor retrieves the color.Color instance for a ColorType. Returns an empty color.Color if the ColorType hasn't been configured.
Parameters:
- id: The ColorType to retrieve
Returns:
- Pointer to color.Color instance (never nil)
Thread-safe: Can be called concurrently from multiple goroutines.
Example:
c := console.GetColor(console.ColorPrint)
c.Println("Colored text")
func PadCenter ¶ added in v1.10.4
PadCenter centers a string with padding on both sides. Uses UTF-8 rune counting to correctly handle multi-byte characters. If padding cannot be distributed evenly, the right side gets one extra pad character.
Parameters:
- str: The string to center
- len: The desired total length in runes (not bytes)
- pad: The padding string (typically " ", "=", or "-")
Returns:
- Centered string with length 'len' runes
UTF-8 Support: Correctly handles emojis, CJK characters, and multi-byte Unicode.
Example:
PadCenter("text", 10, " ") // Returns " text "
PadCenter("Title", 20, "=") // Returns "=======Title========"
PadCenter("你好", 10, " ") // Returns " 你好 " (correctly counts 2 runes)
func PadLeft ¶
PadLeft pads a string on the left (right-aligns the text). Uses UTF-8 rune counting to correctly handle multi-byte characters.
Parameters:
- str: The string to pad
- len: The desired total length in runes (not bytes)
- pad: The padding string (typically " " or "0")
Returns:
- Padded string with length 'len' runes
UTF-8 Support: Correctly handles emojis, CJK characters, and multi-byte Unicode.
Example:
PadLeft("text", 10, " ") // Returns " text"
PadLeft("5", 5, "0") // Returns "00005"
PadLeft("你好", 10, " ") // Returns " 你好" (correctly counts 2 runes)
func PadRight ¶
PadRight pads a string on the right (left-aligns the text). Uses UTF-8 rune counting to correctly handle multi-byte characters.
Parameters:
- str: The string to pad
- len: The desired total length in runes (not bytes)
- pad: The padding string (typically " ")
Returns:
- Padded string with length 'len' runes
UTF-8 Support: Correctly handles emojis, CJK characters, and multi-byte Unicode.
Example:
PadRight("text", 10, " ") // Returns "text "
PadRight("Name", 20, " ") // Returns "Name "
PadRight("🌍", 5, " ") // Returns "🌍 " (correctly counts 1 rune)
func PrintTabf ¶
PrintTabf prints formatted text with hierarchical indentation. Each indentation level adds 2 spaces. Uses ColorPrint for output.
Parameters:
- tablLevel: The indentation level (0 = no indent, 1 = 2 spaces, 2 = 4 spaces, etc.)
- format: Printf-style format string
- args: Arguments for format string
Output: Writes directly to stdout with ColorPrint colors.
Use Cases:
- Configuration display
- Hierarchical data structures
- Nested lists
- Tree output
Example:
console.PrintTabf(0, "Root\n") console.PrintTabf(1, "Child 1\n") console.PrintTabf(2, "Grandchild\n") console.PrintTabf(1, "Child 2\n")
Output:
Root
Child 1
Grandchild
Child 2
func PromptBool ¶
PromptBool displays a prompt and reads a boolean value from stdin. Accepts multiple formats for true/false values.
Parameters:
- text: The prompt message to display (e.g., "Continue? (true/false)")
Returns:
- bool: The parsed boolean value
- error: Input error or parse error (invalid boolean format)
Accepted values:
- True: "true", "TRUE", "True", "t", "T", "1"
- False: "false", "FALSE", "False", "f", "F", "0"
Example:
confirm, err := console.PromptBool("Do you want to continue? (true/false)")
if err != nil {
log.Fatal(err)
}
if confirm {
fmt.Println("Proceeding...")
}
func PromptInt ¶
PromptInt displays a prompt and reads an integer from stdin. The input is parsed as a base-10, 64-bit signed integer.
Parameters:
- text: The prompt message to display (e.g., "Enter your age")
Returns:
- int64: The parsed integer value
- error: Input error or parse error (invalid integer format)
Accepts: Any valid base-10 integer (-9223372036854775808 to 9223372036854775807)
Example:
age, err := console.PromptInt("Enter your age")
if err != nil {
log.Fatal(err)
}
fmt.Printf("You are %d years old\n", age)
func PromptPassword ¶
PromptPassword displays a prompt and reads a password from stdin with hidden input. The input is not echoed to the terminal for security. A newline is printed after input to maintain proper terminal formatting.
Parameters:
- text: The prompt message to display (e.g., "Enter password")
Returns:
- string: The password entered by the user
- error: Any error during reading (e.g., terminal not available)
Security Notes:
- Input is not displayed on screen (no echo)
- Password remains in memory as a string (consider using []byte and zeroing)
- Use HTTPS/TLS when transmitting passwords over network
Example:
password, err := console.PromptPassword("Enter password")
if err != nil {
log.Fatal(err)
}
// Use password securely...
// Consider zeroing the password when done:
// for i := range password { password[i] = 0 }
func PromptString ¶
PromptString displays a prompt and reads a line of text from stdin. The prompt text is displayed using ColorPrompt colors.
Parameters:
- text: The prompt message to display (e.g., "Enter your name")
Returns:
- string: The user's input (trimmed of newline)
- error: Any error during reading (e.g., EOF, I/O error)
Example:
name, err := console.PromptString("Enter your name")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Hello, %s!\n", name)
func PromptUrl ¶
PromptUrl displays a prompt and reads a URL from stdin. The input is parsed and validated as a URL.
Parameters:
- text: The prompt message to display (e.g., "Enter API endpoint")
Returns:
- *url.URL: The parsed URL object
- error: Input error or parse error (invalid URL format)
Accepts: Any valid URL format (http://example.com, https://api.example.com/v1, etc.)
Example:
endpoint, err := console.PromptUrl("Enter API endpoint")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Connecting to: %s\n", endpoint.String())
func SetColor ¶
SetColor configures the color attributes for a ColorType. Multiple attributes can be combined (e.g., color + bold + underline).
Parameters:
- id: The ColorType to configure
- value: Variadic list of color attributes (from fatih/color package)
Thread-safe: Can be called concurrently from multiple goroutines.
Example:
// Set single attribute
console.SetColor(console.ColorPrint, int(color.FgRed))
// Set multiple attributes
console.SetColor(console.ColorPrint,
int(color.FgYellow),
int(color.Bold),
int(color.Underline))
Types ¶
type ColorType ¶ added in v1.19.0
type ColorType uint8
ColorType represents a color scheme identifier. Each ColorType can have its own color configuration (foreground, background, attributes). This allows different parts of the application to use different color schemes.
const ( // ColorPrint is the default color type for standard output. // Use this for general application output, messages, and formatted text. ColorPrint ColorType = iota // ColorPrompt is the color type for user prompts and interactive input. // Use this for questions, input requests, and interactive elements. ColorPrompt )
func GetColorType ¶
GetColorType converts a uint8 to a ColorType. This is useful when loading color types from configuration files or external sources.
Parameters:
- id: The numeric identifier (0 = ColorPrint, 1 = ColorPrompt, etc.)
Returns:
- ColorType corresponding to the given id
Example:
ct := console.GetColorType(0) // Returns ColorPrint
func (ColorType) BuffPrintf ¶ added in v1.19.0
BuffPrintf writes formatted, colored text to an io.Writer. This is useful for:
- Writing colored output to buffers for testing
- Writing colored text to files
- Capturing colored output for processing
- Non-terminal output that supports ANSI codes
Parameters:
- buff: The io.Writer to write to (returns error if nil)
- format: Printf-style format string
- args: Arguments for format string
Returns:
- int: Number of bytes written
- error: ErrorColorBufUndefined if buff is nil, or write error
Example:
var buf bytes.Buffer
n, err := console.ColorPrint.BuffPrintf(&buf, "Hello %s", "World")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Wrote %d bytes: %s\n", n, buf.String())
func (ColorType) Print ¶ added in v1.19.0
Print prints the text to stdout with the ColorType's color, without a newline. Output goes directly to os.Stdout.
Parameters:
- text: The text to print
Example:
console.ColorPrint.Print("Hello")
console.ColorPrint.Print(" World")
func (ColorType) PrintLnf ¶ added in v1.19.0
PrintLnf prints formatted text to stdout with the ColorType's color, followed by a newline. Equivalent to Println(fmt.Sprintf(format, args...)).
Parameters:
- format: Printf-style format string
- args: Arguments for format string
Example:
console.ColorPrint.PrintLnf("Hello %s!", "World")
func (ColorType) Printf ¶ added in v1.19.0
Printf prints formatted text to stdout with the ColorType's color, without a newline. Equivalent to Print(fmt.Sprintf(format, args...)).
Parameters:
- format: Printf-style format string
- args: Arguments for format string
Example:
console.ColorPrint.Printf("Hello %s", "World")
func (ColorType) Println ¶ added in v1.19.0
Println prints the text to stdout with the ColorType's color, followed by a newline. Output goes directly to os.Stdout.
Parameters:
- text: The text to print
Example:
console.ColorPrint.Println("Hello, World!")
func (ColorType) SetColor ¶ added in v1.19.0
SetColor sets the color configuration for this ColorType using a color.Color object. This method provides an alternative to the package-level SetColor function.
Parameters:
- col: The color.Color instance to use (nil resets to no coloring)
Thread-safe: Can be called concurrently.
Example:
c := color.New(color.FgGreen, color.BgBlack) console.ColorPrint.SetColor(c)
func (ColorType) Sprintf ¶ added in v1.19.0
Sprintf formats the string with the ColorType's color and returns it. Does not print to stdout - returns the formatted string with ANSI color codes.
Parameters:
- format: Printf-style format string
- args: Arguments for format string
Returns:
- Formatted string with color codes
Example:
colored := console.ColorPrint.Sprintf("Hello %s", "World")
fmt.Println(colored) // Prints colored text