gop

package module
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: MIT Imports: 17 Imported by: 3

README

Go Pretty Print Value

Make a random Go value human readable. The output format uses valid golang syntax, so you don't have to learn any new knowledge to understand the output.

Features

  • Uses valid golang syntax to print the data
  • Make rune, []byte, time, etc. data human readable
  • Color output with customizable theme
  • Stable map output with sorted by keys
  • Auto split multiline large string block
  • Prints the path of circular reference
  • Auto format inline json string
  • Low-level API to extend the lib

Usage

Usually, you only need to use gop.P function:

package main

import (
    "time"

    "github.com/ysmood/got/lib/gop"
)

func main() {
    val := map[string]interface{}{
        "bool":   true,
        "number": 1 + 1i,
        "bytes":  []byte{97, 98, 99},
        "lines":  "multiline string\nline two",
        "slice":  []interface{}{1, 2},
        "time":   time.Now(),
        "chan":   make(chan int, 1),
        "struct": struct{ test int32 }{
            test: 13,
        },
        "json": `{"a"   : 1}`,
        "func": func(int) int { return 0 },
    }
    val["slice"].([]interface{})[1] = val["slice"]

    _ = gop.P(val)
}

The output will be something like:

// 2023-10-07T18:19:57.517309+08:00 example/main.go:27 (main.main)
map[string]interface {}{
    "bool": true,
    "bytes": []byte("abc"),
    "chan": make(chan int, 1)/* 0x1400008c070 */,
    "func": (func(int) int)(nil)/* 0x1025a5460 */,
    "json": gop.JSONStr(map[string]interface {}{
        "a": 1.0,
    }, `{"a"   : 1}`),
    "lines": `multiline string
line two`,
    "number": 1+1i,
    "slice": []interface {}{
        1,
        gop.Circular("slice").([]interface {}),
    },
    "struct": struct { test int32 }{
        test: int32(13),
    },
    "time": gop.Time("2023-10-07T18:19:57.516984+08:00", 3081584),
}

Documentation

Overview

Package gop ...

Index

Constants

View Source
const SymbolBase64 = "gop.Base64"

SymbolBase64 for Base64

View Source
const SymbolCircular = "gop.Circular"

SymbolCircular for Circular

View Source
const SymbolDuration = "gop.Duration"

SymbolDuration for Duration

View Source
const SymbolGopError = "gop.GopError"
View Source
const SymbolJSONBytes = "gop.JSONBytes"

SymbolJSONBytes for JSONBytes

View Source
const SymbolJSONStr = "gop.JSONStr"

SymbolJSONStr for JSONStr

View Source
const SymbolPtr = "gop.Ptr"

SymbolPtr for Ptr

View Source
const SymbolRune = "gop.Rune"

SymbolRune for Rune

View Source
const SymbolTime = "gop.Time"

SymbolTime for Time

Variables

View Source
var (
	// Bold style
	Bold = addStyle(1, 22)
	// Faint style
	Faint = addStyle(2, 22)
	// Italic style
	Italic = addStyle(3, 23)
	// Underline style
	Underline = addStyle(4, 24)
	// Blink style
	Blink = addStyle(5, 25)
	// RapidBlink style
	RapidBlink = addStyle(6, 26)
	// Invert style
	Invert = addStyle(7, 27)
	// Hide style
	Hide = addStyle(8, 28)
	// Strike style
	Strike = addStyle(9, 29)

	// Black color
	Black = addStyle(30, 39)
	// Red color
	Red = addStyle(31, 39)
	// Green color
	Green = addStyle(32, 39)
	// Yellow color
	Yellow = addStyle(33, 39)
	// Blue color
	Blue = addStyle(34, 39)
	// Magenta color
	Magenta = addStyle(35, 39)
	// Cyan color
	Cyan = addStyle(36, 39)
	// White color
	White = addStyle(37, 39)

	// BgBlack color
	BgBlack = addStyle(40, 49)
	// BgRed color
	BgRed = addStyle(41, 49)
	// BgGreen color
	BgGreen = addStyle(42, 49)
	// BgYellow color
	BgYellow = addStyle(43, 49)
	// BgBlue color
	BgBlue = addStyle(44, 49)
	// BgMagenta color
	BgMagenta = addStyle(45, 49)
	// BgCyan color
	BgCyan = addStyle(46, 49)
	// BgWhite color
	BgWhite = addStyle(47, 49)

	// None type
	None = Style{}
)
View Source
var DefaultOptions = Options{
	MaxDepth: 15,
}

DefaultOptions for Tokenize.

View Source
var NoStyle = func() bool {
	_, noColor := os.LookupEnv("NO_COLOR")

	b, _ := exec.Command("tput", "colors").CombinedOutput()
	n, _ := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 32)
	return noColor || n == 0
}()

NoStyle respects https://no-color.org/ and "tput colors"

