requests

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2024 License: Apache-2.0 Imports: 20 Imported by: 1

README

requests

Install

go get github.com/chyroc/requests

Usage

sample usage

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/chyroc/requests"
)

func Example_Method() {
	r := requests.Get("https://httpbin.org/get")

	r = requests.Post("https://httpbin.org/post")

	r = requests.Delete("https://httpbin.org/delete")

	r = requests.New(http.MethodPut, "https://httpbin.org/put")

	fmt.Println(r.Text().Unpack())
}

func Example_unmarshal() {
	r := requests.Post("https://httpbin.org/post")

	type Response struct {
		// ...
	}

	resp := requests.JSON[Response](r)

	fmt.Println(resp.Unpack())
}

func Example_factory() {
	// I hope to set fixed parameters every time I initiate a request
	// Then, every request created by this factory will not log
	opt := requests.Options(
		requests.WithLogger(requests.DiscardLogger()),
		requests.WithTimeout(time.Second*10),
		requests.WithQuery("query", "value"),
		requests.WithHeader("Auth", "hey"),
	)

	// Send sample request
	r := requests.Get("https://httpbin.org/get", opt...)

	r = requests.Post("https://httpbin.org/get").
		WithLogger(requests.DiscardLogger()).
		WithTimeout(time.Second * 10)
	fmt.Println(r.Text().Unpack())
}

func Example_newSession() {
	session := requests.NewSession("/tmp/requests-session.txt")
	r := session.Get("https://jsonplaceholder.typicode.com/todos/1").
		WithTimeout(time.Second * 10)
	fmt.Println(r.Text().Unpack())
}

Documentation

Overview

Example (Factory)
package main

import (
	"fmt"
	"time"

	"github.com/chyroc/requests"
)

func main() {
	// I hope to set fixed parameters every time I initiate a request
	// Then, every request created by this factory will not log
	opt := requests.Options(
		requests.WithLogger(requests.DiscardLogger()),
		requests.WithTimeout(time.Second*10),
		requests.WithQuery("query", "value"),
		requests.WithHeader("Auth", "hey"),
	)

	// Send sample request
	r := requests.Get("https://httpbin.org/get", opt...)

	r = requests.Post("https://httpbin.org/get").
		WithLogger(requests.DiscardLogger()).
		WithTimeout(time.Second * 10)
	fmt.Println(r.Text().Unpack())
}
Output:

Example (NewSession)
package main

import (
	"fmt"
	"time"

	"github.com/chyroc/requests"
)

func main() {
	session := requests.NewSession("/tmp/requests-session.txt")
	r := session.Get("https://jsonplaceholder.typicode.com/todos/1").
		WithTimeout(time.Second * 10)
	fmt.Println(r.Text().Unpack())
}
Output:

Example (Unmarshal)
package main

import (
	"fmt"

	"github.com/chyroc/anyhow"
	"github.com/chyroc/requests"
)

