requests

package module
v0.0.0-...-85ecc89 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2022 License: MIT Imports: 15 Imported by: 0

README

Requests

Build Status Go Report Card codecov

A "Requests" style HTTP client for golang

Install

go get -u github.com/correiaa/requests

Example

var (
	timeout     = time.Second * 3
	url         = "http://example.com"
	queryParams = map[string]string{"foo": "bar"}
	body        = map[string]interface{}{"a": "b", "nums": []int{1, 2, 3}}
)

// Do `curl --connect-timeout 3 -d '{"a": "b", "num": [1, 2, 3]}' -H 'Content-Type: application/json' http://example.com?foo=bar`

// With net/http
func UseNetHttp() map[string]interface{} {
	ctx, _ := context.WithTimeout(context.Background(), timeout)
	buf := new(bytes.Buffer)
	if err := json.NewEncoder(buf).Encode(body); err != nil {
		log.Panic(err)
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, buf)
	if err != nil {
		log.Panic(err)
	}
	req.Header.Set("Content-Type", "application/json")
	value := urlPkg.Values{}
	for k, v := range queryParams {
		value.Set(k, v)
	}
	req.URL.RawQuery = value.Encode()
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Panic(err)
	}
	defer resp.Body.Close()
	data := map[string]interface{}{}
	if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
		log.Panic(err)
	}
	return data
}

// With Requests
func UseRequests() map[string]interface{} {
	resp, err := requests.Post(url,
		requests.Timeout(timeout),
		requests.Queries(queryParams),
		requests.JSON(body),
	)
	if err != nil {
		log.Panic(err)
	}
	data := map[string]interface{}{}
	if err := resp.JSON(&data); err != nil {
		log.Panic(err)
	}
	return data
}

Documentation

Index

Constants

View Source
const (
	HeaderContentType   = "Content-Type"
	HeaderUserAgent     = "User-Agent"
	HeaderReferer       = "Referer"
	HeaderAuthorization = "Authorization"
)

Common header.

View Source
const (
	ContentTypeJSON = "application/json"
	ContentTypeForm = "application/x-www-form-urlencoded"
)

Common content type.

Variables

View Source
var DefaultSession = NewSession(http.DefaultClient)

DefaultSession is a wrapper of http.DefaultClient.

Functions

func NewRequest

func NewRequest(method, url string, opts ...RequestOption) (*http.Request, error)

NewRequest return a new *http.Request

func NewRequestWithContext

func NewRequestWithContext(ctx context.Context, method, url string, opts ...RequestOption) (*http.Request, error)

NewRequestWithContext return a new *http.Request

Types

type RequestOption

type RequestOption func(o *RequestOptions)

RequestOption is used to update the fields in RequestOptions.

func Authorization

func Authorization(a string) RequestOption

Authorization sets the request's Authorization header.

func BasicAuth

func BasicAuth(username, password string) RequestOption

BasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.

func Body

func Body(r io.Reader) RequestOption

Body sets the request's body.

func ContentType

func ContentType(ct string) RequestOption

ContentType sets the request's ContentType header.

func Cookie(k, v string) RequestOption

Cookie sets the request's cookie.

func Cookies

func Cookies(m map[string]string, replace ...bool) RequestOption

Cookies sets the request's cookies, if the replace flag is true, the existing cookies will be removed.

func Deadline

func Deadline(t time.Time) RequestOption

Deadline set the deadline of this request.

func File

func File(fieldName string, file *os.File) RequestOption

File build the body for a multipart/form-data request.

func FileFromReader

func FileFromReader(fieldName, fileName string, r io.Reader) RequestOption

FileFromReader build the body for a multipart/form-data request.

func Form

func Form(m map[string]string) RequestOption

Form sets m as form format of request's body. ContentType will set to ContentTypeForm.

func Header(k string, v interface{}) RequestOption

Header sets the request's header, v can be a string, fmt.Stringer or nil, when v is nil this header will be removed.

func Headers

func Headers(m map[string]interface{}, replace ...bool) RequestOption

Headers sets the request's headers, value of map be a string, fmt.Stringer or nil, when v is nil this header will be removed. If the replace flag is true, the existing header will be removed.

func JSON

func JSON(i interface{}) RequestOption

JSON marshal i to JSON format and sets it to request's body. ContentType will set to ContentTypeJSON.

func MultipartField

func MultipartField(fieldName string, r io.Reader) RequestOption