View Source
var RegANSI = regexp.MustCompile(`\x1b\[\d+m`)

RegANSI token

View Source
var Stdout io.Writer = os.Stdout

Stdout is the default stdout for gop.P .

View Source
var ThemeDefault = func(t Type) []Style {
	switch t {
	case TypeName:
		return []Style{Cyan}
	case Bool, Chan:
		return []Style{Blue}
	case RuneInt32, Byte, String:
		return []Style{Yellow}
	case Number:
		return []Style{Green}
	case Func:
		return []Style{Magenta}
	case Comment:
		return []Style{White}
	case Nil:
		return []Style{Red}
	case Error:
		return []Style{Underline, Red}
	default:
		return []Style{None}
	}
}

ThemeDefault colors for Sprint

View Source
var ThemeNone = func(t Type) []Style {
	return []Style{None}
}

ThemeNone colors for Sprint

Functions

func Base64

func Base64(s string) []byte

Base64 returns the []byte that s represents

func Circular

func Circular(path ...interface{}) interface{}

Circular reference of the path from the root

func Duration

func Duration(s string) time.Duration

Duration from parsing s

func F

func F(v interface{}) string

F is a shortcut for Format with color

func FixNestedStyle

func FixNestedStyle(s string) string

FixNestedStyle like

<d><a>1<b>2<c>3</d></>4</>5</>

into

<d><a>1</><b>2</><c>3</d></><b>4</><a>5</>

func Format

func Format(ts []Token, theme Theme) string

Format a list of tokens.

func GetPrivateField

func GetPrivateField(v reflect.Value, i int) reflect.Value

GetPrivateField via field index TODO: we can use a LRU cache for the copy of the values, but it might be trivial for just testing.

func GetPrivateFieldByName

func GetPrivateFieldByName(v reflect.Value, name string) reflect.Value

GetPrivateFieldByName is similar with GetPrivateField

func GopError added in v0.3.0

func GopError(msg string) error

GopError returns an error with the given message, it represents an error occurred during tokenization or formatting.

func JSONBytes

func JSONBytes(v interface{}, raw string) []byte

JSONBytes returns the raw as []byte

func JSONStr

func JSONStr(v interface{}, raw string) string

JSONStr returns the raw

func P

func P(values ...interface{}) error

P pretty print the values

func Plain

func Plain(v interface{}) string

Plain is a shortcut for Format with plain color

func Ptr

func Ptr(v interface{}) interface{}

Ptr returns a pointer to v

func Render added in v0.4.0

func Render(sb *strings.Builder, str string, styles []Style)

Render writes the stylized form of str to sb without allocating intermediate strings: both the single-line and multi-line paths stream directly into sb.

func Rune

func Rune(i int32, r rune) rune

func S

func S(str string, styles ...Style) string

S is the shortcut for Stylize.

func StripANSI

func StripANSI(str string) string

StripANSI tokens

func Stylize

func Stylize(str string, styles []Style) string

Stylize wraps str with the given styles.

func Time

func Time(s string, monotonic int) time.Time

Time from parsing s

func VisualizeANSI

func VisualizeANSI(str string) string

VisualizeANSI tokens

Types

type ByteTok added in v0.4.0

type ByteTok byte

ByteTok lazily renders a byte as a Byte token, quoted when graphic else as 0xHEX.

func (ByteTok) Build added in v0.4.0

func (b ByteTok) Build(sb *strings.Builder)

Build appends the rendered byte to sb.

func (ByteTok) Type added in v0.4.0

func (ByteTok) Type() Type

Type returns Byte.

type CommentPtrTok added in v0.4.0

type CommentPtrTok uintptr

CommentPtrTok lazily renders a uintptr as a Comment token in /* 0xHEX */ form.

func (CommentPtrTok) Build added in v0.4.0

func (p CommentPtrTok) Build(sb *strings.Builder)

Build appends the wrapped hex representation to sb.

func (CommentPtrTok) Type added in v0.4.0

func (CommentPtrTok) Type() Type

Type returns Comment.

type ComplexTok added in v0.4.0

type ComplexTok struct {
	V    complex128
	Bits int
}

ComplexTok lazily renders a complex value at the given bit size as a Number token, stripping the parentheses that strconv.FormatComplex adds.

func (ComplexTok) Build added in v0.4.0

func (c ComplexTok) Build(sb *strings.Builder)

Build appends the formatted value to sb.

func (ComplexTok) Type added in v0.4.0

func (ComplexTok) Type() Type

Type returns Number.

type Float64Tok added in v0.4.0

type Float64Tok float64

Float64Tok lazily renders a float64 as a Number token, appending ".0" when the value is integral.

func (Float64Tok) Build added in v0.4.0

func (f Float64Tok) Build(sb *strings.Builder)

Build appends the formatted value to sb.

func (Float64Tok) Type added in v0.4.0

