Skip to content

Commit

Permalink
Merge pull request #63 from KyberNetwork/chore/make_new_http_request_…
Browse files Browse the repository at this point in the history
…more_robust

Make NewRequestWithContext more robust
  • Loading branch information
hiepnv90 authored Jul 11, 2024
2 parents 49149e5 + 92fefac commit 1f7d86e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
23 changes: 18 additions & 5 deletions pkg/httpclient/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ import (
"fmt"
"io"
"net/http"

"github.com/KyberNetwork/tradinglib/pkg/sb"
"net/url"
)

func DoHTTPRequest(client *http.Client, req *http.Request, out interface{}, options ...Option) (*http.Response, error) {
Expand Down Expand Up @@ -47,11 +46,25 @@ func NewRequest(method, baseURL, path string, query Query, body io.Reader) (*htt
func NewRequestWithContext(
ctx context.Context, method, baseURL, path string, query Query, body io.Reader,
) (*http.Request, error) {
url := baseURL + path
u, err := url.Parse(baseURL)
if err != nil {
return nil, fmt.Errorf("parse url: %w", err)
}

if path != "" {
u = u.JoinPath(path)
}
if query != nil {
url = sb.Concat(url, "?", query.String())
existingQuery := u.Query()
for key, values := range existingQuery {
for _, value := range values {
query.AddString(key, value)
}
}
u.RawQuery = query.String()
}
return http.NewRequestWithContext(ctx, method, url, body)

return http.NewRequestWithContext(ctx, method, u.String(), body)
}

func NewGet(baseURL, path string, query Query) (*http.Request, error) {
Expand Down
5 changes: 5 additions & 0 deletions pkg/httpclient/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ func (q Query) SetString(key, value string) Query {
return q
}

func (q Query) AddString(key, value string) Query {
q.url().Add(key, value)
return q
}

func stringsContains(ss []string, token string) bool {
for _, s := range ss {
if s == token {
Expand Down

0 comments on commit 1f7d86e

Please sign in to comment.