MultipartField build the body for a multipart/form-data request.

func MultipartFieldBytes

func MultipartFieldBytes(fieldName string, value []byte) RequestOption

MultipartFieldBytes build the body for a multipart/form-data request.

func MultipartFieldString

func MultipartFieldString(fieldName, value string) RequestOption

MultipartFieldString build the body for a multipart/form-data request.

func Queries

func Queries(m map[string]string, replace ...bool) RequestOption

Queries sets the request's queries.

func QueriesFromValue

func QueriesFromValue(v url.Values) RequestOption

QueriesFromValue sets the request's queries.

func Query

func Query(k, v string) RequestOption

Query sets the request's query.

func Referer

func Referer(r string) RequestOption

Referer sets the request's Referer header.

func Timeout

func Timeout(d time.Duration) RequestOption

Timeout set the timeout of this request.

func UserAgent

func UserAgent(ua string) RequestOption

UserAgent sets the request's UserAgent header.

type RequestOptions

type RequestOptions struct {
	Headers  map[string]interface{}
	Queries  url.Values
	Cookies  map[string]string
	Body     io.Reader
	Deadline time.Time

	Err error
	// contains filtered or unexported fields
}

RequestOptions is a collection of request options.

func NewOptions

func NewOptions() *RequestOptions

NewOptions return a new *RequestOptions.

type Response

type Response struct {
	*http.Response
}

Response is wrapper of *http.Response.

func Connect

func Connect(url string, opts ...RequestOption) (*Response, error)

Connect sends a CONNECT request.

func Delete

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

Delete sends a DELETE request.

func Get

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

Get sends a GET request.

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

Head sends a HEAT request.

func NewResponse

func NewResponse(r *http.Response) *Response

NewResponse return a new *Response.

func Options

func Options(url string, opts ...RequestOption) (*Response, error)

Options sends a OPTIONS request.

func Patch

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

Patch sends a PATCH request.

func Post

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

Post sends a POST request.

func Put

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

Put sends a PUT request.

func Request

func Request(method, url string, opts ...RequestOption) (*Response, error)

Request sends an HTTP request and returns an HTTP response.

func Trace

func Trace(url string, opts ...RequestOption) (*Response, error)

Trace sends a TRACE request.

func (*Response) Bytes

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

Bytes return the response`s body as []byte.

func (*Response) JSON

func (r *Response) JSON(i interface{}) error

JSON unmarshal the response`s body as JSON.

func (*Response) StdResponse

func (r *Response) StdResponse() *http.Response

StdResponse return a unwrapped *http.Response.

func (*Response) Text

func (r *Response) Text() (string, error)

Text return the response`s body as string.

type Session

type Session struct {
	*http.Client
}

Session is a wrapper of *http.Client.

func NewSession

func NewSession(c *http.Client) *Session

NewSession return a new *Session

func (*Session) Connect

func (s *Session) Connect(url string, opts ...RequestOption) (*Response, error)

Connect sends a CONNECT request.

func (*Session) Delete

func (s *Session) Delete(url string, opts ...RequestOption) (*Response, error)

Delete sends a DELETE request.

func (*Session) Do

func (s *Session) Do(r *http.Request) (*Response, error)

Do sends an HTTP request and returns an HTTP response.

func (*Session) Get

func (s *Session) Get(url string, opts ...RequestOption) (*Response, error)

Get sends a GET request.

func (*Session) Head

func (s *Session) Head(url string, opts ...RequestOption) (*Response, error)

Head sends a HEAT request.

func (*Session) Options

func (s *Session) Options(url string, opts ...RequestOption) (*Response, error)

Options sends a OPTIONS request.

func (*Session) Patch

func (s *Session) Patch(url string, opts ...RequestOption) (*Response, error)

Patch sends a PATCH request.

func (*Session) Post

func (s *Session) Post(url string, opts ...RequestOption) (*Response, error)

Post sends a POST request.

func (*Session) Put

func (s *Session) Put(url string, opts ...RequestOption) (*Response, error)

Put sends a PUT request.

func (*Session) Request

func (s *Session) Request(method, url string, opts ...RequestOption) (*Response, error)

Request sends an HTTP request and returns an HTTP response.

func (*Session) Trace

func (s *Session) Trace(url string, opts ...RequestOption) (*Response, error)

Trace sends a TRACE request.

Jump to

Keyboard shortcuts

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