...

Package formatter

import "gitlab.com/tymonx/go-formatter/formatter"
Overview
Index
Examples

Overview ▾

Package formatter implements “replacement fields” surrounded by curly braces {} format strings.

Built-in functions

Simple example:

formatted, err := formatter.Format("{italic}{red}{blink}blinky :){blink | off} no blinky :({default}")

Built-in text functions

List of built-in functions:

reset      - All text attributes off
normal 	   - All text attributes off, alias to reset
default    - All text attributes off, alias to reset
bold       - Bold text
faint      - Faint text
italic     - Italic text
underline  - Underline text
overline   - Overline text
blink      - Blink text
invert     - Swap foreground and background colors
hide       - Hide text
strike     - Strike text
off        - Disable specific text attribute. Example: blink | off

Built-in string functions

List of built-in functions:

upper      - Transform provided string to upper case. Example: upper "text"
lower      - Transform provided string to lower case. Example: lower "TEXT"
capitalize - Capitalize provided string. Example: capitalize "text"

Built-in color functions

List of built-in functions:

black      - Black color
red        - Red color
green      - Green color
yellow     - Yellow color
blue       - Blue color
magenta    - Magenta color
cyan       - Cyan color
white      - White color
gray       - Gray color
rgb        - 24-bit color, 3 arguments (red, green, blue), integer values between 0-255
color      - Set color, 1 argument, color name like "red" or RGB HEX value in "0xXXXXXX" format
bright     - Make color bright, used with standard color function. Example: green | bright
foreground - Set as foreground color (default). Example: blue | foreground
background - Set as background color. Example: cyan | background

Built-in OS functions

List of built-in functions:

ip         - Get outbound (local) IP address
user       - Get current user name
executable - Get current executable path
cwd        - Get current working directory path
hostname   - Get hostname
env        - Get environment variable
expand     - Get and expand environment variable
uid        - Get user ID
gid        - Get group ID
euid       - Get effective user ID
egid       - Get effective group ID
pid        - Get process ID
ppid       - Get parent process ID
bell       - Make a sound

Built-in time functions

List of built-in functions:

now        - Get current time
rfc3339    - Format time to RFC 3339. Example: now | rfc3339
iso8601    - Format time to ISO 8601. Example: now | iso8601

Built-in path functions

List of built-in functions:

absolute   - Returns an absolute representation of path
base       - Returns the last element of path. Example: base "/dir/dir/file"
clean      - Returns the shortest path name equivalent to path by purely lexical processing
directory  - Returns all but the last element of path, typically the path's directory
extension  - Returns the file name extension used by path. Example: extension "/dir/dir/file.ext"

Built-in object functions

List of built-in functions:

fields    - Print also struct field names for given object. Example: p | fields
json      - Marshal object to JSON. Example: p | json
indent    - Indent marshaled JSON. Example: p | json | indent

Index ▾

Constants
Variables
func AreEscapeSequencesSupported() bool
func Format(message string, arguments ...interface{}) (string, error)
func FormatWriter(writer io.Writer, message string, arguments ...interface{}) error
func MustFormat(message string, arguments ...interface{}) string
type Formatter
    func New() *Formatter
    func (f *Formatter) AddFunction(name string, function interface{}) *Formatter
    func (f *Formatter) AddFunctions(functions Functions) *Formatter
    func (f *Formatter) AreEscapeSequencesEnabled() bool
    func (f *Formatter) DisableEscapeSequences() *Formatter
    func (f *Formatter) EnableEscapeSequences() *Formatter
    func (f *Formatter) Format(message string, arguments ...interface{}) (string, error)
    func (f *Formatter) FormatWriter(writer io.Writer, message string, arguments ...interface{}) error
    func (f *Formatter) GetDelimiters() (left, right string)
    func (f *Formatter) GetFunction(name string) interface{}
    func (f *Formatter) GetFunctions() Functions
    func (f *Formatter) GetLeftDelimiter() string
    func (f *Formatter) GetPlaceholder() string
    func (f *Formatter) GetRightDelimiter() string
    func (f *Formatter) MustFormat(message string, arguments ...interface{}) string
    func (f *Formatter) RemoveFunction(name string) *Formatter
    func (f *Formatter) RemoveFunctions(names []string) *Formatter
    func (f *Formatter) Reset() *Formatter
    func (f *Formatter) ResetDelimiters() *Formatter
    func (f *Formatter) ResetFunctions() *Formatter
    func (f *Formatter) ResetLeftDelimiter() *Formatter
    func (f *Formatter) ResetPlaceholder() *Formatter
    func (f *Formatter) ResetRightDelimiter() *Formatter
    func (f *Formatter) SetDelimiters(left, right string) *Formatter
    func (f *Formatter) SetEscapeSequences(escapeSequences bool) *Formatter
    func (f *Formatter) SetFunctions(functions Functions) *Formatter
    func (f *Formatter) SetLeftDelimiter(delimiter string) *Formatter
    func (f *Formatter) SetPlaceholder(placeholder string) *Formatter
    func (f *Formatter) SetRightDelimiter(delimiter string) *Formatter
