github.com/neilotoole/jsoncolor@v0.7.2-0.20231115150201-1637fae69be1/example_test.go (about) 1 package jsoncolor_test 2 3 import ( 4 "fmt" 5 "os" 6 7 "github.com/fatih/color" 8 "github.com/neilotoole/jsoncolor/helper/fatihcolor" 9 10 "github.com/mattn/go-colorable" 11 json "github.com/neilotoole/jsoncolor" 12 ) 13 14 // ExampleEncoder shows use of neilotoole/jsoncolor Encoder. 15 func ExampleEncoder() { 16 var enc *json.Encoder 17 18 // Note: this check will fail if running inside Goland (and 19 // other IDEs?) as IsColorTerminal will return false. 20 if json.IsColorTerminal(os.Stdout) { 21 // Safe to use color 22 out := colorable.NewColorable(os.Stdout) // needed for Windows 23 enc = json.NewEncoder(out) 24 25 // DefaultColors are similar to jq 26 clrs := json.DefaultColors() 27 28 // Change some values, just for fun 29 clrs.Bool = json.Color("\x1b[36m") // Change the bool color 30 clrs.String = json.Color{} // Disable the string color 31 32 enc.SetColors(clrs) 33 } else { 34 // Can't use color; but the encoder will still work 35 enc = json.NewEncoder(os.Stdout) 36 } 37 38 m := map[string]interface{}{ 39 "a": 1, 40 "b": true, 41 "c": "hello", 42 } 43 44 if err := enc.Encode(m); err != nil { 45 fmt.Fprintln(os.Stderr, err) 46 } 47 } 48 49 // ExampleFatihColor shows use of the fatihcolor helper package 50 // with jsoncolor. 51 func ExampleFatihColor() { 52 var enc *json.Encoder 53 54 // Note: this check will fail if running inside Goland (and 55 // other IDEs?) as IsColorTerminal will return false. 56 if json.IsColorTerminal(os.Stdout) { 57 out := colorable.NewColorable(os.Stdout) 58 enc = json.NewEncoder(out) 59 60 fclrs := fatihcolor.DefaultColors() 61 62 // Change some values, just for fun 63 fclrs.Number = color.New(color.FgBlue) 64 fclrs.String = color.New(color.FgCyan) 65 66 clrs := fatihcolor.ToCoreColors(fclrs) 67 enc.SetColors(clrs) 68 } else { 69 enc = json.NewEncoder(os.Stdout) 70 } 71 enc.SetIndent("", " ") 72 73 m := map[string]interface{}{ 74 "a": 1, 75 "b": true, 76 "c": "hello", 77 } 78 79 if err := enc.Encode(m); err != nil { 80 fmt.Fprintln(os.Stderr, err) 81 } 82 }