text

package
v1.43.2 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2025 License: Apache-2.0 Imports: 7 Imported by: 25

Documentation

Overview

Package text provides utilities for text formatting, humanization, and manipulation.

The package offers functions to format bytes and numbers into human-readable strings, handle durations, safely read from io.Reader, and indent text output. It includes utilities commonly needed for CLI tools and logging.

Key features:

  • Human-readable byte formatting (e.g., "10M", "12.5K")
  • Human-readable number formatting with metric suffixes
  • Duration parsing and formatting
  • Text indentation utilities
  • Safe reader utilities

Byte formatting example:

size := int64(1536)
fmt.Println(text.HumanizeBytes(size))  // "1.5K"

size = 1073741824
fmt.Println(text.HumanizeBytes(size))  // "1G"

Number formatting example:

count := 1500
fmt.Println(text.HumanizeInt(count))   // "1.5k"

count = 2000000
fmt.Println(text.HumanizeInt(count))   // "2m"

Duration example:

d := 3*time.Hour + 30*time.Minute
fmt.Println(text.HumanizeDuration(d))  // "3h30m"

age := text.Age(time.Now().Add(-24 * time.Hour))
fmt.Println(age)  // "1d"

Indentation example:

indented := text.String("  ", "line1\nline2\nline3")
// Result:
//   line1
//   line2
//   line3

Package text provides utilities for text processing, formatting, and manipulation.

The package includes functions for humanizing numbers and durations, indenting text, parsing extended duration formats, and safe I/O operations.

Key Features:

  • Human-readable formatting for bytes, numbers, and durations
  • Text indentation for hierarchical output
  • Extended duration parsing (days, weeks, years)
  • Safe I/O operations that never panic

Byte and Number Formatting:

// Format bytes in human-readable form
text.HumanizeBytes(1536)        // "1.5 KB"
text.HumanizeBytes(1048576)     // "1.0 MB"
text.HumanizeBytes(5368709120)  // "5.0 GB"

// Format large numbers with thousand separators
text.HumanizeInt(1000000)       // "1,000,000"
text.HumanizeInt(42)            // "42"

Duration Formatting:

// Format durations in human-readable form
text.HumanizeDuration(90 * time.Minute)        // "1h30m"
text.HumanizeDuration(25 * time.Hour)          // "1d1h"
text.HumanizeDuration(8 * 24 * time.Hour)      // "1w1d"

// Calculate age since a time
created := time.Now().Add(-48 * time.Hour)
text.Age(created)                               // "2d"

Duration Parsing:

Parse durations with extended units beyond the standard Go time.Duration:

d, err := text.ParseDuration("3d")       // 72 hours
d, err := text.ParseDuration("1w")       // 168 hours
d, err := text.ParseDuration("2y")       // ~17520 hours
d, err := text.ParseDuration("1d12h30m") // 36.5 hours

Supported units: ns, us/µs, ms, s, m, h, d (days), w (weeks), y (years)

Text Indentation:

// Indent a string
indented := text.String("  ", "line1\nline2\nline3")
// "  line1\n  line2\n  line3"

// Indent bytes
data := []byte("line1\nline2")
indented := text.Bytes("  ", data)

// Create an indenting writer
writer := text.NewWriter(os.Stdout, "  ")
fmt.Fprintln(writer, "This will be indented")
fmt.Fprintln(writer, "So will this")

Safe I/O:

// Read from reader without error handling
resp, _ := http.Get("https://example.com")
defer resp.Body.Close()
content := text.SafeRead(resp.Body) // Empty string on error

Formatting Examples:

// Display file sizes
fmt.Printf("Size: %s\n", text.HumanizeBytes(fileSize))

// Display request counts
fmt.Printf("Requests: %s\n", text.HumanizeInt(requestCount))

// Display uptime
fmt.Printf("Uptime: %s\n", text.HumanizeDuration(time.Since(startTime)))

// Display last updated
fmt.Printf("Updated: %s ago\n", text.Age(lastModified))

Related Packages:

  • duration: Extended duration parsing (used internally)

