Skip to content

Commit

Permalink
version 2.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
Navid2zp committed Jun 8, 2020
1 parent cd41fc4 commit 6fcbc45
Show file tree
Hide file tree
Showing 3 changed files with 120 additions and 97 deletions.
139 changes: 72 additions & 67 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ This package uses builtin ```net/http``` to make requests.

`json` and `xml` package will be used to unmarshal these types.

For now there is no support for third party packages.

### Install
```
go get github.com/Navid2zp/easyreq
Expand All @@ -19,33 +17,9 @@ import (
"github.com/Navid2zp/easyreq"
)

type MyData struct {
Name string `json:"name" xml:"name"`
LastName string `json:"last_name" xml:"last_name"`
Github string `json:"github" xml:"github"`
}

func main() {

sendData := MyData{
Name: "Navid",
LastName: "Zarepak",
Github: "Navid2zp",
}

result := MyData{}

ereq := easyreq.Request{
URL: "https://site.com/api",
Method: "post",
Data: []byte(sendData),
RequestDataType: "json",
ResponseDataType: "json",
SaveResponseTo: &result,
Headers: map[string]string{
"Content-Type": "application/json",
},
}
ereq = easyreq.NewRequest("GET", "https://site.com/api")
resp, err := ereq.Make()
if err != nil {
fmt.Println(err)
Expand All @@ -54,61 +28,95 @@ func main() {
}
```

You can also make a request using ```Make()``` function:
##### Unmarshaling
You can unmarshal the response directly:

```go
res, err := easyreq.Make(
"post", // Request method
"https://site.com/api", // URL
[]byte(sendData), // Data to send
"json", // Request data type
"json", // Response data type
&result, map[string]string{"Content-Type": "application/json",}, // Headers
)
type MyData struct {
Name string `json:"name" xml:"name"`
LastName string `json:"last_name" xml:"last_name"`
Github string `json:"github" xml:"github"`
}
var stringResult string
var result MyData

err := resp.ToJson(&result)
// or xml:
err := resp.ToXML(&result)
// Or string:
err := resp.ToString(&stringResult)
```

##### Posting Data
You pass any type of data to be posted with the request.

###### Byte:
```go
ereq.SetData([]byte("this is my data"))
```

###### Reader:
```go
ereq.SetDataReader(strings.NewReader("this is my data"))
```


###### String:
```go
ereq.SetStringData("this is my data")
```

By providing ```ResponseDataType``` and ```SaveResponseTo``` package will try to parse the response to the given ```ResponseDataType``` and the result will be saved to where ```SaveResponseTo``` points.
###### JSON/XML:
```go
sendData := MyData{
Name: "Navid",
LastName: "Zarepak",
Github: "Navid2zp",
}

err := ereq.SetJsonData(sendData)
err := ereq.SetXMLData(sendData)
```

#### ```easyreq.Request``` Args
##### Request header

| Arg | Description | Type |
|----------------------|-------------------------------------------------------------|--------------------|
|**URL** | URL to send the request to. | string
|**Method** | Request method (default is get) | string
|**Data** | Data to send with request | []byte
|**RequestDataType** | Data type for request (json, xml, string, ...) | string
|**ResponseDataType** | Data type for response (Will be used to parse the response) | string
|**SaveResponseTo** | Where parsed data for response should be saved to | pointer
|**Headers** | Request headers | map[string]string
```go
myHeaders := map[string]string{"myHeader": "Header Value"}
ereq.SetHeaders(myHeaders)

// Add a header:
ereq.AddHeader("NewHeaderKey", "Value")
```

##### Download Files
You can download files directly by calling ```DownloadAsFile``` method on a request response and providing a path to save the file.
```go
result, err := resp.DownloadAsFile("myfile.zip")

#### Methods
fmt.Println("Bytes copied:", result.BytesCopied)
fmt.Println("Download time:", result.DownloadTime)
```

Request shortcuts:
```Get(url string)```, ```Post(url string, data []byte)```, ```Put(url string, data []byte)```, ```Patch(url string, data []byte)``` and ```Delete(url string)```.
##### Proxy

These methods can be called on ```Make()``` response which is a ```easyreq.RequestResponse``` Type containing the original response from request sent with ```net/http``` package.

```go
// A pointer to your struct to save the data to.
// Uses 'json' package to unmarshal the response body.
// Returns error if anything goes wrong.
err := resp.ToJson(&result)
ereq.SetHttpProxy("http://<PROXY_ADDRESS>:<PROXY_PORT>")
```

