package godump
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"text/tabwriter"
"unicode/utf8"
"unsafe"
)
const (
colorReset = "\033[0m"
colorGray = "\033[90m"
colorYellow = "\033[33m"
colorRed = "\033[31m"
colorGreen = "\033[32m"
colorRedBg = "\033[48;2;34;16;16m"
colorGreenBg = "\033[48;2;16;34;22m"
colorLime = "\033[1;38;5;113m"
colorCyan = "\033[38;5;38m"
colorNote = "\033[38;5;38m"
colorRef = "\033[38;5;247m"
colorMeta = "\033[38;5;170m"
colorDefault = "\033[38;5;208m"
indentWidth = 2
)
const (
defaultDisableStringer = false
defaultMaxDepth = 15
defaultMaxItems = 100
defaultMaxStringLen = 100000
defaultMaxStackDepth = 10
initialCallerSkip = 2
)
var defaultDumper = NewDumper ()
var exitFunc = os .Exit
type Colorizer func (code, str string ) string
func colorizeUnstyled(code , str string ) string {
return str
}
func colorizeANSI(code , str string ) string {
return code + str + colorReset
}
var htmlColorMap = map [string ]string {
colorGray : "#999" ,
colorYellow : "#ffb400" ,
colorRed : "#ff5f5f" ,
colorGreen : "#55d655" ,
colorLime : "#80ff80" ,
colorNote : "#40c0ff" ,
colorRef : "#aaa" ,
colorMeta : "#d087d0" ,
colorDefault : "#ff7f00" ,
}
func colorizeHTML(code , str string ) string {
return fmt .Sprintf (`<span style="color:%s">%s</span>` , htmlColorMap [code ], str )
}
type Dumper struct {
maxDepth int
maxItems int
maxStringLen int
writer io .Writer
skippedStackFrames int
disableStringer bool
disableColor bool
callerFn func (skip int ) (uintptr , string , int , bool )
colorizer Colorizer
}
type Option func (*Dumper ) *Dumper
type dumpState struct {
nextRefID int
refs map [uintptr ]int
}
func newDumpState() *dumpState {
return &dumpState {
nextRefID : 1 ,
refs : map [uintptr ]int {},
}
}
func WithMaxDepth (n int ) Option {
return func (d *Dumper ) *Dumper {
if n >= 0 {
d .maxDepth = n
}
return d
}
}
func WithMaxItems (n int ) Option {
return func (d *Dumper ) *Dumper {
if n >= 0 {
d .maxItems = n
}
return d
}
}
func WithMaxStringLen (n int ) Option {
return func (d *Dumper ) *Dumper {
if n >= 0 {
d .maxStringLen = n
}
return d
}
}
func WithWriter (w io .Writer ) Option {
return func (d *Dumper ) *Dumper {
d .writer = w
return d
}
}
func WithSkipStackFrames (n int ) Option {
return func (d *Dumper ) *Dumper {
if n >= 0 {
d .skippedStackFrames = n
}
return d
}
}
func WithDisableStringer (b bool ) Option {
return func (d *Dumper ) *Dumper {
d .disableStringer = b
return d
}
}
func WithoutColor () Option {
return func (d *Dumper ) *Dumper {
d .disableColor = true
d .colorizer = colorizeUnstyled
return d
}
}
func NewDumper (opts ...Option ) *Dumper {
d := &Dumper {
maxDepth : defaultMaxDepth ,
maxItems : defaultMaxItems ,
maxStringLen : defaultMaxStringLen ,
disableStringer : defaultDisableStringer ,
writer : os .Stdout ,
colorizer : nil ,
callerFn : runtime .Caller ,
}
for _ , opt := range opts {
d = opt (d )
}
return d
}
func Dump (vs ...any ) {
defaultDumper .Dump (vs ...)
}
func (d *Dumper ) Dump (vs ...any ) {
fmt .Fprint (d .writer , d .DumpStr (vs ...))
}
func Fdump (w io .Writer , vs ...any ) {
NewDumper (WithWriter (w )).Dump (vs ...)
}
func DumpStr (vs ...any ) string {
return defaultDumper .DumpStr (vs ...)
}
func (d *Dumper ) DumpStr (vs ...any ) string {
local := d .clone ()
state := newDumpState ()
var sb strings .Builder
local .printDumpHeader (&sb )
tw := tabwriter .NewWriter (&sb , 0 , 0 , 1 , ' ' , 0 )
local .writeDump (tw , state , vs ...)
tw .Flush ()
return sb .String ()
}
func (d *Dumper ) DumpJSONStr (vs ...any ) string {
if len (vs ) == 0 {
return `{"error": "DumpJSON called with no arguments"}`
}
var data any = vs
if len (vs ) == 1 {
data = vs [0 ]
}
b , err := json .MarshalIndent (data , "" , strings .Repeat (" " , indentWidth ))
if err != nil {
errorJSON , _ := json .Marshal (map [string ]string {"error" : err .Error()})
return string (errorJSON )
}
return string (b )
}
func (d *Dumper ) DumpJSON (vs ...any ) {
output := d .DumpJSONStr (vs ...)
fmt .Fprintln (d .writer , output )
}
func DumpHTML (vs ...any ) string {
return defaultDumper .DumpHTML (vs ...)
}
func (d *Dumper ) DumpHTML (vs ...any ) string {
var sb strings .Builder
sb .WriteString (`<div style='background-color:black;'><pre style="background-color:black; color:white; padding:5px; border-radius: 5px">` + "\n" )
htmlDumper := d .clone ()
if !htmlDumper .disableColor {
htmlDumper .colorizer = colorizeHTML
}
sb .WriteString (htmlDumper .DumpStr (vs ...))
sb .WriteString ("</pre></div>" )
return sb .String ()
}
func DumpJSON (vs ...any ) {
defaultDumper .DumpJSON (vs ...)
}
func DumpJSONStr (vs ...any ) string {
return defaultDumper .DumpJSONStr (vs ...)
}
func Dd (vs ...any ) {
defaultDumper .Dd (vs ...)
}
func (d *Dumper ) Dd (vs ...any ) {
d .Dump (vs ...)
exitFunc (1 )
}
func (d *Dumper ) clone () *Dumper {
newDumper := *d
return &newDumper
}
func (d *Dumper ) colorize (code , str string ) string {
if d .colorizer == nil {
if d .disableColor {
d .colorizer = colorizeUnstyled
return d .colorizer (code , str )
}
d .colorizer = newColorizer ()
}
return d .colorizer (code , str )
}
func (d *Dumper ) ensureColorizer () {
if d .colorizer == nil {
if d .disableColor {
d .colorizer = colorizeUnstyled
return
}
d .colorizer = newColorizer ()
}
}
func (d *Dumper ) printDumpHeader (out io .Writer ) {
file , line := d .findFirstNonInternalFrame (d .skippedStackFrames )
if file == "" {
return
}
relPath := file
if wd , err := os .Getwd (); err == nil {
if rel , err := filepath .Rel (wd , file ); err == nil {
relPath = rel
}
}
header := fmt .Sprintf ("<#dump // %s:%d" , relPath , line )
fmt .Fprintln (out , d .colorize (colorGray , header ))
}
func (d *Dumper ) findFirstNonInternalFrame (skip int ) (string , int ) {
for i := initialCallerSkip ; i < defaultMaxStackDepth ; i ++ {
pc , file , line , ok := d .callerFn (i )
if !ok {
break
}
fn := runtime .FuncForPC (pc )
if fn == nil || !strings .Contains (fn .Name (), "godump" ) || strings .HasSuffix (file , "_test.go" ) {
if skip > 0 {
skip --
continue
}
return file , line
}
}
return "" , 0
}
func (d *Dumper ) formatByteSliceAsHexDump (b []byte , indent int ) string {
var sb strings .Builder
const lineLen = 16
const asciiStartCol = 50
const asciiMaxLen = 16
fieldIndent := strings .Repeat (" " , indent *indentWidth )
bodyIndent := fieldIndent
sb .WriteString (fmt .Sprintf ("([]uint8) (len=%d cap=%d) {\n" , len (b ), cap (b )))
for i := 0 ; i < len (b ); i += lineLen {
end := i + lineLen
if end > len (b ) {
end = len (b )
}
line := b [i :end ]
visibleLen := 0
offsetStr := fmt .Sprintf ("%08x " , i )
sb .WriteString (bodyIndent )
sb .WriteString (d .colorize (colorMeta , offsetStr ))
visibleLen += len (offsetStr )
for j := 0 ; j < lineLen ; j ++ {
var hexStr string
if j < len (line ) {
hexStr = fmt .Sprintf ("%02x " , line [j ])
} else {
hexStr = " "
}
if j == 7 {
hexStr += " "
}
sb .WriteString (d .colorize (colorCyan , hexStr ))
visibleLen += len (hexStr )
}
padding := asciiStartCol - visibleLen
if padding < 1 {
padding = 1
}
sb .WriteString (strings .Repeat (" " , padding ))
sb .WriteString (d .colorize (colorGray , "| " ))
asciiCount := 0
for _ , c := range line {
ch := "."
if c >= 32 && c <= 126 {
ch = string (c )
}
sb .WriteString (d .colorize (colorLime , ch ))
asciiCount ++
}
if asciiCount < asciiMaxLen {
sb .WriteString (strings .Repeat (" " , asciiMaxLen -asciiCount ))
}
sb .WriteString (d .colorize (colorGray , " |" ) + "\n" )
}
fieldIndent = fieldIndent [:len (fieldIndent )-indentWidth ]
sb .WriteString (fieldIndent + "}" )
return sb .String ()
}
func (d *Dumper ) writeDump (w io .Writer , state *dumpState , vs ...any ) {
for _ , v := range vs {
rv := reflect .ValueOf (v )
rv = makeAddressable (rv )
d .printValue (w , rv , 0 , state )
fmt .Fprintln (w )
}
}
func (d *Dumper ) getTypeString (t reflect .Type ) string {
switch t .Kind () {
case reflect .Map :
return fmt .Sprintf ("map[%s]%s" , d .getTypeString (t .Key ()), d .getTypeString (t .Elem ()))
case reflect .Slice :
return fmt .Sprintf ("[]%s" , d .getTypeString (t .Elem ()))
case reflect .Array :
return fmt .Sprintf ("[%d]%s" , t .Len (), d .getTypeString (t .Elem ()))
case reflect .Ptr :
return fmt .Sprintf ("*%s" , d .getTypeString (t .Elem ()))
default :
return t .String ()
}
}
func (d *Dumper ) printValue (w io .Writer , v reflect .Value , indent int , state *dumpState ) {
if indent > d .maxDepth {
fmt .Fprint (w , d .colorize (colorGray , "... (max depth)" ))
return
}
if !v .IsValid () {
fmt .Fprint (w , d .colorize (colorGray , "<invalid>" ))
return
}
if s := d .asStringer (v ); s != "" {
fmt .Fprint (w , s )
return
}
switch v .Kind () {
case reflect .Chan :
typ := d .colorizer (colorGray , d .getTypeString (v .Type ()))
if v .IsNil () {
fmt .Fprint (w , d .colorize (colorGray , fmt .Sprintf ("#%s(nil)" , typ )))
} else {
fmt .Fprintf (w , "%s(%s)" , d .colorize (colorGray , typ ), d .colorize (colorCyan , fmt .Sprintf ("%#x" , v .Pointer ())))
}
return
}
if isNil (v ) {
typeStr := d .getTypeString (v .Type ())
fmt .Fprintf (w , d .colorize (colorLime , typeStr )+d .colorize (colorGray , "(nil)" ))
return
}
if v .Kind () == reflect .Ptr && v .CanAddr () {
ptr := v .Pointer ()
if id , ok := state .refs [ptr ]; ok {
fmt .Fprintf (w , d .colorize (colorRef , "↩︎ &%d" ), id )
return
} else {
state .refs [ptr ] = state .nextRefID
state .nextRefID ++
}
}
ptrPrefix := ""
for v .Kind () == reflect .Ptr {
ptrPrefix += "*"
v = v .Elem ()
}
switch v .Kind () {
case reflect .Interface :
d .printValue (w , v .Elem (), indent , state )
case reflect .Struct :
t := v .Type ()
fmt .Fprintf (w , "%s {" , d .colorize (colorGray , fmt .Sprintf ("#%s%s" , ptrPrefix , d .getTypeString (v .Type ()))))
fmt .Fprintln (w )
for i := 0 ; i < t .NumField (); i ++ {
field := t .Field (i )
fieldVal := v .Field (i )
symbol := "+"
if field .PkgPath != "" {
symbol = "-"
fieldVal = forceExported (fieldVal )
}
indentPrint (w , indent +1 , d .colorize (colorYellow , symbol )+field .Name )
fmt .Fprint (w , " => " )
if s := d .asStringer (fieldVal ); s != "" {
fmt .Fprint (w , s )
} else {
d .printValue (w , fieldVal , indent +1 , state )
}
fmt .Fprintln (w )
}
indentPrint (w , indent , "" )
fmt .Fprint (w , "}" )
case reflect .Complex64 , reflect .Complex128 :
fmt .Fprint (w , d .colorize (colorCyan , fmt .Sprintf ("%v" , v .Complex ())))
case reflect .UnsafePointer :
fmt .Fprint (w , d .colorize (colorGray , fmt .Sprintf ("unsafe.Pointer(%#x)" , v .Pointer ())))
case reflect .Map :
fmt .Fprintf (w , "%s {" , d .colorize (colorGray , fmt .Sprintf ("#%s%s" , ptrPrefix , d .getTypeString (v .Type ()))))
fmt .Fprintln (w )
keys := v .MapKeys ()
for i , key := range keys {
if i >= d .maxItems {
indentPrint (w , indent +1 , d .colorize (colorGray , "... (truncated)" ))
break
}
keyStr := fmt .Sprintf ("%v" , key .Interface ())
indentPrint (w , indent +1 , fmt .Sprintf (" %s => " , d .colorize (colorMeta , keyStr )))
d .printValue (w , v .MapIndex (key ), indent +1 , state )
fmt .Fprintln (w )
}
indentPrint (w , indent , "" )
fmt .Fprint (w , "}" )
case reflect .Slice , reflect .Array :
if v .Type ().Elem ().Kind () == reflect .Uint8 {
if v .CanConvert (reflect .TypeOf ([]byte {})) {
if data , ok := v .Convert (reflect .TypeOf ([]byte {})).Interface ().([]byte ); ok {
hexDump := d .formatByteSliceAsHexDump (data , indent +1 )
fmt .Fprint (w , d .colorize (colorLime , hexDump ))
break
}
}
}
fmt .Fprintf (w , "%s [" , d .colorize (colorGray , fmt .Sprintf ("#%s%s" , ptrPrefix , d .getTypeString (v .Type ()))))
fmt .Fprintln (w )
for i := 0 ; i < v .Len (); i ++ {
if i >= d .maxItems {
indentPrint (w , indent +1 , d .colorize (colorGray , "... (truncated)\n" ))
break
}
indentPrint (w , indent +1 , fmt .Sprintf ("%s => " , d .colorize (colorCyan , fmt .Sprintf ("%d" , i ))))
d .printValue (w , v .Index (i ), indent +1 , state )
fmt .Fprintln (w )
}
indentPrint (w , indent , "" )
fmt .Fprint (w , "]" )
case reflect .String :
str := escapeControl (v .String ())
if utf8 .RuneCountInString (str ) > d .maxStringLen {
runes := []rune (str )
str = string (runes [:d .maxStringLen ]) + "…"
}
fmt .Fprint (w , d .colorize (colorYellow , `"` )+d .colorize (colorLime , str )+d .colorize (colorYellow , `"` ))
case reflect .Bool :
if v .Bool () {
fmt .Fprint (w , d .colorize (colorYellow , "true" ))
} else {
fmt .Fprint (w , d .colorize (colorGray , "false" ))
}
case reflect .Int , reflect .Int8 , reflect .Int16 , reflect .Int32 , reflect .Int64 :
fmt .Fprint (w , d .colorize (colorCyan , fmt .Sprint (v .Int ())))
case reflect .Uint , reflect .Uint8 , reflect .Uint16 , reflect .Uint32 , reflect .Uint64 , reflect .Uintptr :
fmt .Fprint (w , d .colorize (colorCyan , fmt .Sprint (v .Uint ())))
case reflect .Float32 , reflect .Float64 :
fmt .Fprint (w , d .colorize (colorCyan , fmt .Sprintf ("%f" , v .Float ())))
case reflect .Func :
fmt .Fprint (w , d .colorize (colorGray , v .Type ().String ()))
}
if contains ([]reflect .Kind {
reflect .Struct ,
reflect .UnsafePointer ,
reflect .Map ,
reflect .Slice ,
reflect .Array ,
reflect .Ptr ,
reflect .Interface ,
}, v .Kind ()) {
return
}
fmt .Fprint (w , d .colorizer (colorGray , fmt .Sprintf (" #%s%s" , ptrPrefix , d .getTypeString (v .Type ()))))
}
func (d *Dumper ) asStringer (v reflect .Value ) string {
if d .disableStringer {
return ""
}
val := v
if !val .CanInterface () {
val = forceExported (val )
}
if val .CanInterface () {
if s , ok := val .Interface ().(fmt .Stringer ); ok {
rv := reflect .ValueOf (s )
if rv .Kind () == reflect .Ptr && rv .IsNil () {
return d .colorize (colorGray , val .Type ().String ()+"(nil)" )
}
return d .colorize (colorLime , s .String ()) + d .colorize (colorGray , " #" +d .getTypeString (val .Type ()))
}
}
return ""
}
func indentPrint(w io .Writer , indent int , text string ) {
fmt .Fprint (w , strings .Repeat (" " , indent *indentWidth )+text )
}
func forceExported(v reflect .Value ) reflect .Value {
if v .CanInterface () {
return v
}
if v .CanAddr () {
return reflect .NewAt (v .Type (), unsafe .Pointer (v .UnsafeAddr ())).Elem ()
}
return v
}
func makeAddressable(v reflect .Value ) reflect .Value {
if v .CanAddr () {
return v
}
if v .Kind () == reflect .Struct {
ptr := reflect .New (v .Type ())
ptr .Elem ().Set (v )
return ptr .Elem ()
}
return v
}
func isNil(v reflect .Value ) bool {
switch v .Kind () {
case reflect .Ptr , reflect .Slice , reflect .Map , reflect .Interface , reflect .Func , reflect .Chan :
return v .IsNil ()
default :
return false
}
}
var replacer = strings .NewReplacer (
"\n" , `\n` ,
"\t" , `\t` ,
"\r" , `\r` ,
"\v" , `\v` ,
"\f" , `\f` ,
"\x1b" , `\x1b` ,
)
func escapeControl(s string ) string {
return replacer .Replace (s )
}
func detectColor() bool {
if os .Getenv ("NO_COLOR" ) != "" {
return false
}
if os .Getenv ("FORCE_COLOR" ) != "" {
return true
}
return true
}
func newColorizer() Colorizer {
if detectColor () {
return colorizeANSI
}
return colorizeUnstyled
}
func contains(candidates []reflect .Kind , target reflect .Kind ) bool {
for _ , candidate := range candidates {
if candidate == target {
return true
}
}
return false
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .