Skip to content

Commit

Permalink
feat(client): add JSON marshaling option
Browse files Browse the repository at this point in the history
  • Loading branch information
jaxron committed Nov 10, 2024
1 parent 6c298c8 commit 10fce0f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
5 changes: 5 additions & 0 deletions pkg/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package client

import (
"context"
"encoding/json"
"net/http"

"github.com/jaxron/axonet/pkg/client/logger"
Expand All @@ -13,6 +14,8 @@ import (
type Client struct {
middlewareChain *middleware.Chain
httpClient *http.Client
marshalFunc MarshalFunc
unmarshalFunc UnmarshalFunc
}

// NewClient creates a new Client instance with default settings.
Expand All @@ -25,6 +28,8 @@ func NewClient(opts ...Option) *Client {
Jar: nil,
Timeout: 0,
},
marshalFunc: json.Marshal,
unmarshalFunc: json.Unmarshal,
}

for _, opt := range opts {
Expand Down
27 changes: 20 additions & 7 deletions pkg/client/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
Expand All @@ -14,6 +13,12 @@ import (
"github.com/jaxron/axonet/pkg/client/middleware"
)

// MarshalFunc is a function type that matches standard marshal functions.
type MarshalFunc func(interface{}) ([]byte, error)

// UnmarshalFunc is a function type that matches standard unmarshal functions.
type UnmarshalFunc func([]byte, interface{}) error

// Option is a function type that modifies the Client configuration.
type Option func(*Client)

Expand All @@ -38,11 +43,19 @@ func WithLogger(logger logger.Logger) Option {
}
}

// MarshalFunc is a function type that matches standard marshal functions.
type MarshalFunc func(interface{}) ([]byte, error)
// WithMarshalFunc sets the marshal function for the Client.
func WithMarshalFunc(fn MarshalFunc) Option {
return func(c *Client) {
c.marshalFunc = fn
}
}

// UnmarshalFunc is a function type that matches standard unmarshal functions.
type UnmarshalFunc func([]byte, interface{}) error
// WithUnmarshalFunc sets the unmarshal function for the Client.
func WithUnmarshalFunc(fn UnmarshalFunc) Option {
return func(c *Client) {
c.unmarshalFunc = fn
}
}

// Request helps build requests using method chaining.
type Request struct {
Expand All @@ -62,8 +75,8 @@ type Request struct {
func (c *Client) NewRequest() *Request {
return &Request{
client: c,
marshalFunc: json.Marshal,
unmarshalFunc: json.Unmarshal,
marshalFunc: c.marshalFunc,
unmarshalFunc: c.unmarshalFunc,
result: nil,
method: "",
url: "",
Expand Down

0 comments on commit 10fce0f

Please sign in to comment.