func (Float64Tok) Type() Type

Type returns Number.

type FloatTok added in v0.4.0

type FloatTok struct {
	V    float64
	Bits int
}

FloatTok lazily renders a float at the given bit size as a Number token.

func (FloatTok) Build added in v0.4.0

func (f FloatTok) Build(sb *strings.Builder)

Build appends the formatted value to sb.

func (FloatTok) Type added in v0.4.0

func (FloatTok) Type() Type

Type returns Number.

type IntTok added in v0.4.0

type IntTok int64

IntTok lazily renders a signed integer as a Number token.

func (IntTok) Build added in v0.4.0

func (n IntTok) Build(sb *strings.Builder)

Build appends the decimal representation to sb.

func (IntTok) Type added in v0.4.0

func (IntTok) Type() Type

Type returns Number.

type Lit added in v0.4.0

type Lit struct {
	T Type
	L string
}

Lit is a token with a fixed literal string.

func (*Lit) Build added in v0.4.0

func (l *Lit) Build(sb *strings.Builder)

Build writes the literal to sb.

func (*Lit) Type added in v0.4.0

func (l *Lit) Type() Type

Type returns the token type.

type Options added in v0.3.0

type Options struct {
	// MaxDepth limits the depth of tokenization for nested structures.
	// If less than 1 there is no limit.
	MaxDepth int
}

Options controls tokenization.

type PtrTok added in v0.4.0

type PtrTok uintptr

PtrTok lazily renders a uintptr as a Number token in 0xHEX form.

func (PtrTok) Build added in v0.4.0

func (p PtrTok) Build(sb *strings.Builder)

Build appends the hex representation to sb.

func (PtrTok) Type added in v0.4.0

func (PtrTok) Type() Type

Type returns Number.

type RuneTok added in v0.4.0

type RuneTok rune

RuneTok lazily renders a rune as a RuneInt32 token (quoted).

func (RuneTok) Build added in v0.4.0

func (r RuneTok) Build(sb *strings.Builder)

Build appends the quoted rune to sb.

func (RuneTok) Type added in v0.4.0

func (RuneTok) Type() Type

Type returns RuneInt32.

type Style

type Style struct {
	Set   string
	Unset string
}

Style type

func GetStyle

func GetStyle(s string) Style

GetStyle from available styles

type Styled added in v0.4.0

type Styled struct {
	Inner  Token
	Styles []Style
}

Styled wraps an inner Token and applies the given Styles when built. It is the token form of the legacy Stylize helper.

func (Styled) Build added in v0.4.0

func (s Styled) Build(sb *strings.Builder)

Build writes the styled rendering of the inner token to sb.

func (Styled) Type added in v0.4.0

func (s Styled) Type() Type

Type returns the inner token type.

type Theme

type Theme func(t Type) []Style

Theme to color values

type Token

type Token interface {
	Type() Type
	Build(sb *strings.Builder)
}

Token represents a symbol in value layout. Build appends the token's rendered form to sb so the literal can be computed lazily and avoid allocating intermediate strings.

func Tokenize

func Tokenize(v interface{}) []Token

Tokenize a random Go value with DefaultOptions.

func TokenizeWithOptions added in v0.3.0

func TokenizeWithOptions(v interface{}, opts Options) []Token

TokenizeWithOptions tokenizes v with the given Options.

type Type

type Type int

Type of token

const (
	// Nil type
	Nil Type = iota
	// Bool type
	Bool
	// Number type
	Number
	// Float type
	Float
	// Complex type
	Complex
	// String type
	String
	// Byte type
	Byte
	// RuneInt32 type
	RuneInt32
	// Chan type
	Chan
	// Func type
	Func
	// Error type
	Error

	// Comment type
	Comment

	// TypeName type
	TypeName

	// ParenOpen type
	ParenOpen
	// ParenClose type
	ParenClose

	// Dot type
	Dot
	// And type
	And

	// SliceOpen type
	SliceOpen
	// SliceItem type
	SliceItem
	// InlineComma type
	InlineComma
	// Comma type
	Comma
	// SliceClose type
	SliceClose

	// MapOpen type
	MapOpen
	// MapKey type
	MapKey
	// Colon type
	Colon
	// MapClose type
	MapClose

	// StructOpen type
	StructOpen
	// StructKey type
	StructKey
	// StructField type
	StructField
	// StructClose type
	StructClose
)

type UintTok added in v0.4.0

type UintTok uint64

UintTok lazily renders an unsigned integer as a Number token.

func (UintTok) Build added in v0.4.0

func (n UintTok) Build(sb *strings.Builder)

Build appends the decimal representation to sb.

func (UintTok) Type added in v0.4.0

func (UintTok) Type() Type

Type returns Number.

Directories

Path Synopsis
Package main ...
Package main ...

Jump to

Keyboard shortcuts

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