From 1496bf7a5eedc1a455bddc05d9e264f62a066b15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9=20=D0=93=D1=83?= =?UTF-8?q?=D0=BB=D1=8F=D1=87=D0=B5=D0=BD=D0=BA=D0=BE=D0=B2?= Date: Fri, 8 Sep 2023 17:50:18 +0300 Subject: [PATCH 1/2] main - custom json serializers --- body.go | 3 +-- handler.go | 3 +-- json.go | 26 ++++++++++++++++++++++++++ 3 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 json.go diff --git a/body.go b/body.go index a4eea4a..1a1c172 100644 --- a/body.go +++ b/body.go @@ -2,7 +2,6 @@ package requests import ( "bytes" - "encoding/json" "io" "net/url" "os" @@ -47,7 +46,7 @@ func BodyBytes(b []byte) BodyGetter { // BodyJSON is a BodyGetter that marshals a JSON object. func BodyJSON(v any) BodyGetter { return func() (io.ReadCloser, error) { - b, err := json.Marshal(v) + b, err := jsonMarshal(v) if err != nil { return nil, err } diff --git a/handler.go b/handler.go index 31fb9f8..590c8cf 100644 --- a/handler.go +++ b/handler.go @@ -3,7 +3,6 @@ package requests import ( "bufio" "bytes" - "encoding/json" "io" "net/http" "os" @@ -46,7 +45,7 @@ func ToJSON(v any) ResponseHandler { if err != nil { return err } - if err = json.Unmarshal(data, v); err != nil { + if err = jsonUnmarshal(data, v); err != nil { return err } return nil diff --git a/json.go b/json.go new file mode 100644 index 0000000..2df9bac --- /dev/null +++ b/json.go @@ -0,0 +1,26 @@ +package requests + +import ( + "encoding/json" +) + +type jsonMarshaller = func(v any) ([]byte, error) +type jsonUnmarshaller = func(data []byte, v any) error + +var ( + jsonMarshal = json.Marshal + jsonUnmarshal = json.Unmarshal +) + +func SetJSONUnmarshaller(j jsonUnmarshaller) { + jsonUnmarshal = j +} + +func SetJSONMarshaller(j jsonMarshaller) { + jsonMarshal = j +} + +func SetJSONSerializers(marshaller jsonMarshaller, unmarshaller jsonUnmarshaller) { + jsonMarshal = marshaller + jsonUnmarshal = unmarshaller +} From eef9f97dcd0090bff1b3725d77de7b407ba06104 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9=20=D0=93=D1=83?= =?UTF-8?q?=D0=BB=D1=8F=D1=87=D0=B5=D0=BD=D0=BA=D0=BE=D0=B2?= Date: Fri, 8 Sep 2023 17:59:43 +0300 Subject: [PATCH 2/2] main - add comment --- json.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/json.go b/json.go index 2df9bac..62a9331 100644 --- a/json.go +++ b/json.go @@ -20,6 +20,8 @@ func SetJSONMarshaller(j jsonMarshaller) { jsonMarshal = j } +// SetJSONSerializers is a function to set global json.Marshal/json.Unmarshal function +// For faster serialization/deserialization you can use functions from, for instance, https://github.com/goccy/go-json func SetJSONSerializers(marshaller jsonMarshaller, unmarshaller jsonUnmarshaller) { jsonMarshal = marshaller jsonUnmarshal = unmarshaller