Skip to content

Commit

Permalink
feat: Increase status code and support for custom http.Client(#28)
Browse files Browse the repository at this point in the history
feat(request): Increase status code recognition; And support for custom `http.Client` (#28)
  • Loading branch information
flc1125 authored Nov 3, 2023
1 parent cc36ca8 commit e081bf9
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 8 deletions.
45 changes: 38 additions & 7 deletions client.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package youdu

import "net/http"

type Config struct {
Addr string
Buin int
Expand All @@ -8,14 +10,43 @@ type Config struct {
}

type Client struct {
config *Config
encryptor *Encryptor
token *token
config *Config
token *token

encryptor *Encryptor
httpClient *http.Client
}

func WithEncryptor(encryptor *Encryptor) func(c *Client) {
return func(c *Client) {
c.encryptor = encryptor
}
}

func WithHttpClient(client *http.Client) func(c *Client) {
return func(c *Client) {
c.httpClient = client
}
}

func NewClient(config *Config) *Client {
return &Client{
config: config,
encryptor: NewEncryptorWithConfig(config),
type ClientOption func(c *Client)

func NewClient(config *Config, opts ...ClientOption) *Client {
c := &Client{
config: config,
}

for _, opt := range opts {
opt(c)
}

if c.httpClient == nil {
c.httpClient = http.DefaultClient
}

if c.encryptor == nil {
c.encryptor = NewEncryptorWithConfig(config)
}

return c
}
11 changes: 10 additions & 1 deletion request.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
)

var (
ErrUnexpectedResponseCode = errors.New("youdu sdk: unexpected response code")
)

type Request struct {
Buin int `json:"buin"`
AppId string `json:"appId"`
Expand Down Expand Up @@ -137,11 +142,15 @@ func (c *Client) encodeRequestBody(opt *requestOptions) (io.Reader, error) {
}

func (c *Client) sendRequest(req *http.Request, resp interface{}, opts ...responseOption) error {
res, err := http.DefaultClient.Do(req)
res, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()

if res.StatusCode != http.StatusOK {
return ErrUnexpectedResponseCode
}

return c.decodeResponse(res.Body, resp, opts...)
}

0 comments on commit e081bf9

Please sign in to comment.