type Functions
type Named

Package files

ansi.go doc.go error.go fields.go formatter.go functions.go ip.go iso8601.go json.go user.go

Constants

These constants define default values used by formatter.

const (
    DefaultPlaceholder      = "p"
    DefaultLeftDelimiter    = "{"
    DefaultRightDelimiter   = "}"
    ForceEscapeSequencesEnv = "FORCE_ESCAPE_SEQUENCES"
)

Variables

Current is used only in testing and mocking.

var Current = user.Current // nolint: gochecknoglobals

Dial is used only in testing and mocking.

var Dial = net.Dial // nolint: gochecknoglobals

func AreEscapeSequencesSupported

func AreEscapeSequencesSupported() bool

AreEscapeSequencesSupported returns true if environment supports ANSI escape sequences. Otherwise, it returns false.

func Format

func Format(message string, arguments ...interface{}) (string, error)

Format formats string.

Example (AutomaticPlaceholder)

Code:

formatted, err := formatter.Format("Automatic placeholder {p}:{p}:{p}():", "dir/file", 1, "func1")

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

Automatic placeholder dir/file:1:func1():

Example (BackgroundBrightColors)

Code:

formatted, err := formatter.Format("With background bright colors {cyan | bright | background}cyan{normal}")

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Example (BackgroundColors)

Code:

formatted, err := formatter.Format("With background colors {yellow | background}yellow{normal}")

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Example (BackgroundRGB)

Code:

formatted, err := formatter.Format("With background RGB {rgb 255 165 0 | background}funky{normal}")

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Example (BrightColors)

Code:

formatted, err := formatter.Format("With bright colors {magenta | bright}magenta{normal}")

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Example (Colors)

Code:

formatted, err := formatter.Format("With colors {red}red{normal} {green}green{normal} {blue}blue{normal}")

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Example (MixedPlaceholders)

Code:

objectPointer := &struct {
    X int
    Y int
    Z int
}{
    X: 2,
    Z: 6,
    Y: 3,
}

formatted, err := formatter.Format("Mixed placeholders {.X}.{p}.{.Y}.{.Z} {p1} {p0}", objectPointer, "b", "c", nil)

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

Mixed placeholders 2.{2 3 6}.3.6 b {2 3 6} c <nil>

Example (NamedPlaceholders)

Code:

formatted, err := formatter.Format("Named placeholders {file}:{line}:{function}():", formatter.Named{
    "line":     3,
    "function": "func1",
    "file":     "dir/file",
})

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

Named placeholders dir/file:3:func1():

Example (ObjectAutomaticPlaceholders)

Code:

object1 := struct {
    X int
}{
    X: 1,
}

object2 := struct {
    Message string
}{
    Message: "msg",
}

formatted, err := formatter.Format("{p.X} {p.Message}", object1, object2)

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

1 msg

Example (ObjectPlaceholders)

Code:

object := struct {
    Line     int
    Function string
    File     string
}{
    Line:     4,
    Function: "func1",
    File:     "dir/file",
}

formatted, err := formatter.Format("Object placeholders {.File}:{.Line}:{.Function}():", object)

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

Object placeholders dir/file:4:func1():

Example (ObjectPointerPlaceholders)

Code:

objectPointer := &struct {
    X int
    Y int
    Z int
}{
    X: 4,
    Z: 3,
    Y: 1,
}

formatted, err := formatter.Format("Object placeholders {.X}.{.Y}.{.Z}", objectPointer)

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

Object placeholders 4.1.3