Index

Constants

View Source
const (
	BYTE = 1 << (10 * iota)
	KILOBYTE
	MEGABYTE
	GIGABYTE
	TERABYTE
	PETABYTE
	EXABYTE
)
View Source
const (
	KILO = 1000
	MEGA = 1000 * KILO
	GIGA = 1000 * MEGA
)

Variables

This section is empty.

Functions

func Age added in v1.5.10

func Age(d time.Time) string

Age returns a human-readable string representing the time elapsed since the given time. It's a convenience function that combines time.Since with HumanizeDuration.

Example:

created := time.Now().Add(-24 * time.Hour)
fmt.Printf("Created %s ago", text.Age(created)) // "Created 1d ago"

func Bytes added in v1.30.5

func Bytes(indent, b []byte) []byte

Bytes returns b with each line in b prefixed by indent.

func HumanizeBytes added in v1.5.2

func HumanizeBytes(size interface{}) string

HumanizeBytes returns a human-readable byte string of the form 10M, 12.5K, and so forth. The following units are available:

E: Exabyte  (1024^6 bytes)
P: Petabyte (1024^5 bytes)
T: Terabyte (1024^4 bytes)
G: Gigabyte (1024^3 bytes)
M: Megabyte (1024^2 bytes)
K: Kilobyte (1024 bytes)
B: Byte

The unit that results in the smallest number greater than or equal to 1 is always chosen. The function accepts uint, uint64, int, int64, or string as input.

Examples:

HumanizeBytes(1024)        // "1K"
HumanizeBytes(1536)        // "1.5K"
HumanizeBytes(1048576)     // "1M"
HumanizeBytes("1073741824") // "1G"

func HumanizeDuration added in v1.5.2

func HumanizeDuration(d time.Duration) string

HumanizeDuration returns a string representing of a duration in the form "3d1h3m".

Leading zero units are omitted. As a special case, durations less than one second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure that the leading digit is non-zero. Duration more than a day or more than a week lose granularity and are truncated to resp. days-hours-minutes and weeks-days-hours. The zero duration formats as 0s.

Examples:

HumanizeDuration(3*time.Hour + 30*time.Minute) // "3h30m"
HumanizeDuration(24*time.Hour)                  // "1d"
HumanizeDuration(168*time.Hour + 12*time.Hour)  // "1w12h"

func HumanizeInt added in v1.29.1

func HumanizeInt(size interface{}) string

HumanizeInt formats integers with metric suffixes for readability. It uses decimal (base-10) units: k for thousands, m for millions, b for billions.

The function accepts uint, uint64, int, int64, or string as input.

Examples:

HumanizeInt(1500)        // "1.5k"
HumanizeInt(2000000)     // "2m"
HumanizeInt(1500000000)  // "1.5b"
HumanizeInt("1000")      // "1k"

func NewWriter added in v1.30.5

func NewWriter(w io.Writer, indent string) io.Writer

NewWriter returns an io.Writer that prefixes the lines written to it with indent and then writes them to w. The writer returns the number of bytes written to the underlying Writer.

func ParseDuration added in v1.5.10

func ParseDuration(val string) (*time.Duration, error)

ParseDuration parses a duration string with support for extended units like days and weeks. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h", "d", "w", "y".

Examples:

d, _ := ParseDuration("3d12h")    // 3 days 12 hours
d, _ := ParseDuration("1w")       // 1 week
d, _ := ParseDuration("2h30m")    // 2 hours 30 minutes

func SafeRead

func SafeRead(r io.Reader) string

SafeRead reads all data from an io.Reader and returns it as a string. If an error occurs during reading, it returns an empty string instead of propagating the error. This is useful when you want to ensure a read operation never fails, such as in logging or display contexts.

Example:

resp, _ := http.Get("https://example.com")
defer resp.Body.Close()
content := text.SafeRead(resp.Body)
// content will be empty string if read fails

func String added in v1.30.5

func String(indent, s string) string

String returns s with each line in s prefixed by indent.

Types

This section is empty.

Jump to

Keyboard shortcuts

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