func main() {
	type Data struct{}

	f := func() (Data, error) {
		type Response struct {
			Code int32
			Data Data
		}
		return anyhow.AndThen11(requests.JSON[Response](requests.Post("https://httpbin.org/post")), func(t1 *Response) anyhow.Result1[Data] {
			if t1.Code != 0 {
				return anyhow.Err1[Data](fmt.Errorf("fail: %d", t1.Code))
			}
			return anyhow.Ok1(t1.Data)
		}).Unpack()
	}
	f()
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func JSON

func JSON[T any](r *Request) Result1[*T]

JSON convert request body to T as json type

Types

type Logger

type Logger interface {
	Info(ctx context.Context, format string, v ...any)
	Error(ctx context.Context, format string, v ...any)
}

func DiscardLogger

func DiscardLogger() Logger

func StdoutLogger

func StdoutLogger() Logger

type Option

type Option func(req *Request)

func Options

func Options(options ...Option) []Option

func WithHeader

func WithHeader(key, val string) Option

func WithHeaders added in v0.1.1

func WithHeaders(kv map[string]string) Option

func WithLogger

func WithLogger(logger Logger) Option

func WithQueries added in v0.1.1

func WithQueries(queries any) Option

func WithQuery

func WithQuery(key, val string) Option

func WithTimeout

func WithTimeout(timeout time.Duration) Option

type Request

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

func Delete

func Delete(url string, options ...Option) *Request

func Get

func Get(url string, options ...Option) *Request

func New

func New(method, url string, options ...Option) *Request

func Patch

func Patch(url string, options ...Option) *Request

func Post

func Post(url string, options ...Option) *Request

func Put

func Put(url string, options ...Option) *Request

func (*Request) Bytes

func (r *Request) Bytes() Result1[[]byte]

Bytes get request body response as []byte

func (*Request) Context

func (r *Request) Context() context.Context

Context request context.Context

func (*Request) CookiesByKey

func (r *Request) CookiesByKey(key string) Result1[[]string]

CookiesByKey get specific http cookie response with key

func (*Request) FullURL

func (r *Request) FullURL() string

FullURL request full url, contain query param

func (*Request) Header

func (r *Request) Header() Result1[http.Header]

Header get http response header

func (*Request) HeaderByKey

func (r *Request) HeaderByKey(key string) Result1[string]

HeaderByKey get specific http header response with key

func (*Request) HeadersByKey

func (r *Request) HeadersByKey(key string) Result1[[]string]

HeadersByKey get specific http header response with key

func (*Request) Map

func (r *Request) Map() Result1[map[string]any]

Map convert request body to map

func (*Request) Method

func (r *Request) Method() string

Method request method

func (*Request) ReqHeader

func (r *Request) ReqHeader() http.Header

ReqHeader request header

func (*Request) Response

func (r *Request) Response() Result1[*http.Response]

Response get http response

func (*Request) SetError

func (r *Request) SetError(err error) *Request

func (*Request) Status

func (r *Request) Status() Result1[int]

Response get http response status

func (*Request) Text

func (r *Request) Text() Result1[string]

Map convert request body to str

func (*Request) Timeout

func (r *Request) Timeout() time.Duration

Timeout request timeout

func (*Request) URL

func (r *Request) URL() string

URL request url

func (*Request) WithBody

func (r *Request) WithBody(body any) *Request

WithBody set request body, support: io.Reader, []byte, string, any(as json format)

func (*Request) WithContext

func (r *Request) WithContext(ctx context.Context) *Request

WithContext setup request context.Context

func (*Request) WithFile

func (r *Request) WithFile(filename string, file io.Reader, fileKey string, params map[string]string) *Request

WithFile set file to body and set some multi-form k-v map

func (*Request) WithForm

func (r *Request) WithForm(body map[string]string) *Request

WithForm set body and set Content-Type to multiform

func (*Request) WithFormURLEncoded

func (r *Request) WithFormURLEncoded(body map[string]string) *Request

WithFormURLEncoded set body and set Content-Type to application/x-www-form-urlencoded

func (*Request) WithHeader

func (r *Request) WithHeader(k, v string) *Request

WithHeader set one header k-v map

func (*Request) WithHeaders

func (r *Request) WithHeaders(kv map[string]string) *Request

WithHeaders set multi header k-v map

func (*Request) WithIgnoreSSL

func (r *Request) WithIgnoreSSL(ignore bool) *Request

WithIgnoreSSL ignore ssl verify

func (*Request) WithJSON

func (r *Request) WithJSON(body any) *Request

WithJSON set body same as WithBody, and set Content-Type to application/json

func (*Request) WithLogger

func (r *Request) WithLogger(logger Logger) *Request

WithLogger set logger

func (*Request) WithQueries added in v0.1.1

func (r *Request) WithQueries(queries any) *Request

WithQueries set multi query k-v

func (*Request) WithQuery

func (r *Request) WithQuery(k, v string) *Request

WithQuery set one query k-v map

func (*Request) WithRedirect

func (r *Request) WithRedirect(redirect bool) *Request

WithRedirect set allow or not-allow redirect with Location header

func (*Request) WithTimeout

func (r *Request) WithTimeout(timeout time.Duration) *Request

WithTimeout setup request timeout

func (*Request) WithURLCookie

func (r *Request) WithURLCookie(uri string) *Request

WithURLCookie set cookie of uri

func (*Request) WithWrapResponse

func (r *Request) WithWrapResponse(f func(resp *http.Response) (*http.Response, error)) *Request

WithWrapResponse set round tripper response wrap

type Session

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

func NewSession

func NewSession(cookieFile string, options ...Option) *Session

same cookie-file has same session instance

func (*Session) CookieFile

func (r *Session) CookieFile() string

func (*Session) Delete

func (r *Session) Delete(url string, options ...Option) *Request

func (*Session) Get

func (r *Session) Get(url string, options ...Option) *Request

func (*Session) Jar

func (r *Session) Jar() http.CookieJar

func (*Session) New

func (r *Session) New(method, url string, options ...Option) *Request

func (*Session) Patch

func (r *Session) Patch(url string, options ...Option) *Request

func (*Session) Post

func (r *Session) Post(url string, options ...Option) *Request

func (*Session) Put

func (r *Session) Put(url string, options ...Option) *Request

Jump to

Keyboard shortcuts

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