Example (ObjectPositionalPlaceholders)

Code:

object1 := struct {
    X int
}{
    X: 1,
}

object2 := struct {
    Y int
}{
    Y: 2,
}

formatted, err := formatter.Format("{p1.Y} {p0.X}", object1, object2)

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

2 1

Example (PositionalPlaceholders)

Code:

formatted, err := formatter.Format("Positional placeholders {p1}:{p0}:{p2}():", 2, "dir/file", "func1")

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

Positional placeholders dir/file:2:func1():

Example (Rgb)

Code:

formatted, err := formatter.Format("With RGB {rgb 255 165 0}funky{normal}")

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Example (WithArguments)

Code:

formatted, err := formatter.Format("With arguments", 3, nil, 4.5, true, "arg1", []byte{}, Error("error"))

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

With arguments 3 <nil> 4.5 true arg1 [] error

Example (WithoutArguments)

Code:

formatted, err := formatter.Format("Without arguments")

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

Without arguments

func FormatWriter

func FormatWriter(writer io.Writer, message string, arguments ...interface{}) error

FormatWriter formats string to writer.

Example

Code:

buffer := new(bytes.Buffer)

if err := formatter.FormatWriter(buffer, "Writer {p2}", 3, "foo", "bar"); err != nil {
    panic(err)
}

fmt.Println(buffer.String())

Output:

Writer bar 3 foo

func MustFormat

func MustFormat(message string, arguments ...interface{}) string

MustFormat is like Format but panics if provided message cannot be formatted. It simplifies safe initialization of global variables holding formatted strings.

Example

Code:

fmt.Println(formatter.MustFormat("With arguments", 3, nil, false, 4.5, "text", []byte{}, Error("error")))

Output:

With arguments 3 <nil> false 4.5 text [] error

type Formatter

Formatter defines a formatter object that formats string using “replacement fields” surrounded by curly braces {}.

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

func New

func New() *Formatter

New creates a new formatter object.

func (*Formatter) AddFunction

func (f *Formatter) AddFunction(name string, function interface{}) *Formatter

AddFunction adds template function used by formatter.

func (*Formatter) AddFunctions

func (f *Formatter) AddFunctions(functions Functions) *Formatter

AddFunctions adds template functions used by formatter.

func (*Formatter) AreEscapeSequencesEnabled

func (f *Formatter) AreEscapeSequencesEnabled() bool

AreEscapeSequencesEnabled returns true if escape sequences are allowed in formatted messages. Otherwise, it returns false.

Example

Code:

f := formatter.New()

fmt.Println(f.DisableEscapeSequences().AreEscapeSequencesEnabled())
fmt.Println(f.EnableEscapeSequences().AreEscapeSequencesEnabled())

Output:

false
true

func (*Formatter) DisableEscapeSequences

func (f *Formatter) DisableEscapeSequences() *Formatter

DisableEscapeSequences removes ANSI escape sequences in formatted messages.

Example

Code:

formatted, err := formatter.New().DisableEscapeSequences().Format("{rgb 255 134 5 | background}Escape sequences disabled{normal}")

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

Escape sequences disabled

func (*Formatter) EnableEscapeSequences

func (f *Formatter) EnableEscapeSequences() *Formatter

EnableEscapeSequences allows ANSI escape sequences in formatted messages.

Example

Code:

fmt.Println(formatter.New().EnableEscapeSequences().AreEscapeSequencesEnabled())

Output:

true

func (*Formatter) Format

func (f *Formatter) Format(message string, arguments ...interface{}) (string, error)

Format formats string.

func (*Formatter) FormatWriter

func (f *Formatter) FormatWriter(writer io.Writer, message string, arguments ...interface{}) error

FormatWriter formats string to writer.

func (*Formatter) GetDelimiters

func (f *Formatter) GetDelimiters() (left, right string)

GetDelimiters returns delimiters used by formatter. Default is {}.

func (*Formatter) GetFunction

func (f *Formatter) GetFunction(name string) interface{}

GetFunction returns template function used by formatter.

func (*Formatter) GetFunctions

func (f *Formatter) GetFunctions() Functions

GetFunctions returns template functions used by formatter.

func (*Formatter) GetLeftDelimiter

func (f *Formatter) GetLeftDelimiter() string