// A pointer to your struct to save the data to.
// Uses 'xml' package to unmarshal the response body.
// Returns error if anything goes wrong.
err := resp.ToXML(&result)

// A pointer to a string.
// Response body will be converted to string and saved to the given pointer.
// Returns error if anything goes wrong.
err := resp.ToString(&result)
##### Request Shortcuts

```go
response, err := easyreq.Get("http://site.com")
response, err := easyreq.Post("http://site.com", []byte("my data"))
response, err := easyreq.Put("http://site.com", []byte("my data"))
response, err := easyreq.Patch("http://site.com", []byte("my data"))
response, err := easyreq.Delete("http://site.com")
```

Other useful methods:
##### Response Methods

```go
// Returns status code (200, ...)
// Type: int
Expand All @@ -133,9 +141,6 @@ resp.ReadBody()
// Close response body
resp.CloseBody()

// Downloads the body and saves it into the given path.
// Type: DownloadResult, error
resp.DownloadAsFile("myfile.zip")
```

You can also access the original response returned by ```http``` package by calling ```resp.Response```. (Will be a pointer to original response)
Expand Down
76 changes: 46 additions & 30 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,7 @@ func (r *Request) Make() (*RequestResponse, error) {
if err != nil {
return nil, err
}
data, err := r.getData()
if err != nil {
return nil, err
}
req, err := http.NewRequest(r.getMethod(), r.URL, bytes.NewBuffer(data))
req, err := http.NewRequest(r.getMethod(), r.URL, r.getData())
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -81,28 +77,12 @@ func NewRequest(method, url string) *Request {
}
}

// Returns request data based on information provided
// It will convert data type if it doesn't match what has been set as RequestDataType
func (r *Request) getData() ([]byte, error) {
if r.RequestDataType != "" {
switch strings.ToLower(r.RequestDataType) {
case "json":
if !IsJson(r.Data) {
jsonData, err := json.Marshal(r.Data)
return jsonData, err
}
return r.Data, nil
case "xml":
if !IsXML(r.Data) {
xmlData, err := xml.Marshal(r.Data)
return xmlData, err
}
return r.Data, nil
default:
return r.Data, nil
}
// getData returns request data
func (r *Request) getData() io.Reader {
if r.Data != nil {
return bytes.NewReader(r.Data)
}
return r.Data, nil
return r.DataReader
}

func Get(url string) (*RequestResponse, error) {
Expand Down Expand Up @@ -223,6 +203,7 @@ func (r *RequestResponse) Headers() http.Header {
return r.Response.Header
}


// Returns response body
func (r *RequestResponse) Body() io.ReadCloser {
return r.Response.Body
Expand Down Expand Up @@ -252,13 +233,48 @@ func (r *RequestResponse) DownloadAsFile(fileName string) (*DownloadResult, erro
}, err
}

// SetHeaders sets request headers
func (r *Request) SetHeaders(headers map[string]string) {
r.Headers = headers
// SetData sets data to request
func (r *Request) SetData(data []byte) {
r.Data = data
}

// SetDataReader sets data reader for request
func (r *Request) SetDataReader(reader io.Reader) {
r.DataReader = reader
}

// SetStringData sets request data from string
func (r *Request) SetStringData(data string) {
r.DataReader = strings.NewReader(data)
}

// SetJsonData converts the data to json and adds it to request
func (r *Request) SetJsonData(data interface{}) error {
var err error
r.Data, err = json.Marshal(data)
return err
}

// SetJsonData converts the data to XML and adds it to request
func (r *Request) SetXMLData(data interface{}) error {
var err error
r.Data, err = xml.Marshal(data)
return err
}

func (r *Request) SetProxy(proxy string) error {
// SetProxy sets proxy for request
func (r *Request) SetHttpProxy(proxy string) error {
proxyURL, err := url.Parse(proxy)
r.Proxy = proxyURL
return err
}

// AddHeader adds a new header to request headers
func (r *Request) AddHeader(key, value string) {
r.Headers[key] = value
}

// AddHeader adds a new header to request headers
func (r *Request) SetHeaders(headers map[string]string) {
r.Headers = headers
}
2 changes: 2 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package easyreq

import (
"io"
"net/http"
"net/url"
"time"
Expand All @@ -10,6 +11,7 @@ type Request struct {
URL string
Headers map[string]string
Data []byte
DataReader io.Reader
Method string
RequestDataType string
ResponseDataType string
Expand Down

0 comments on commit 6fcbc45

Please sign in to comment.