requests

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2023 License: BSD-2-Clause Imports: 10 Imported by: 2

README

requests

Build Status

HTTP for Gophers.

Roadmap

requests temporarily uses the net/http package, but plans to move to its own HTTP/1.1 and HTTP/2.0 client.

  • HTTP/1.1 and HTTP/2.0 support
  • RFC 2068 proxy support
  • SOCKS4/5 proxy support

Documentation

Index

Examples

Constants

View Source
const (
	INFO_CONTINUE           = 100
	INFO_SWITCHING_PROTOCOL = 101
	INFO_PROCESSING         = 102

	SUCCESS_OK                = 200
	SUCCESS_CREATED           = 201
	SUCCESS_ACCEPTED          = 202
	SUCCESS_NON_AUTHORITATIVE = 203
	SUCCESS_NO_CONTENT        = 204
	SUCCESS_RESET_CONTENT     = 205
	SUCCESS_PARTIAL_CONTENT   = 206
	SUCCESS_MULTI_STATUS      = 207

	REDIRECTION_MULTIPLE_CHOICES   = 300
	REDIRECTION_MOVED_PERMANENTLY  = 301
	REDIRECTION_MOVED_TEMPORARILY  = 302
	REDIRECTION_SEE_OTHER          = 303
	REDIRECTION_NOT_MODIFIED       = 304
	REDIRECTION_USE_PROXY          = 305
	REDIRECTION_TEMPORARY_REDIRECT = 307

	CLIENT_ERROR_BAD_REQUEST                     = 400
	CLIENT_ERROR_UNAUTHORIZED                    = 401
	CLIENT_ERROR_PAYMENT_REQUIRED                = 402
	CLIENT_ERROR_FORBIDDEN                       = 403
	CLIENT_ERROR_NOT_FOUND                       = 404
	CLIENT_ERROR_METHOD_NOT_ALLOWED              = 405
	CLIENT_ERROR_NOT_ACCEPTABLE                  = 406
	CLIENT_ERROR_PROXY_AUTHENTIFICATION_REQUIRED = 407
	CLIENT_ERROR_REQUEST_TIMEOUT                 = 408
	CLIENT_ERROR_CONFLICT                        = 409
	CLIENT_ERROR_GONE                            = 410
	CLIENT_ERROR_LENGTH_REQUIRED                 = 411
	CLIENT_ERROR_PRECONDITION_FAILED             = 412
	CLIENT_ERROR_REQUEST_ENTITY_TOO_LARGE        = 413
	CLIENT_ERROR_REQUEST_URI_TOO_LONG            = 414
	CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE          = 415
	CLIENT_ERROR_REQUESTED_RANGE_NOT_SATISFIABLE = 416
	CLIENT_ERROR_EXPECTATION_FAILED              = 417
	CLIENT_ERROR_UNPROCESSABLE_ENTITY            = 422
	CLIENT_ERROR_LOCKED                          = 423
	CLIENT_ERROR_FAILED_DEPENDENCY               = 424

	SERVER_ERROR_INTERNAL                   = 500
	SERVER_ERROR_NOT_IMPLEMENTED            = 501
	SERVER_ERROR_BAD_GATEWAY                = 502
	SERVER_ERROR_SERVICE_UNAVAILABLE        = 503
	SERVER_ERROR_GATEWAY_TIMEOUT            = 504
	SERVER_ERROR_HTTP_VERSION_NOT_SUPPORTED = 505
	SERVER_ERROR_INSUFFICIENT_STORAGE       = 507
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Body

type Body struct {
	io.ReadCloser
	// contains filtered or unexported fields
}

func (*Body) Content

func (b *Body) Content() string

Content returns the bosy of the response in it's raw sting format

func (*Body) JSON

func (b *Body) JSON(v interface{}) error

JSON decodes the next JSON encoded object in the body to v.

Example
package main

import (
	"fmt"
	"log"

	"github.com/kyliecat/requests"
)

func main() {
	var c requests.Client

	resp, err := c.Get("https://frinkiac.com/api/search?q=burn+that+seat")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Close()

	if !resp.IsSuccess() {
		log.Fatalf("%s: expected 200, got %v", resp.Request.URL, resp.Status)
	}

	var results []struct {
		Id        int    `json:"Id"`
		Episode   string `json:"Episode"`
		Timestamp int    `json:"Timestamp"`
	}

	err = resp.JSON(&results)
	fmt.Printf("%#v\n%v", results, err)
}
Output:

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a HTTP Client.

func NewClient

func NewClient(opts ...ClientOptionFunc) *Client

NewClient returns a `Client` struct. If no arguments are passed a default HTTP client is used. A custom HTTP client can also be passed in via a functional parameter.

func (*Client) Delete

func (c *Client) Delete(url string, options ...RequestOptionFunc) (*Response, error)

func (*Client) Get

func (c *Client) Get(url string, options ...RequestOptionFunc) (*Response, error)

Get issues a GET to the specified URL.

Example
package main

import (
	"fmt"
	"log"

	"github.com/kyliecat/requests"
)

func main() {
	var c requests.Client

	resp, err := c.Get("https://www.example.com")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(resp.Request.Method, resp.Request.URL, resp.Status.Code)
}
Output:

func (*Client) Head

func (c *Client) Head(url string, options ...RequestOptionFunc) (*Response, error)

func (*Client) Patch added in v1.1.1

func (c *Client) Patch(url string, body io.Reader, options ...RequestOptionFunc) (*Response, error)

func (*Client) Post

func (c *Client) Post(url string, body io.Reader, options ...RequestOptionFunc) (*Response, error)

Post issues a POST request to the specified URL.

Example
package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/kyliecat/requests"
)

