Skip to content

Commit 3593436

Browse files
authored
🔥 feat: Add support for creating Fiber client from existing FastHTTP client (#3214)
* add support to create client from existing client * add NewWithClient to documentation * fix typo in comment * fix and shorten comment * add unit test for NewWithClient * add nil check and test * fix lint check
1 parent f08ebf4 commit 3593436

File tree

3 files changed

+41
-2
lines changed

3 files changed

+41
-2
lines changed

client/client.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -680,8 +680,16 @@ func New() *Client {
680680
// trie to use a pool to reduce the cost of memory allocation
681681
// for the fiber client and the fasthttp client
682682
// if possible also for other structs -> request header, cookie, query param, path param...
683+
return NewWithClient(&fasthttp.Client{})
684+
}
685+
686+
// NewWithClient creates and returns a new Client object from an existing client.
687+
func NewWithClient(c *fasthttp.Client) *Client {
688+
if c == nil {
689+
panic("fasthttp.Client must not be nil")
690+
}
683691
return &Client{
684-
fasthttp: &fasthttp.Client{},
692+
fasthttp: c,
685693
header: &Header{
686694
RequestHeader: &fasthttp.RequestHeader{},
687695
},

client/client_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,29 @@ func startTestServerWithPort(t *testing.T, beforeStarting func(app *fiber.App))
5555
return nil, ""
5656
}
5757

58+
func Test_New_With_Client(t *testing.T) {
59+
t.Parallel()
60+
61+
t.Run("with valid client", func(t *testing.T) {
62+
t.Parallel()
63+
64+
c := &fasthttp.Client{
65+
MaxConnsPerHost: 5,
66+
}
67+
client := NewWithClient(c)
68+
69+
require.NotNil(t, client)
70+
})
71+
72+
t.Run("with nil client", func(t *testing.T) {
73+
t.Parallel()
74+
75+
require.PanicsWithValue(t, "fasthttp.Client must not be nil", func() {
76+
NewWithClient(nil)
77+
})
78+
})
79+
}
80+
5881
func Test_Client_Add_Hook(t *testing.T) {
5982
t.Parallel()
6083

docs/client/rest.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,14 +95,22 @@ type Client struct {
9595
}
9696
```
9797

98-
New
98+
### New
9999

100100
New creates and returns a new Client object.
101101

102102
```go title="Signature"
103103
func New() *Client
104104
```
105105

106+
### NewWithClient
107+
108+
NewWithClient creates and returns a new Client object from an existing client object.
109+
110+
```go title="Signature"
111+
func NewWithClient(c *fasthttp.Client) *Client
112+
```
113+
106114
## REST Methods
107115

108116
### Get

0 commit comments

Comments
 (0)