From bd8904c07514efad75764538034b9c2d64a16f7b Mon Sep 17 00:00:00 2001 From: Andrey Zverev Date: Mon, 11 Dec 2023 22:22:24 +0300 Subject: [PATCH] Implement WithJsonMarshalFunc which allow us to implement own Marshal function --- client.go | 14 ++++++++++++++ request.go | 15 ++++++++++++--- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/client.go b/client.go index cd0325c..ada4889 100644 --- a/client.go +++ b/client.go @@ -22,6 +22,9 @@ type Client struct { HttpClient *http.Client HttpRetryTimeout time.Duration + // Store custom JSON Unmarshal function + jsonMarshalFunc JsonMarshalFunc + // Option to specify extra headers like User-Agent ExtraHeader map[string]string } @@ -42,8 +45,19 @@ type FormOptions struct { GrantType string `url:"grant_type"` } +type JsonMarshalFunc func(v any) ([]byte, error) + type Option func(*Client) +// WithJsonMarshalFunc allow override (encoding/json) json.Marshal function with own implementation +// while keep original function signature. +func WithJsonMarshalFunc(f JsonMarshalFunc) Option { + return func(c *Client) { + c.jsonMarshalFunc = f + + } +} + // WithHttpClient sets the http client to use for requests func WithHttpClient(client *http.Client) Option { return func(c *Client) { diff --git a/request.go b/request.go index b858eb8..c0e3be4 100644 --- a/request.go +++ b/request.go @@ -177,9 +177,18 @@ func (c *Client) createRequest(method, api string, params *url.Values, reqbody i } bodyReader = strings.NewReader(b.Encode()) } else { - b, err := json.Marshal(reqbody) - if err != nil { - return nil, err + var b []byte + var err error + if c.jsonMarshalFunc == nil { + b, err = json.Marshal(reqbody) + if err != nil { + return nil, err + } + } else { + b, err = c.jsonMarshalFunc(reqbody) + if err != nil { + return nil, err + } } bodyReader = bytes.NewReader(b) }