Skip to content

Commit

Permalink
feat: improve examples and commets
Browse files Browse the repository at this point in the history
  • Loading branch information
tonnytg committed Jul 20, 2024
1 parent 0f82fad commit 9c4cb4e
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 58 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# IDE
.idea
.DS_Store
# Binaries for programs and plugins
*.exe
*.exe~
Expand Down
46 changes: 46 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
31 changes: 22 additions & 9 deletions examples/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
2 changes: 0 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
module github.com/tonnytg/webreq

go 1.18

require github.com/tonnytg/pkggowebreq v0.0.0-20220505023532-f729b5cf91a6
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -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=
73 changes: 29 additions & 44 deletions webreq.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand All @@ -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 {
Expand All @@ -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"
Expand All @@ -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)
Expand All @@ -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
}
2 changes: 1 addition & 1 deletion webreq_get_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down

0 comments on commit 9c4cb4e

Please sign in to comment.