From 99924e85515bc7f73342e0f66d19887fa032129c Mon Sep 17 00:00:00 2001 From: Jules Michael Date: Mon, 28 Mar 2022 11:52:22 +0400 Subject: [PATCH] refactor: make `encoding/json` swappable for `jsoniter` --- cache/cache.go | 4 ++-- json/json.go | 22 ++++++++++++++++++++++ json/jsoniter.go | 27 +++++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 json/json.go create mode 100644 json/jsoniter.go diff --git a/cache/cache.go b/cache/cache.go index 86e362b..ac4c172 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -2,8 +2,8 @@ package cache import ( "github.com/JulesMike/spoty/config" + "github.com/JulesMike/spoty/json" "github.com/dgraph-io/ristretto" - jsoniter "github.com/json-iterator/go" "go.uber.org/fx" ) @@ -26,7 +26,7 @@ func New(cfg *config.Config) (*Cache, error) { MaxCost: cfg.CacheMaxCost, BufferItems: _defaultBufferItems, Cost: func(value interface{}) int64 { - test, err := jsoniter.Marshal(value) + test, err := json.Marshal(value) if err != nil { return 1 } diff --git a/json/json.go b/json/json.go new file mode 100644 index 0000000..2401b07 --- /dev/null +++ b/json/json.go @@ -0,0 +1,22 @@ +//go:build !jsoniter +// +build !jsoniter + +package json + +import "encoding/json" + +var ( + // Marshal refers to 'encoding/json.Marshal'. + Marshal = json.Marshal + // Unmarshal refers to 'encoding/json.Unmarshal'. + Unmarshal = json.Unmarshal + // MarshalIndent refers to 'encoding/json.MarshalIndent'. + MarshalIndent = json.MarshalIndent + // NewDecoder refers to 'encoding/json.NewDecoder'. + NewDecoder = json.NewDecoder + // NewEncoder refers to 'encoding/json.NewEncoder'. + NewEncoder = json.NewEncoder +) + +// RawMessage refers to 'encoding/json.RawMessage'. +type RawMessage = json.RawMessage diff --git a/json/jsoniter.go b/json/jsoniter.go new file mode 100644 index 0000000..bbc11dc --- /dev/null +++ b/json/jsoniter.go @@ -0,0 +1,27 @@ +//go:build jsoniter +// +build jsoniter + +package json + +import ( + stdjson "encoding/json" + + jsoniter "github.com/json-iterator/go" +) + +var ( + json = jsoniter.ConfigCompatibleWithStandardLibrary + // Marshal refers to 'github.com/json-iterator/go.Marshal'. + Marshal = json.Marshal + // Unmarshal refers to 'github.com/json-iterator/go.Unmarshal'. + Unmarshal = json.Unmarshal + // MarshalIndent refers to 'github.com/json-iterator/go.MarshalIndent'. + MarshalIndent = json.MarshalIndent + // NewDecoder refers to 'github.com/json-iterator/go.NewDecoder'. + NewDecoder = json.NewDecoder + // NewEncoder refers to 'github.com/json-iterator/go.NewEncoder'. + NewEncoder = json.NewEncoder +) + +// RawMessage refers to 'encoding/json.RawMessage'. +type RawMessage = stdjson.RawMessage