Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor code improvements #1

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 33 additions & 42 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import (

type ClientOptions map[string]interface{}

func (opt *ClientOptions) Merge(other ClientOptions) {
func (c ClientOptions) Merge(other ClientOptions) {
for key := range other {
(*opt)[key] = other[key]
c[key] = other[key]
}
}

Expand All @@ -30,30 +30,30 @@ func New() *Request {
return NewRequest(Cleaned())
}

func Default() (cl *StandardClient) {
func Default() *StandardClient {
return &StandardClient{
Client: &http.Client{},
Logger: defaultLogger,
}
}

func Cleaned() (cl *StandardClient) {
func Cleaned() *StandardClient {
return &StandardClient{
Client: cleanhttp.DefaultClient(),
Logger: defaultLogger,
}
}

func Pooled() (cl *StandardClient) {
func Pooled() *StandardClient {
return &StandardClient{
Client: cleanhttp.DefaultPooledClient(),
Logger: defaultLogger,
}
}

func NewClient(clients ...*http.Client) (cl *StandardClient) {

func NewClient(clients ...*http.Client) *StandardClient {
var client *http.Client

if len(clients) == 0 {
client = &http.Client{}
} else {
Expand All @@ -66,66 +66,57 @@ func NewClient(clients ...*http.Client) (cl *StandardClient) {
}
}

func (client *StandardClient) Error() error {
return client.err
func (cl StandardClient) Error() error {
return cl.err
}

func (client *StandardClient) With(options ...interface{}) *StandardClient {

func (cl *StandardClient) With(options ...interface{}) *StandardClient {
for _, option := range options {
switch option.(type) {
case time.Duration:
client.Timeout = option.(time.Duration)
cl.Timeout = option.(time.Duration)

case http.RoundTripper:
client.Transport = option.(http.RoundTripper)
cl.Transport = option.(http.RoundTripper)

case http.CookieJar:
client.Jar = option.(http.CookieJar)
cl.Jar = option.(http.CookieJar)
}
}
return client
return cl
}

func (client *StandardClient) WithTimeout(
timeout time.Duration) *StandardClient {

client.Timeout = timeout
return client
func (cl *StandardClient) WithTimeout(timeout time.Duration) *StandardClient {
cl.Timeout = timeout
return cl
}

func (client *StandardClient) WithJar(jar http.CookieJar) *StandardClient {

client.Jar = jar
return client
func (cl *StandardClient) WithJar(jar http.CookieJar) *StandardClient {
cl.Jar = jar
return cl
}

func (client *StandardClient) SetCookies(
host string, cookies ...*http.Cookie) *StandardClient {

if client.Jar == nil {
client.Jar, _ = cookiejar.New(nil)
func (cl *StandardClient) SetCookies(host string, cookies ...*http.Cookie) *StandardClient {
if cl.Jar == nil {
cl.Jar, _ = cookiejar.New(nil)
}

u, _ := url.Parse(host)
client.Jar.SetCookies(u, cookies)
return client
cl.Jar.SetCookies(u, cookies)
return cl
}

func (client *StandardClient) Cookies(host string) []*http.Cookie {
func (cl StandardClient) Cookies(host string) []*http.Cookie {
u, _ := url.Parse(host)
return client.Jar.Cookies(u)
return cl.Jar.Cookies(u)
}

func (client *StandardClient) WithTransport(
transport http.RoundTripper) *StandardClient {

client.Transport = transport
return client
func (cl *StandardClient) WithTransport(transport http.RoundTripper) *StandardClient {
cl.Transport = transport
return cl
}

func (client *StandardClient) WithLogger(logger Logger) *StandardClient {

client.Logger = logger
return client
func (cl *StandardClient) WithLogger(logger Logger) *StandardClient {
cl.Logger = logger
return cl
}
7 changes: 4 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ module github.com/GarryGaller/go-www

go 1.17

require github.com/softlandia/cpd v0.0.0-20210117083209-2413526f2815
require (
github.com/hashicorp/go-cleanhttp v0.5.2
github.com/softlandia/cpd v0.0.0-20210117083209-2413526f2815
)

require (
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/stretchr/testify v1.7.0 // indirect
golang.org/x/net v0.0.0-20211111160137-58aab5ef257a // indirect
golang.org/x/text v0.3.6 // indirect
)
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ github.com/softlandia/cpd v0.0.0-20210117083209-2413526f2815/go.mod h1:4xzl60B5T
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/net v0.0.0-20211111160137-58aab5ef257a h1:c83jeVQW0KGKNaKBRfelNYNHaev+qawl9yaA825s8XE=
golang.org/x/net v0.0.0-20211111160137-58aab5ef257a/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
Expand Down
92 changes: 39 additions & 53 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
"strings"
)

var ErrorEmptyListValues = errors.New("An empty list of values is passed to create multipart content")
var ErrorEmptyListValues = errors.New("an empty list of values is passed to create multipart content")

type Request struct {
*http.Request
Expand All @@ -27,50 +27,37 @@ type Request struct {
}

func NewRequest(client *StandardClient) *Request {
return &Request{client: client}
return &Request{
client: client,
}
}

func (r *Request) Error() error {
func (r Request) Error() error {
return r.err
}

func (r *Request) Headers() (out http.Header) {
func (r Request) Headers() (out http.Header) {
if r.Request != nil {
out = r.Request.Header
}
return

return out
}

func (r *Request) Cookies() (out []*http.Cookie) {
func (r Request) Cookies() (out []*http.Cookie) {
if r.Request != nil {
out = r.Request.Cookies()
}
return
}

/*
func (r *Request) SetHeaders(headers http.Header) *Request {
for key, val := range headers {
r.Request.Header.Set(key, val[0])
}
return r
}

func (r *Request) AddHeaders(headers http.Header) *Request {
for key, val := range headers {
r.Request.Header.Add(key, val[0])
}
return r
return out
}
*/

func (r *Request) SetCookies(cookies ...*http.Cookie) *Request {
r.cookies = cookies
return r
}

func (r *Request) prepareCookies() {

for _, cookie := range r.cookies {
r.Request.AddCookie(cookie)
}
Expand Down Expand Up @@ -106,62 +93,63 @@ func (r *Request) prepareRequest(
}

func (r *Request) Get(uri string, headers ...http.Header) *Response {

return r.Do("GET", uri, headers...)
return r.Do(http.MethodGet, uri, headers...)
}

func (r *Request) Post(
uri string, headers ...http.Header) *Response {

return r.Do("POST", uri, headers...)
func (r *Request) Post(uri string, headers ...http.Header) *Response {
return r.Do(http.MethodPost, uri, headers...)
}

func (r *Request) Put(uri string, headers ...http.Header) *Response {
return r.Do("PUT", uri, headers...) // with body, output body
return r.Do(http.MethodPut, uri, headers...) // with body, output body
}

func (r *Request) Patch(uri string, headers ...http.Header) *Response {
return r.Do("PATCH", uri, headers...) // with body, output body
return r.Do(http.MethodPatch, uri, headers...) // with body, output body
}

func (r *Request) Delete(uri string, headers ...http.Header) *Response {
return r.Do("DELETE", uri, headers...) // can have a body, output body
return r.Do(http.MethodDelete, uri, headers...) // may have a body, output body
}

func (r *Request) Head(uri string) *Response {
return r.Do("HEAD", uri) // no body
return r.Do(http.MethodHead, uri) // no body
}

func (r *Request) Trace(uri string) *Response {
return r.Do("TRACE", uri) // no body
return r.Do(http.MethodTrace, uri) // no body
}

func (r *Request) Options(uri string) *Response {
return r.Do("OPTIONS", uri) // no body
return r.Do(http.MethodOptions, uri) // no body
}

func (r *Request) Connect(uri string) *Response {
return r.Do("CONNECT", uri) // no body
return r.Do(http.MethodConnect, uri) // no body
}

func (r *Request) Do(method string,
uri string, headers ...http.Header) *Response {

func (r *Request) Do(method string, uri string, headers ...http.Header) *Response {
var err error

defer closeReader(r.body)

if r.err != nil {
return &Response{nil, nil, nil}
return &Response{nil, r.err, nil}
}

r.prepareRequest(method, uri, headers...)
r.prepareCookies()
if r.err != nil {
return &Response{nil, nil, nil}
return &Response{nil, r.err, nil}
}

resp, err := r.client.Do(r.Request)

return &Response{resp, err, nil}
return &Response{
Response: resp,
err: err,
content: nil,
}
}

func (r *Request) With(params *url.Values, data *url.Values) *Request {
Expand Down Expand Up @@ -217,8 +205,7 @@ func (r *Request) AttachFile(reader io.Reader, contentType ...string) *Request {
return r
}

body := &bytes.Buffer{}

body := new(bytes.Buffer)
writer := multipart.NewWriter(body)

if part, err = CreateFormFile(
Expand All @@ -242,18 +229,18 @@ func (r *Request) AttachFile(reader io.Reader, contentType ...string) *Request {
}

func (r *Request) AttachFiles(files map[string][]interface{}) *Request {

var (
err error
fileName string
contentType string
part io.Writer
)

body := &bytes.Buffer{}

body := new(bytes.Buffer)
writer := multipart.NewWriter(body)

var closeReaders []io.Reader

for field, values := range files {
if len(values) == 0 {
r.err = ErrorEmptyListValues
Expand All @@ -275,14 +262,11 @@ func (r *Request) AttachFiles(files map[string][]interface{}) *Request {

if f, ok := reader.(*os.File); ok {
fileName = filepath.Base(f.Name())
defer func(reader io.Reader) {
closeReader(reader)
}(reader)
closeReaders = append(closeReaders, f)

if part, err = CreateFormFile(
writer, field, fileName, contentType); err != nil {
r.err = err
//closeReader(reader)
continue
}
} else {
Expand All @@ -295,13 +279,15 @@ func (r *Request) AttachFiles(files map[string][]interface{}) *Request {
r.err = err
continue
}

//closeReader(reader)
}

r.mime = writer.FormDataContentType()
writer.Close()
r.body = body

for _, reader := range closeReaders {
closeReader(reader)
}

return r
}
Loading