Documentation
¶
Overview ¶
Package requests is a minimal, atomic and expressive way of making HTTP requests. It is inspired partly by the HTTP request libraries in other dynamic languages like Python and Javascript. It is safe for all rodents, not just Gophers.
Requests is built as a convenient, expressive API around Go's standard http package. With special Request and Response types to help facilitate and streamline RESTful tasks.
To send a common GET request just like you'd do with `http.Get`.
import ( "github.com/jochasinga/requests" ) func main() { resp, err := requests.Get("http://httpbin.org/get") fmt.Println(resp.StatusCode) // 200 }
To send additional data, such as a query parameter, basic authorization header, or content type, just pass in functional options:
addFoo := func(r *Request) { r.Params.Add("foo", "bar") } addAuth := func(r *Request) { r.SetBasicAuth("user", "pass") } addMime := func(r *Request) { r.Header.Add("content-type", "application/json") } resp, err := requests.Get("http://httpbin.org/get", addFoo, addAuth, addMime) // Or everything goes into one functional option opts := func(r *Request) { r.Params.Add("foo", "bar") r.SetBasicAuth("user", "pass") r.Header.Add("content-type", "application/json") } resp, err := requests.Get("http://httpbin.org/get", opts)
The data can be a map or struct (anything JSON-marshalable).
data1 := map[string][]string{"foo": []string{"bar", "baz"}} data2 := struct { Foo []string `json:"foo"` }{[]string{"bar", "baz"}} data := map[string][]interface{}{ "combined": {data1, data2}, } res, err := requests.Post("http://httpbin.org/post", "application/json", data)
You can asynchronously wait on a GET response with `GetAsync`.
timeout := time.Duration(1) * time.Second resChan, _ := requests.GetAsync("http://httpbin.org/get", nil, nil, timeout) // Do some other things res := <-resChan fmt.Println(res.StatusCode) // 200
The response returned has the type *requests.Response which embeds *http.Response type to provide more buffer-like methods such as Len(), String(), Bytes(), and JSON().
// Len() returns the body's length. var len int = res.Len() // String() returns the body as a string. var text string = res.String() // Bytes() returns the body as bytes. var content []byte = res.Bytes() // JSON(), like Bytes() but returns an empty `[]byte` unless `Content-Type` // is set to `application/json` in the response's header. var jsn []byte = res.JSON()
These special methods use bytes.Buffer under the hood, thus unread portions of data are returned. Make sure not to read from the response's body beforehand.
Requests is an ongoing project. Any contribution is whole-heartedly welcomed.
Package requests provide useful and declarative methods for RESTful HTTP requests.
Package requests provide useful and declarative methods for RESTful HTTP requests.
Index ¶
- func GetAsync(urlStr string, options ...func(*Request)) (<-chan *Response, error)
- func PostAsync(urlStr, bodyType string, body io.Reader, options ...func(*Request)) (<-chan *Response, error)
- type HTTPRequest
- type HTTPResponse
- type Pool
- type Request
- type Response
- func Delete(urlStr string, options ...func(*Request)) (*Response, error)
- func Get(urlStr string, options ...func(*Request)) (*Response, error)
- func Head(urlStr string, options ...func(*Request)) (*Response, error)
- func Options(urlStr string) (*Response, error)
- func Patch(urlStr, bodyType string, body io.Reader, options ...func(*Request)) (*Response, error)
- func Post(urlStr, bodyType string, body io.Reader, options ...func(*Request)) (*Response, error)
- func PostJSON(urlStr string, body interface{}, options ...func(*Request)) (*Response, error)
- func Put(urlStr, bodyType string, body io.Reader, options ...func(*Request)) (*Response, error)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetAsync ¶
GetAsync sends a HTTP GET request to the provided URL and returns a <-chan *http.Response immediately.
timeout := func(r *request.Request) { r.Timeout = time.Duration(10) * time.Second } rc, err := requests.GetAsync("http://httpbin.org/get", timeout) if err != nil { panic(err) } resp := <-rc if resp.Error != nil { panic(resp.Error) } fmt.Println(resp.String())
func PostAsync ¶
func PostAsync(urlStr, bodyType string, body io.Reader, options ...func(*Request)) (<-chan *Response, error)
PostAsync sends a HTTP POST request to the provided URL, body type, and body, and returns a <-chan *http.Response immediately.
redirect := func(r *requests.Request) { r.CheckRedirect = redirectPolicyFunc }
resp, err := requests.PostAsync("https://httpbin.org/post", "image/png", &buf, redirect)
if err != nil { panic(err) }
resp := <-rc
if resp.Error != nil { panic(resp.Error) }
fmt.Println(resp.String())
Types ¶
type HTTPRequest ¶
type HTTPRequest interface { AddCookie(*http.Cookie) BasicAuth() (string, string, bool) Cookie(string) (*http.Cookie, error) Cookies() []*http.Cookie FormFile(string) (multipart.File, *multipart.FileHeader, error) FormValue(string) string MultipartReader() (*multipart.Reader, error) ParseForm() error ParseMultipartForm(int64) error PostFormValue(string) string ProtoAtLeast(int, int) bool Referer() string SetBasicAuth(string, string) UserAgent() string Write(io.Writer) error WriteProxy(io.Writer) error }
HTTPRequest is for future uses.
type HTTPResponse ¶
type HTTPResponse interface { Cookies() []*http.Cookie Location() (*url.URL, error) ProtoAtLeast(major, minor int) bool Write(w io.Writer) error Bytes() []byte String() string JSON() []byte Len() int }
HTTPResponse is meant for future use for the time being.
type Pool ¶
Pool represents a variable-sized bufferred channel of type *Response which collects results from each request in a goroutine.
type Request ¶
type Request struct { // "Inherite" both http.Request and http.Client *http.Request *http.Client *http.Transport // Params is an alias used to add query parameters to // the request through functional options. // Values in Params have higher precedence over the // query string in the initial URL. Params url.Values }
Request is a hybrid descendant of http.Request and http.Client. It is used as an argument to the functional options.
type Response ¶
Response is a *http.Response and implements HTTPResponse.
func Get ¶
Get sends a HTTP GET request to the provided url with the functional options to add query paramaters, headers, timeout, etc.
addMimeType := func(r *Request) { r.Header.Add("content-type", "application/json") } resp, err := requests.Get("http://httpbin.org/get", addMimeType) if err != nil { panic(err) } fmt.Println(resp.StatusCode)
func Head ¶
Head sends a HTTP HEAD request to the provided url with the functional options to add query paramaters, headers, timeout, etc.
func Options ¶
Options sends a rarely-used HTTP OPTIONS request to the provided URL. Options only allows one parameter--the destination URL string.
func Patch ¶
Patch sends a HTTP PATCH request to the provided URL with optional body to modify data.
func Post ¶
Post sends a HTTP POST request to the provided URL, and encode the data according to the appropriate bodyType.
redirect := func(r *requests.Request) { r.CheckRedirect = redirectPolicyFunc }
resp, err := requests.Post("https://httpbin.org/post", "image/png", &buf, redirect)
if err != nil { panic(err) }
fmt.Println(resp.JSON())
func PostJSON ¶
PostJSON aka UnsafePost! It marshals your data as JSON and set the bodyType to "application/json" automatically.
redirect := func(r *requests.Request) { r.CheckRedirect = redirectPolicyFunc }
first := map[string][]string{"foo": []string{"bar", "baz"}} second := struct {Foo []string `json:"foo"`}{[]string{"bar", "baz"}} payload := map[string][]interface{}{"twins": {first, second}}
resp, err := requests.PostJSON("https://httpbin.org/post", payload, redirect)
if err != nil { panic(err) }
fmt.Println(resp.StatusCode)
func (*Response) Bytes ¶
Bytes returns the response's Body as []byte. Any errors reading from the body is ignored for convenience.
func (*Response) ContentType ¶
ContentType is an alias for Response.Header.Get("content-type"), but filtered through mime.ParseMediaType to rid of extra arguments such as encoding.
func (*Response) JSON ¶
JSON returns the response's body as []byte if Content-Type is in the header contains "application/json".