From 359343625b46baf6557ebddad277ef8b61978c68 Mon Sep 17 00:00:00 2001 From: Mitul Agrawal Date: Mon, 25 Nov 2024 16:24:07 +0530 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A5=20feat:=20Add=20support=20for=20cr?= =?UTF-8?q?eating=20Fiber=20client=20from=20existing=20FastHTTP=20client?= =?UTF-8?q?=20(#3214)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 --- client/client.go | 10 +++++++++- client/client_test.go | 23 +++++++++++++++++++++++ docs/client/rest.md | 10 +++++++++- 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/client/client.go b/client/client.go index d9b9c84c..820be4ee 100644 --- a/client/client.go +++ b/client/client.go @@ -680,8 +680,16 @@ func New() *Client { // trie to use a pool to reduce the cost of memory allocation // for the fiber client and the fasthttp client // if possible also for other structs -> request header, cookie, query param, path param... + return NewWithClient(&fasthttp.Client{}) +} + +// NewWithClient creates and returns a new Client object from an existing client. +func NewWithClient(c *fasthttp.Client) *Client { + if c == nil { + panic("fasthttp.Client must not be nil") + } return &Client{ - fasthttp: &fasthttp.Client{}, + fasthttp: c, header: &Header{ RequestHeader: &fasthttp.RequestHeader{}, }, diff --git a/client/client_test.go b/client/client_test.go index 0323f70c..0a1ad14a 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -55,6 +55,29 @@ func startTestServerWithPort(t *testing.T, beforeStarting func(app *fiber.App)) return nil, "" } +func Test_New_With_Client(t *testing.T) { + t.Parallel() + + t.Run("with valid client", func(t *testing.T) { + t.Parallel() + + c := &fasthttp.Client{ + MaxConnsPerHost: 5, + } + client := NewWithClient(c) + + require.NotNil(t, client) + }) + + t.Run("with nil client", func(t *testing.T) { + t.Parallel() + + require.PanicsWithValue(t, "fasthttp.Client must not be nil", func() { + NewWithClient(nil) + }) + }) +} + func Test_Client_Add_Hook(t *testing.T) { t.Parallel() diff --git a/docs/client/rest.md b/docs/client/rest.md index 3590407e..97181311 100644 --- a/docs/client/rest.md +++ b/docs/client/rest.md @@ -95,7 +95,7 @@ type Client struct { } ``` - New +### New New creates and returns a new Client object. @@ -103,6 +103,14 @@ New creates and returns a new Client object. func New() *Client ``` +### NewWithClient + +NewWithClient creates and returns a new Client object from an existing client object. + +```go title="Signature" +func NewWithClient(c *fasthttp.Client) *Client +``` + ## REST Methods ### Get