GetLeftDelimiter returns left delimiter used by formatter. Default is {.

func (*Formatter) GetPlaceholder

func (f *Formatter) GetPlaceholder() string

GetPlaceholder returns placeholder string prefix used for automatic and positional placeholders to format string. Default is p.

func (*Formatter) GetRightDelimiter

func (f *Formatter) GetRightDelimiter() string

GetRightDelimiter returns right delimiter used by formatter. Default is }.

func (*Formatter) MustFormat

func (f *Formatter) MustFormat(message string, arguments ...interface{}) string

MustFormat is like Format but panics if provided message cannot be formatted. It simplifies safe initialization of global variables holding formatted strings.

func (*Formatter) RemoveFunction

func (f *Formatter) RemoveFunction(name string) *Formatter

RemoveFunction removes template function used by formatter.

func (*Formatter) RemoveFunctions

func (f *Formatter) RemoveFunctions(names []string) *Formatter

RemoveFunctions removes template functions used by formatter.

func (*Formatter) Reset

func (f *Formatter) Reset() *Formatter

Reset resets formatter to default state.

func (*Formatter) ResetDelimiters

func (f *Formatter) ResetDelimiters() *Formatter

ResetDelimiters resets delimiters used by formatter to default values.

func (*Formatter) ResetFunctions

func (f *Formatter) ResetFunctions() *Formatter

ResetFunctions resets template functions used by formatter.

func (*Formatter) ResetLeftDelimiter

func (f *Formatter) ResetLeftDelimiter() *Formatter

ResetLeftDelimiter resets left delimiter used by formatter to default value.

func (*Formatter) ResetPlaceholder

func (f *Formatter) ResetPlaceholder() *Formatter

ResetPlaceholder resets placeholder to default value.

func (*Formatter) ResetRightDelimiter

func (f *Formatter) ResetRightDelimiter() *Formatter

ResetRightDelimiter resets right delimiter used by formatter to default value.

func (*Formatter) SetDelimiters

func (f *Formatter) SetDelimiters(left, right string) *Formatter

SetDelimiters sets delimiters used by formatter. Default is {}.

Example

Code:

formatted, err := formatter.New().SetDelimiters("<", ">").Format("Custom delimiters <p1> <p0>", "4", 3)

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

Custom delimiters 3 4

func (*Formatter) SetEscapeSequences

func (f *Formatter) SetEscapeSequences(escapeSequences bool) *Formatter

SetEscapeSequences enables or disables ANSI escape sequences in formatted messages.

Example

Code:

f := formatter.New()

fmt.Println(f.SetEscapeSequences(false).AreEscapeSequencesEnabled())
fmt.Println(f.SetEscapeSequences(true).AreEscapeSequencesEnabled())

Output:

false
true

func (*Formatter) SetFunctions

func (f *Formatter) SetFunctions(functions Functions) *Formatter

SetFunctions sets template functions used by formatter.

Example

Code:

functions := formatter.Functions{
    "str": func() string {
        return "text"
    },
    "number": func() int {
        return 3
    },
    "boolean": func() bool {
        return true
    },
    "floating": func() float64 {
        return 4.5
    },
}

formatted, err := formatter.New().SetFunctions(functions).Format("Custom functions {str} {p} {number} {boolean} {floating}", 5)

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

Custom functions text 5 3 true 4.5

func (*Formatter) SetLeftDelimiter

func (f *Formatter) SetLeftDelimiter(delimiter string) *Formatter

SetLeftDelimiter sets left delimiter used by formatter. Default is {.

func (*Formatter) SetPlaceholder

func (f *Formatter) SetPlaceholder(placeholder string) *Formatter

SetPlaceholder sets placeholder string prefix used for automatic and positional placeholders to format string. Default is p.

Example

Code:

formatted, err := formatter.New().SetPlaceholder("arg").Format("Custom placeholder {arg1} {arg0}", "2", 3)

if err != nil {
    panic(err)
}

fmt.Println(formatted)

Output:

Custom placeholder 3 2

func (*Formatter) SetRightDelimiter

func (f *Formatter) SetRightDelimiter(delimiter string) *Formatter

SetRightDelimiter sets right delimiter used by formatter. Default is }.

type Functions

Functions defines a map of template functions.

type Functions map[string]interface{}

type Named

Named defines named arguments.

type Named map[string]interface{}