option.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package json
  2. import (
  3. "io"
  4. "github.com/goccy/go-json/internal/decoder"
  5. "github.com/goccy/go-json/internal/encoder"
  6. )
  7. type EncodeOption = encoder.Option
  8. type EncodeOptionFunc func(*EncodeOption)
  9. // UnorderedMap doesn't sort when encoding map type.
  10. func UnorderedMap() EncodeOptionFunc {
  11. return func(opt *EncodeOption) {
  12. opt.Flag |= encoder.UnorderedMapOption
  13. }
  14. }
  15. // DisableHTMLEscape disables escaping of HTML characters ( '&', '<', '>' ) when encoding string.
  16. func DisableHTMLEscape() EncodeOptionFunc {
  17. return func(opt *EncodeOption) {
  18. opt.Flag &= ^encoder.HTMLEscapeOption
  19. }
  20. }
  21. // DisableNormalizeUTF8
  22. // By default, when encoding string, UTF8 characters in the range of 0x80 - 0xFF are processed by applying \ufffd for invalid code and escaping for \u2028 and \u2029.
  23. // This option disables this behaviour. You can expect faster speeds by applying this option, but be careful.
  24. // encoding/json implements here: https://github.com/golang/go/blob/6178d25fc0b28724b1b5aec2b1b74fc06d9294c7/src/encoding/json/encode.go#L1067-L1093.
  25. func DisableNormalizeUTF8() EncodeOptionFunc {
  26. return func(opt *EncodeOption) {
  27. opt.Flag &= ^encoder.NormalizeUTF8Option
  28. }
  29. }
  30. // Debug outputs debug information when panic occurs during encoding.
  31. func Debug() EncodeOptionFunc {
  32. return func(opt *EncodeOption) {
  33. opt.Flag |= encoder.DebugOption
  34. }
  35. }
  36. // DebugWith sets the destination to write debug messages.
  37. func DebugWith(w io.Writer) EncodeOptionFunc {
  38. return func(opt *EncodeOption) {
  39. opt.DebugOut = w
  40. }
  41. }
  42. // Colorize add an identifier for coloring to the string of the encoded result.
  43. func Colorize(scheme *ColorScheme) EncodeOptionFunc {
  44. return func(opt *EncodeOption) {
  45. opt.Flag |= encoder.ColorizeOption
  46. opt.ColorScheme = scheme
  47. }
  48. }
  49. type DecodeOption = decoder.Option
  50. type DecodeOptionFunc func(*DecodeOption)
  51. // DecodeFieldPriorityFirstWin
  52. // in the default behavior, go-json, like encoding/json,
  53. // will reflect the result of the last evaluation when a field with the same name exists.
  54. // This option allow you to change this behavior.
  55. // this option reflects the result of the first evaluation if a field with the same name exists.
  56. // This behavior has a performance advantage as it allows the subsequent strings to be skipped if all fields have been evaluated.
  57. func DecodeFieldPriorityFirstWin() DecodeOptionFunc {
  58. return func(opt *DecodeOption) {
  59. opt.Flags |= decoder.FirstWinOption
  60. }
  61. }