requests

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: May 8, 2023 License: Apache-2.0 Imports: 16 Imported by: 0

README

Requests

Requests is an elegant and simple HTTP library for Go.

Install

go get github.com/fanjindong/go-requests

QuickStart

Make a Request

Making a request with Requests is very simple. For this example:

resp, err := requests.Get("https://example.com/ping", requests.Params{"key": "value"})

Now, we have a Response object called resp. We can get all the information we need from this object.

Requests’ simple API means that all forms of HTTP request are as obvious. For example, this is how you make an HTTP POST request:

resp, err := requests.Post("https://example.com/ping", requests.Params{"k": "v"}, requests.Json{"key": "value"})

What about the other HTTP request types: PUT, DELETE, HEAD and OPTIONS? These are all just as simple:

resp, err := requests.Put("https://example.com/ping", requests.Form{"key": "value"})
resp, err := requests.Delete("https://example.com/ping")
resp, err := requests.Head("https://example.com/ping")
resp, err := requests.Options("https://example.com/ping")

That’s all well and good, but it’s also only the start of what Requests can do.

Passing Parameters In URLs

You often want to send some sort of data in the URL’s query string. If you were constructing the URL by hand, this data would be given as key/value pairs in the URL after a question mark, e.g. example.com/get?key=val. Requests allows you to provide these arguments as a dictionary of strings, using the params keyword argument. As an example, if you wanted to pass key1=value1 and key2=value2 to example.com/get, you would use the following code:

resp, err := requests.Get("https://example.com/get", requests.Params{"key1": "value1", "key2": "value2"})

You can see that the URL has been correctly encoded by printing the URL:

fmt.Println(resp.Request.URL)
//https://example.com/get?key2=value2&key1=value1
Response Content

We can read the content of the server’s response. Consider the GitHub timeline again:

resp, _ := requests.Get("https://api.github.com/events")
fmt.Println(resp.Text)
//{"code":0,"message":"pong"}
JSON Response Content

There’s also a builtin JSON decoder, in case you’re dealing with JSON data:

var response struct{
    Code    int    `json:"code"`
    Message string `json:"message"`
}

resp.Json(&response)
fmt.Printf("resp.Json to struct: %+v \n", response)
// resp.Json to struct: {Code:0, Message:"success"} 
Custom Headers

If you’d like to add HTTP headers to a request, simply pass in a requests.Headers to the headers parameter.

For example, we did not specify our user-agent in the previous example:

resp, _ := requests.Get("https://api.github.com/some/endpoint", requests.Headers{"user-agent": "my-app/0.0.1"})
More complicated POST requests

Typically, you want to send some form-encoded data — much like an HTML form. To do this, simply pass a requests.Form to the data argument. Your data will automatically be form-encoded when the request is made:

resp, _ := requests.Post("https://httpbin.org/post", requests.Form{"key1": "value1", "key2": "value2"})
fmt.Println(r.Text())
//{"code":0,"message":"pong"}

For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data, you can also pass it requests.Json using the json parameter and it will be encoded automatically:

resp, _ := requests.Post("https://api.github.com/some/endpoint", requests.Json{"key1": "value1", "key2": "value2"})

Using the requests.Json in the request will change the Content-Type in the header to application/json.

Response Status Codes

We can check the response status code:

resp, _ := requests.Get("https://httpbin.org/get")
fmt.Println(resp.StatusCode)
// 200
Response Header

We can view the server’s response header:

fmt.Println(resp.Header)
//map[Cache-Control:[private] Content-Type:[application/json] Set-Cookie:[QINGCLOUDELB=d9a2454c187d2875afb6701eb80e9c8761ebcf3b54797eae61b25b90f71273ea; path=/; HttpOnly]]

We can access the headers using Get method:

resp.Headers.Get("Content-Type")
//"application/json"

Documentation

Index

Constants

View Source
const (
	GET     = "GET"
	POST    = "POST"
	PUT     = "PUT"
	DELETE  = "DELETE"
	OPTIONS = "OPTIONS"
	PATCH   = "PATCH"
	HEAD    = "HEAD"
)

Variables

View Source
var (
	// ErrInvalidForm will be throw out when request form body data can not be Marshal
	ErrInvalidForm = errors.New("go-requests: Invalid Form value")

	// ErrInvalidJson will be throw out when request json body data can not be Marshal
	ErrInvalidJson = errors.New("go-requests: Invalid Json value")

	// ErrInvalidMethod will be throw out when method not in
	// [HEAD, GET, POST, DELETE, OPTIONS, PUT, PATCH, CONNECT, TRACE]
	ErrInvalidMethod = errors.New("go-requests: Method is invalid")

	//ErrInvalidFile will be throw out when get file content data
	ErrInvalidFile = errors.New("go-requests: Invalid file content")

	ErrInvalidBodyType = errors.New("go-requests: Invalid Body Type")

	ErrTimeout = errors.New("go-requests: timeout")
)
View Source
var DefaultClient = &Client{Client: http.DefaultClient}