func main() {
	var c requests.Client

	body := strings.NewReader("Hello there!")
	resp, err := c.Post("https://www.example.com", body, requests.WithHeader("Content-Type", "application/x-www-form-urlencoded"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(resp.Request.Method, resp.Request.URL, resp.Status.Code)
}
Output:

func (*Client) Put

func (c *Client) Put(url string, body io.Reader, options ...RequestOptionFunc) (*Response, error)

func (*Client) Trace

func (c *Client) Trace(url string, options ...RequestOptionFunc) (*Response, error)

type ClientOptionFunc

type ClientOptionFunc func(*Client)

func CustomClient

func CustomClient(c HTTPClient) ClientOptionFunc

type HTTPClient

type HTTPClient interface {
	Do(r *http.Request) (*http.Response, error)
}
type Header struct {
	Key    string
	Values []string
}

Header is a HTTP header.

type Request

type Request struct {
	Method  string
	URL     string
	Headers []Header
	Body    io.Reader
	// QueryParams is a map of query parameters. Uses url.Values
	QueryParams url.Values
	// Fragment is the bit after a #
	Fragment string
	// User info
	User string
}

Request is a HTTP request.

func (Request) GetUrl

func (r Request) GetUrl() string

GetUrl constructs the final URL from the components on the `Request` struct.

type RequestOptionFunc

type RequestOptionFunc func(*Request) error

func WithBasicAuth

func WithBasicAuth(token string) RequestOptionFunc

WithBasicAuth attaches an Authorization header to the `Request` struct that uses basic auth.

func WithBearerToken

func WithBearerToken(token string) RequestOptionFunc

WithBearerToken attaches an Authorization header to the `Request` struct that uses a bearer token.

func WithHeader

func WithHeader(key, value string) RequestOptionFunc

WithHeader applies the header to the request.

func WithQueryParam

func WithQueryParam(key string, values ...string) RequestOptionFunc

WithQueryParam adds a key, value pair to the `QueryParam` struct.

func WithQueryParams

func WithQueryParams(params url.Values) RequestOptionFunc

WithQueryParams sets the `QueryParams` field on the `Request` struct.

type Response

type Response struct {
	*Request
	Status
	Headers []Header
	Body
}

Response is a HTTP response.

func Delete

func Delete(url string, options ...RequestOptionFunc) (*Response, error)

func Get

func Get(url string, options ...RequestOptionFunc) (*Response, error)

Get issues a GET to the specified URL.

func Head(url string, options ...RequestOptionFunc) (*Response, error)

func Patch added in v1.1.1

func Patch(url string, body io.Reader, options ...RequestOptionFunc) (*Response, error)

func Post

func Post(url string, body io.Reader, options ...RequestOptionFunc) (*Response, error)

Post issues a POST request to the specified URL.

func Put

func Put(url string, body io.Reader, options ...RequestOptionFunc) (*Response, error)

func Trace

func Trace(url string, options ...RequestOptionFunc) (*Response, error)

func (*Response) Header

func (r *Response) Header(key string) string

Header returns the canonicalised version of a response header as a string If there is no key present in the response the empty string is returned. If multiple headers are present, they are canonicalised into as single string by joining them with a comma. See RFC 2616 § 4.2.

Example
package main

import (
	"fmt"

	"github.com/kyliecat/requests"
)

var response = requests.Response{
	Headers: []requests.Header{
		{Key: "Server", Values: []string{"nginx/1.2.1"}},
		{Key: "Connection", Values: []string{"keep-alive"}},
		{Key: "Content-Type", Values: []string{"text/html; charset=UTF-8"}},
	},
}

func main() {
	fmt.Println(response.Header("Server"))
	fmt.Println(response.Header("Content-Type"))

}
Output:

nginx/1.2.1
text/html; charset=UTF-8

type Status

type Status struct {
	Code   int
	Reason string
}

Status is a HTTP reponse status.

func (Status) IsClientError

func (s Status) IsClientError() bool

func (Status) IsError

func (s Status) IsError() bool

func (Status) IsInformational

func (s Status) IsInformational() bool

func (Status) IsRedirect

func (s Status) IsRedirect() bool

func (Status) IsServerError

func (s Status) IsServerError() bool

func (Status) IsSuccess

func (s Status) IsSuccess() bool

func (*Status) String

func (s *Status) String() string

Directories

Path Synopsis
examples
get

Jump to

Keyboard shortcuts

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