Skip to content

Commit

Permalink
Merge pull request #8 from sreeram77/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
sreeram77 authored Sep 7, 2021
2 parents 3aca09d + 2de5b25 commit 173d18f
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
24 changes: 21 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
netURL "net/url"
"time"
)

// client is a wrapper around http.Client
Expand All @@ -17,19 +18,36 @@ func New() Client {
return Client{client: http.DefaultClient}
}

// NewClientWithTimeout returns an instance of Client with a Timeout
// Timeout for DefaultClient is 0, which means the connection never times out
func NewClientWithTimeout(t time.Duration) Client {
c := http.DefaultClient
c.Timeout = t

return Client{client: c}
}

// Get sends a GET request
func (c Client) Get(url string, headers map[string]string, params map[string]interface{}) (*http.Response, error) {
req, err := generateRequest(url, http.MethodPost, headers, params, nil)
if err != nil {
return nil, err
}

return c.client.Do(req)
}

req, err := GenerateRequest(url, http.MethodGet, headers, params, nil)
// Post sends a POST request
func (c Client) Post(url string, headers map[string]string, params map[string]interface{}, body []byte) (*http.Response, error) {
req, err := generateRequest(url, http.MethodGet, headers, params, body)
if err != nil {
return nil, err
}

return c.client.Do(req)
}

// GenerateRequest creates an HTTP request based on params
func GenerateRequest(url, method string, headers map[string]string, params map[string]interface{}, body []byte) (*http.Request, error) {
func generateRequest(url, method string, headers map[string]string, params map[string]interface{}, body []byte) (*http.Request, error) {
req, err := http.NewRequest(http.MethodGet, url, bytes.NewBuffer(body))
if err != nil {
return nil, err
Expand Down
33 changes: 33 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,36 @@ func Test_Get(t *testing.T) {
}
}
}

func Test_GenerateRequest(t *testing.T) {
type testCase struct {
id int
url string
method string
header map[string]string
body []byte
param map[string]interface{}
}

testCases := []testCase{
{
id: 1,
url: "https://google.com",
method: http.MethodGet,
header: nil,
body: nil,
param: nil,
},
}

for _, tc := range testCases {
req, err := generateRequest(tc.url, tc.method, tc.header, tc.param, tc.body)
if err != nil {
t.Error(err)
}

if !reflect.DeepEqual(req.Method, tc.method) {
t.Errorf("testcase: %v Expected Output: %v Actual Output: %v", tc.id, tc.method, req.Method)
}
}
}

0 comments on commit 173d18f

Please sign in to comment.