easyreq

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 5, 2020 License: MIT Imports: 11 Imported by: 4

README

easyreq

Make HTTP requests in go as easy as possible!

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
Usage
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",
		},
    }
    resp, err := ereq.Make()
    if err != nil {
        fmt.Println(err)
    }
    defer resp.CloseBody()
}

You can also make a request using Make() function:

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
)

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.

easyreq.Request Args
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
Methods

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

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.

// 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)

// 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)

Other useful methods:

// Returns status code (200, ...)
// Type: int
resp.StatusCode()

// Returns status code (200 OK) 
// Type: string
resp.Status()

// Returns response headers
// Type: http.Header
resp.Headers()

// Retunrs response body
// Type: io.ReadCloser
resp.Body()

// Reads response body into bytes using `ioutil` and returns the result.
Type: []byte, error
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)

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsJson

func IsJson(data []byte) bool

Check if string is a json

func IsXML

func IsXML(data []byte) bool

Check if string is a XML

Types

type DownloadResult

type DownloadResult struct {
	BytesCopied  int64
	DownloadTime time.Duration
}

type Request

type Request struct {
	URL              string
	Headers          map[string]string
	Data             []byte
	Method           string
	RequestDataType  string
	ResponseDataType string
	SaveResponseTo   interface{}
}

func (*Request) Make

func (r *Request) Make() (*RequestResponse, error)

Send the final request

type RequestResponse

type RequestResponse struct {
	Response *http.Response
	Header   http.Header
}

func Delete

func Delete(url string) (*RequestResponse, error)

func Get

func Get(url string) (*RequestResponse, error)

func Make

func Make(method, url string, data []byte, dataType, responseType string, saveTo interface{}, headers map[string]string) (*RequestResponse, error)

Either call this function to create a request Or call Request type directly and call Make(). Both will do the same.

func Patch

func Patch(url string, data []byte) (*RequestResponse, error)

func Post

func Post(url string, data []byte) (*RequestResponse, error)

func Put

func Put(url string, data []byte) (*RequestResponse, error)

func (*RequestResponse) Body

func (r *RequestResponse) Body() io.ReadCloser

Returns response body

func (*RequestResponse) CloseBody

func (r *RequestResponse) CloseBody() error

Close response body

func (*RequestResponse) DownloadAsFile

func (r *RequestResponse) DownloadAsFile(fileName string) (*DownloadResult, error)

Downloads the body and saves it into the given path

func (*RequestResponse) Headers

func (r *RequestResponse) Headers() http.Header

Returns response headers

func (*RequestResponse) ReadBody

func (r *RequestResponse) ReadBody() ([]byte, error)

Reads response body into bytes and returns the result

func (*RequestResponse) Status

func (r *RequestResponse) Status() string

Returns status (string: 200 OK)

func (*RequestResponse) StatusCode

func (r *RequestResponse) StatusCode() int

Returns response status code (int: 200)

func (*RequestResponse) ToJson

func (r *RequestResponse) ToJson(saveTo interface{}) error

Unmarshals json response and saves it into the given pointer

func (*RequestResponse) ToString

func (r *RequestResponse) ToString(saveTo interface{}) error

converts response to string and saves into the given pointer

func (*RequestResponse) ToXML

func (r *RequestResponse) ToXML(saveTo interface{}) error

Unmarshals xml response and saves into the given pointer

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL