Add Colorize option

This commit is contained in:
Masaaki Goshima 2021-06-01 00:46:42 +09:00
parent 374d8261fa
commit c294f01ac5
4 changed files with 136 additions and 0 deletions

70
color.go Normal file
View File

@ -0,0 +1,70 @@
package json
import (
"fmt"
"github.com/goccy/go-json/internal/encoder"
)
type (
ColorFormat = encoder.ColorFormat
ColorScheme = encoder.ColorScheme
)
const escape = "\x1b"
type colorAttr int
const (
fgBlackColor colorAttr = iota + 30
fgRedColor
fgGreenColor
fgYellowColor
fgBlueColor
fgMagentaColor
fgCyanColor
fgWhiteColor
)
const (
fgHiBlackColor colorAttr = iota + 90
fgHiRedColor
fgHiGreenColor
fgHiYellowColor
fgHiBlueColor
fgHiMagentaColor
fgHiCyanColor
fgHiWhiteColor
)
func createColorFormat(attr colorAttr) ColorFormat {
return ColorFormat{
Header: wrapColor(attr),
Footer: resetColor(),
}
}
func wrapColor(attr colorAttr) string {
return fmt.Sprintf("%s[%dm", escape, attr)
}
func resetColor() string {
return wrapColor(colorAttr(0))
}
var (
DefaultColorScheme = &ColorScheme{
Int: createColorFormat(fgHiMagentaColor),
Uint: createColorFormat(fgHiMagentaColor),
Float: createColorFormat(fgHiMagentaColor),
Bool: createColorFormat(fgHiYellowColor),
String: createColorFormat(fgHiGreenColor),
Binary: createColorFormat(fgHiRedColor),
ObjectStart: createColorFormat(fgHiCyanColor),
ObjectEnd: createColorFormat(fgHiCyanColor),
ArrayStart: createColorFormat(fgHiCyanColor),
ArrayEnd: createColorFormat(fgHiCyanColor),
Colon: createColorFormat(fgWhiteColor),
Comma: createColorFormat(fgWhiteColor),
}
)

32
color_test.go Normal file
View File

@ -0,0 +1,32 @@
package json_test
import (
"testing"
"github.com/goccy/go-json"
)
func TestColorize(t *testing.T) {
v := struct {
A int
B uint
C float32
D string
E bool
F []byte
G []int
}{
A: 123,
B: 456,
C: 3.14,
D: "hello",
E: true,
F: []byte("binary"),
G: []int{1, 2, 3, 4},
}
b, err := json.MarshalWithOption(v, json.Colorize(json.DefaultColorScheme))
if err != nil {
t.Fatal(err)
}
t.Log(string(b))
}

View File

@ -5,4 +5,31 @@ type Option struct {
Indent bool Indent bool
UnorderedMap bool UnorderedMap bool
Debug bool Debug bool
Colorize bool
ColorScheme *ColorScheme
} }
type EncodeFormat struct {
Header string
Footer string
}
type EncodeFormatScheme struct {
Int EncodeFormat
Uint EncodeFormat
Float EncodeFormat
Bool EncodeFormat
String EncodeFormat
Binary EncodeFormat
ObjectStart EncodeFormat
ObjectEnd EncodeFormat
ArrayStart EncodeFormat
ArrayEnd EncodeFormat
Colon EncodeFormat
Comma EncodeFormat
}
type (
ColorScheme = EncodeFormatScheme
ColorFormat = EncodeFormat
)

View File

@ -19,3 +19,10 @@ func Debug() EncodeOptionFunc {
opt.Debug = true opt.Debug = true
} }
} }
func Colorize(scheme *ColorScheme) EncodeOptionFunc {
return func(opt *EncodeOption) {
opt.Colorize = true
opt.ColorScheme = scheme
}
}