Functions

func FileWithContent added in v0.1.3

func FileWithContent(field, fileName string, content []byte) *file

func FileWithPath added in v0.1.3

func FileWithPath(field string, path string) *file

Types

type Client added in v0.1.3

type Client struct {
	*http.Client
	// contains filtered or unexported fields
}

func NewClient added in v0.1.3

func NewClient(opts ...ClientOption) *Client

func (*Client) AddHook added in v0.1.3

func (s *Client) AddHook(h Hook)

func (*Client) Delete added in v0.1.3

func (s *Client) Delete(url string, opts ...ReqOption) (*Response, error)

func (*Client) Get added in v0.1.3

func (s *Client) Get(url string, opts ...ReqOption) (*Response, error)

func (*Client) Head added in v0.1.3

func (s *Client) Head(url string, opts ...ReqOption) (*Response, error)

func (*Client) Patch added in v0.1.3

func (s *Client) Patch(url string, opts ...ReqOption) (*Response, error)

func (*Client) Post added in v0.1.3

func (s *Client) Post(url string, opts ...ReqOption) (*Response, error)

func (*Client) Put added in v0.1.3

func (s *Client) Put(url string, opts ...ReqOption) (*Response, error)

func (*Client) ReqOptions added in v0.1.3

func (s *Client) ReqOptions(url string, opts ...ReqOption) (*Response, error)

func (*Client) Request added in v0.1.3

func (s *Client) Request(method, url string, opts ...ReqOption) (*Response, error)

type ClientOption added in v0.1.3

type ClientOption func(client *Client)

func WithCheckRedirect added in v0.1.3

func WithCheckRedirect(checkRedirect func(req *http.Request, via []*http.Request) error) ClientOption

func WithJar added in v0.1.3

func WithJar(jar http.CookieJar) ClientOption

func WithTimeout added in v0.1.3

func WithTimeout(timeout time.Duration) ClientOption

func WithTransport added in v0.1.3

func WithTransport(transport http.RoundTripper) ClientOption

type Cookies

type Cookies map[string]string

func (Cookies) Do added in v0.1.3

func (c Cookies) Do(req *Request) error

type Ctx added in v0.1.3

type Ctx struct {
	context.Context
}

func (Ctx) Do added in v0.1.3

func (c Ctx) Do(req *Request) error

type Form added in v0.1.3

type Form map[string]string

func (Form) Do added in v0.1.3

func (f Form) Do(req *Request) error

type Gzip added in v0.1.5

type Gzip struct{}

func (Gzip) Do added in v0.1.5

func (Gzip) Do(req *Request) error
type Header map[string]string

func (Header) Do added in v0.1.3

func (h Header) Do(req *Request) error

type Hook added in v0.1.3

type Hook interface {
	// BeforeProcess Before the HTTP request is executed
	BeforeProcess(req *Request)
	// AfterProcess After the HTTP request is executed
	AfterProcess(req *Request, resp *Response, err error)
}

type Json

type Json map[string]interface{}

func (Json) Do added in v0.1.3

func (j Json) Do(req *Request) error

type Jsons added in v0.1.3

type Jsons []Json

func (Jsons) Do added in v0.1.3

func (j Jsons) Do(req *Request) error

type Params

type Params map[string]string

func (Params) Do added in v0.1.3

func (p Params) Do(req *Request) error

type ReqOption added in v0.1.3

type ReqOption interface {
	Do(req *Request) error
}

type Request added in v0.1.3

type Request struct {
	*http.Request
	// contains filtered or unexported fields
}

func NewRequest added in v0.1.3

func NewRequest(method, url string) (*Request, error)

NewRequest wraps NewRequestWithContext using the background context.

type Response

type Response struct {
	*http.Response
	// contains filtered or unexported fields
}

Response is the wrapper for http.Response

func Delete

func Delete(url string, opts ...ReqOption) (*Response, error)

func Get

func Get(url string, opts ...ReqOption) (*Response, error)
func Head(url string, opts ...ReqOption) (*Response, error)

func NewResponse

func NewResponse(r *http.Response) (*Response, error)

func Patch

func Patch(url string, opts ...ReqOption) (*Response, error)

func Post

func Post(url string, opts ...ReqOption) (*Response, error)

func Put

func Put(url string, opts ...ReqOption) (*Response, error)

func ReqOptions added in v0.1.3

func ReqOptions(url string, opts ...ReqOption) (*Response, error)

func (*Response) Bytes

func (r *Response) Bytes() ([]byte, error)

func (Response) Json

func (r Response) Json(s interface{}) error

Json could parse http json response

func (Response) SaveFile

func (r Response) SaveFile(filename string) error

SaveFile save bytes data to a local file

func (*Response) Text

func (r *Response) Text() string

type Timeout

type Timeout time.Duration

func (Timeout) Do added in v0.1.3

func (t Timeout) Do(req *Request) error

Jump to

Keyboard shortcuts

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