From 9c4cb4e2f6b0493f0d46add000de0109d863c243 Mon Sep 17 00:00:00 2001 From: Antonio Thomacelli Date: Tue, 16 Jul 2024 10:30:00 -0300 Subject: [PATCH] feat: improve examples and commets --- .gitignore | 1 + Readme.md | 46 +++++++++++++++++++++++++++++ examples/main.go | 31 ++++++++++++++------ go.mod | 2 -- go.sum | 2 -- webreq.go | 73 ++++++++++++++++++---------------------------- webreq_get_test.go | 2 +- 7 files changed, 99 insertions(+), 58 deletions(-) diff --git a/.gitignore b/.gitignore index 9b60833..01418ae 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # IDE .idea +.DS_Store # Binaries for programs and plugins *.exe *.exe~ diff --git a/Readme.md b/Readme.md index 1a9a22e..fcf4655 100644 --- a/Readme.md +++ b/Readme.md @@ -31,6 +31,52 @@ So many times I needed to make a request in an API and after convert body to str What do you think? Liked, set star in this project to help me to help others! +### Using only Http Get + + client := &http.Client{ + Timeout: 10 * time.Second, + } + + req, err := http.NewRequest("GET", "https://api.example.com/data", nil) + if err != nil { + fmt.Println("Error creating request:", err) + return + } + req.Header.Add("Authorization", "Bearer your_token") + + resp, err := client.Do(req) + if err != nil { + fmt.Println("Error executing request:", err) + return + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + fmt.Println("Error reading response body:", err) + return + } + fmt.Println("Response:", string(body)) + +### Using WebReq + + headers := webreq.NewHeaders(map[string]string{ + "Content-Type": "application/json", + "Authorization": "Bearer your_token", + }) + + request := webreq.NewRequest("POST") + request.SetURL("https://api.example.com/data") + request.SetData([]byte(`{"key":"value"}`)) + request.SetHeaders(headers.Headers) + request.SetTimeout(10) + + response, err := request.Execute() + if err != nil { + fmt.Println("Error executing request:", err) + return + } + fmt.Println("Response:", string(response)) ## Install diff --git a/examples/main.go b/examples/main.go index 396e438..ad78bee 100644 --- a/examples/main.go +++ b/examples/main.go @@ -7,43 +7,56 @@ import ( "time" ) +// Friend represents a friend with a creation date and name type Friend struct { CreatedAt time.Time `json:"createdAt"` Name string `json:"name"` } func main() { - + // Initialize headers with an empty map headers := webreq.NewHeaders(nil) + // Add Content-Type header headers.Add("Content-Type", "application/json") + // Create a new Friend instance f := Friend{ CreatedAt: time.Now(), Name: "Tonny", } - // convert f to bytes + // Convert Friend instance to JSON bytes fBytes, err := json.Marshal(f) if err != nil { - fmt.Println(err) + fmt.Println("Error marshalling JSON:", err) + return } + // Create a new POST request request := webreq.NewRequest("POST") + // Set the request URL request.SetURL("https://623a666d5f037c136217238f.mockapi.io/api/v1/categories") + // Set the request body data request.SetData(fBytes) + // Set the request headers request.SetHeaders(headers.Headers) // Set map directly + // Set the request timeout to 10 seconds request.SetTimeout(10) + // Execute the request and get the response response, err := request.Execute() if err != nil { - fmt.Println(err) + fmt.Println("Error executing request:", err) + return } + + // Convert response bytes to string bodyString := string(response) if bodyString == "" { - fmt.Println("response status code:", request.StatusCode) - fmt.Println("response body:", bodyString) + fmt.Println("Response status code:", request.StatusCode) + fmt.Println("Response body:", bodyString) + } else { + fmt.Println("Response status code:", request.StatusCode) + fmt.Println("Response body:", bodyString) } - - fmt.Println("response status code:", request.StatusCode) - fmt.Println("response body:", bodyString) } diff --git a/go.mod b/go.mod index c4374c6..533a301 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,3 @@ module github.com/tonnytg/webreq go 1.18 - -require github.com/tonnytg/pkggowebreq v0.0.0-20220505023532-f729b5cf91a6 diff --git a/go.sum b/go.sum index 13ba91f..e69de29 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +0,0 @@ -github.com/tonnytg/pkggowebreq v0.0.0-20220505023532-f729b5cf91a6 h1:OcB6yC+OskPqDjbsss5xcn6xng6RHSnYOTohtE+OlYY= -github.com/tonnytg/pkggowebreq v0.0.0-20220505023532-f729b5cf91a6/go.mod h1:oDaweQylMDBYSIatY6mTnh3dKw72ss+Yl2c2MyJAm1o= diff --git a/webreq.go b/webreq.go index 755b8b4..0d46d3d 100644 --- a/webreq.go +++ b/webreq.go @@ -19,8 +19,9 @@ type Headers struct { Headers HeadersMap } +// NewHeaders creates a new Headers instance, initializing with provided headers or an empty map func NewHeaders(headers map[string]string) *Headers { - if len(headers) != 0 { + if headers != nil { return &Headers{ Headers: headers, } @@ -30,11 +31,11 @@ func NewHeaders(headers map[string]string) *Headers { } } +// Add adds a new header key-value pair to the Headers func (header *Headers) Add(key string, value string) { - if key == "" || value == "" { - return + if key != "" && value != "" { + header.Headers[key] = value } - header.Headers[key] = value } type Request struct { @@ -47,23 +48,15 @@ type Request struct { ErrorMessage string } -// NewRequest create new request with method but you can change it later with SetMethod +// NewRequest creates a new Request with the specified method func NewRequest(method string) *Request { - - request := Request{} - - r := request.SetMethod(method) - if r == nil { - return nil - } - return &Request{ TimeoutDuration: 10 * time.Second, Method: method, } } -// SetURL sets the url of the request and checks if it is empty +// SetURL sets the URL of the request func (request *Request) SetURL(urlValue string) *Request { if urlValue == "" { request.ErrorMessage = "url is empty" @@ -73,60 +66,55 @@ func (request *Request) SetURL(urlValue string) *Request { return request } -// SetTimeout sets the timeout and multiplier 10 by time.Second +// SetTimeout sets the request timeout duration func (request *Request) SetTimeout(timeout int) *Request { - if timeout == 0 { - request.TimeoutDuration = time.Duration(10) * time.Second - return request + if timeout > 0 { + request.TimeoutDuration = time.Duration(timeout) * time.Second } - request.TimeoutDuration = time.Duration(timeout) * time.Second return request } -// SetHeaders sets the headers of the request and checks if it is empty -// you can user add or create map[string]string and use NewHeaders +// SetHeaders sets the headers of the request func (request *Request) SetHeaders(headers HeadersMap) *Request { - if len(headers) == 0 { - request.ErrorMessage = "headers is empty" - return request + if len(headers) > 0 { + request.Headers = headers + } else { + request.ErrorMessage = "headers are empty" } - request.Headers = headers return request } -// SetData it is data to send with POST, PUT, PATCH +// SetData sets the data to be sent with the request func (request *Request) SetData(bodyValue []byte) *Request { - if len(bodyValue) == 0 { + if len(bodyValue) > 0 { + request.Data = bodyValue + } else { request.ErrorMessage = "body is empty" - return request } - request.Data = bodyValue return request } -// SetMethod sets the method of the request and checks if it is empty +// SetMethod sets the method of the request func (request *Request) SetMethod(requestMethod string) *Request { - if requestMethod == "" { + if requestMethod != "" { + request.Method = requestMethod + } else { request.ErrorMessage = "request method is empty" - return nil } - request.Method = requestMethod return request } -// SetStatusCode get Statuscode from response and save in object request -// if status code is equal 0 then return error +// SetStatusCode sets the status code of the response func (request *Request) SetStatusCode(statusCodeValue int) *Request { - if statusCodeValue == 0 { + if statusCodeValue > 0 { + request.StatusCode = statusCodeValue + } else { request.ErrorMessage = "status code is empty" - return request } - request.StatusCode = statusCodeValue return request } -// Execute send request and return slice of bytes and error -// check tests GET and POST to see how to use or folder examples +// Execute sends the request and returns the response body and error if any func (request *Request) Execute() ([]byte, error) { client := &http.Client{} ctx, cancel := context.WithTimeout(context.Background(), request.TimeoutDuration) @@ -147,14 +135,11 @@ func (request *Request) Execute() ([]byte, error) { } defer response.Body.Close() - if response != nil { - request.SetStatusCode(response.StatusCode) - } - responseBody, err := io.ReadAll(response.Body) if err != nil { return nil, err } + request.StatusCode = response.StatusCode return responseBody, nil } diff --git a/webreq_get_test.go b/webreq_get_test.go index 44cc343..cc6e0ce 100644 --- a/webreq_get_test.go +++ b/webreq_get_test.go @@ -29,8 +29,8 @@ func TestPackageCall(t *testing.T) { } } +// TestSetURL verify URL it is correctly defined func TestSetURL(t *testing.T) { - // Teste para verificar se a URL é definida corretamente quando não está vazia t.Run("Non-empty URL", func(t *testing.T) { request := webreq.NewRequest("GET") request.SetURL("https://example.com")