Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement WithJsonMarshalFunc which allow us to use own Marshal function for JSON #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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) {
Expand Down
15 changes: 12 additions & 3 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down