fetch

package module
v1.8.1 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2023 License: MIT Imports: 26 Imported by: 65

README

Fetch - HTTP Client

HTTP Client for Go, inspired by the Fetch API, and Axios + Got (Sindre Sorhus).

PkgGoDev Build Status Go Report Card Coverage Status GitHub issues Release

Features

Main API
  • Make HTTP requests
  • Easy JSON Response
  • GZip support
    • Decode GZip response
    • Encode GZip request (Upload File with GZip)
  • HTTP/2 support
  • TLS
    • Custom TLS Ca Certificate (Self signed certificate) Example
      • Custom Client Cert and Key for two-way authentication (Client Cert and Key)
  • Simple Auth Methods
    • Basic Auth
    • Bearer Auth
  • Support cancel (using context)
Timeouts and retries
  • Support timeout
  • Support retry on failure
Progress
  • Support progress and progress events
File upload and download
  • Download files easily
  • Upload files easily
Cache, Proxy and UNIX sockets
WebDAV
  • WebDAV protocol support
Advanced creation
  • Plugin system
  • Middleware system

Installation

To install the package, run:

go get github.com/go-zoox/fetch

Methods

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE
  • HEAD
  • OPTIONS
  • TRACE
  • CONNECT

Getting Started

package main

import (
  "github.com/go-zoox/fetch"
)

func main() {
  response, _ := fetch.Get("https://httpbin.zcorky.com/get")
  url := response.Get("url")
  method := response.Get("method")

  fmt.Println(url, method)
}

Examples

Get
package main

import (
  "github.com/go-zoox/fetch"
)

func main() {
  response, err := fetch.Get("https://httpbin.zcorky.com/get")
  if err != nil {
		panic(err)
	}

  fmt.Println(response.JSON())
}
Post
package main

import (
  "github.com/go-zoox/fetch"
)

func main() {
  response, _ := fetch.Post("https://httpbin.zcorky.com/post", &fetch.Config{
		Body: map[string]interface{}{
			"foo":     "bar",
			"foo2":    "bar2",
			"number":  1,
			"boolean": true,
			"array": []string{
				"foo3",
				"bar3",
			},
			"nest": map[string]string{
				"foo4": "bar4",
			},
		},
	})
	if err != nil {
		panic(err)
	}

  fmt.Println(response.JSON())
}
Put
package main

import (
  "github.com/go-zoox/fetch"
)

func main() {
	response, err := fetch.Put("https://httpbin.zcorky.com/put", &fetch.Config{
		Body: map[string]interface{}{
			"foo":     "bar",
			"foo2":    "bar2",
			"number":  1,
			"boolean": true,
			"array": []string{
				"foo3",
				"bar3",
			},
			"nest": map[string]string{
				"foo4": "bar4",
			},
		},
	})
  if err != nil {
		panic(err)
	}


  fmt.Println(response.JSON())
}
Delete
package main

import (
  "github.com/go-zoox/fetch"
)

func main() {
	response, err := fetch.Delete("https://httpbin.zcorky.com/Delete", &fetch.Config{
		Body: map[string]interface{}{
			"foo":     "bar",
			"foo2":    "bar2",
			"number":  1,
			"boolean": true,
			"array": []string{
				"foo3",
				"bar3",
			},
			"nest": map[string]string{
				"foo4": "bar4",
			},
		},
	})
	if err != nil {
		panic(err)
	}

  fmt.Println(response.JSON())
}
Timeout
package main

import (
  "github.com/go-zoox/fetch"
)

func main() {
  response, err := fetch.Get("https://httpbin.zcorky.com/get", &fetch.Config{
    Timeout: 5 * time.Second,
  })
  if err != nil {
		panic(err)
	}

  fmt.Println(response.JSON())
}
Proxy
package main

import (
  "github.com/go-zoox/fetch"
)

func main() {
  response, err := fetch.Get("https://httpbin.zcorky.com/ip", &fetch.Config{
    Proxy: "http://127.0.0.1:17890",
  })
  if err != nil {
		panic(err)
	}

  fmt.Println(response.JSON())
}
Basic Auth
package main

import (
  "github.com/go-zoox/fetch"
)

func main() {
  response, err := fetch.Get("https://httpbin.zcorky.com/ip", &fetch.Config{
    BasicAuth: &fetch.BasicAuth{
      Username: "foo",
      Password: "bar",
    },
  })
  if err != nil {
		panic(err)
	}

  fmt.Println(response.JSON())
}
Download
package main

import (
  "github.com/go-zoox/fetch"
)

func main() {
	response, err := fetch.Download("https://httpbin.zcorky.com/image", "/tmp/image.webp")
  if err != nil {
		panic(err)
	}
}
Upload
package main

import (
  "github.com/go-zoox/fetch"
)

func main() {
		file, _ := os.Open("go.mod")

	response, err := Upload("https://httpbin.zcorky.com/upload", file)
  if err != nil {
		panic(err)
	}

	fmt.Println(response.JSON())
}
Cancel
package main

import (
  "github.com/go-zoox/fetch"
)

func main() {
	file, _ := os.Open("go.mod")

	ctx, cancel := context.WithCancel(context.Background())

	f := fetch.New()
	f.SetBaseURL("https://httpbin.zcorky.com")
	f.SetURL("/delay/3")
	f.SetContext(ctx)

	go func() {
		_, err := f.Execute()
		fmt.Println(err)
	}()

	cancel()
}

Depencencies

  • gjson - Get JSON Whenever You Need, you don't define type first。

Inspired By

License

GoZoox is released under the MIT License.

Documentation

Index

Constants

View Source
const DELETE = "DELETE"

DELETE is request method DELETE

View Source
const EnvDEBUG = "GO_ZOOX_FETCH_DEBUG"

EnvDEBUG is the DEBUG env name

View Source
const GET = "GET"

GET is request method GET

View Source
const HEAD = "HEAD"

HEAD is request method HEAD

View Source
const PATCH = "PATCH"

PATCH is request method PATCH

View Source
const POST = "POST"

POST is request method POST

View Source
const PUT = "PUT"

PUT is request method PUT

Variables

View Source
var BaseURL = ""

BaseURL is the default base url

View Source
var ErrCannotCopyFile = errors.New("cannot copy file")

ErrCannotCopyFile is the error when the file cannot be copied

View Source
var ErrCannotCreateFormFile = errors.New("cannot create form file")

ErrCannotCreateFormFile is the error when the form file cannot be created

View Source
var ErrCannotCreateRequest = errors.New("cannot create request")

ErrCannotCreateRequest is the error when the request cannot be created

View Source
var ErrCannotSendBodyWithGet = errors.New("cannot send body with GET method")

ErrCannotSendBodyWithGet is the error when the body cannot be sent with GET method

View Source
var ErrCookieEmptyKey = errors.New("empty key")

ErrCookieEmptyKey is the error when the key is empty

View Source
var ErrInvalidBodyMultipart = errors.New("invalid body multipart")

ErrInvalidBodyMultipart is the error when the body is invalid for multipart

View Source
var ErrInvalidContentType = errors.New("invalid content type")

ErrInvalidContentType is the error when the content type is invalid

View Source
var ErrInvalidJSONBody = errors.New("error marshalling body")

ErrInvalidJSONBody is the error when the body is not a valid JSON

View Source
var ErrInvalidMethod = errors.New("invalid method")

ErrInvalidMethod is the error when the method is invalid

View Source
var ErrInvalidURLFormEncodedBody = errors.New("invalid url form encoded body")

ErrInvalidURLFormEncodedBody is the error when the body is invalid for url form encoded

View Source
var ErrReadingResponse = errors.New("error reading response")

ErrReadingResponse is the error when the response cannot be read

View Source
var ErrSendingRequest = errors.New("error sending request")

ErrSendingRequest is the error when the request cannot be sent

View Source
var ErrTooManyArguments = errors.New("too many arguments")

ErrTooManyArguments is the error when the number of arguments is too many

View Source
var ErrorInvalidBody = errors.New("invalid body")

ErrorInvalidBody is the error when the body is invalid

View Source
var METHODS = []string{
	HEAD,
	GET,
	POST,
	PUT,
	DELETE,
	PATCH,
}

METHODS is the list of supported methods

View Source
var Timeout = 60 * time.Second

Timeout is the default timeout

View Source
var UserAgent = fmt.Sprintf("GoFetch/%s (github.com/go-zoox/fetch)", Version)

UserAgent is the default user agent

View Source
var Version = "1.8.1"

Version is the version of this package

Functions

func DefaultUserAgent

func DefaultUserAgent() string

DefaultUserAgent returns the default user agent

func SetBaseURL

func SetBaseURL(url string)

SetBaseURL sets the base url

func SetTimeout

func SetTimeout(timeout time.Duration)

SetTimeout sets the timeout

func SetUserAgent

func SetUserAgent(userAgent string)

SetUserAgent sets the user agent

Types

type BasicAuth added in v1.7.10

type BasicAuth struct {
	Username string
	Password string
}

BasicAuth is the basic auth

type Body added in v1.4.3

type Body interface{}

Body is the body of the request

type Config

type Config struct {
	URL     string
	Method  string
	Headers Headers
	Query   Query
	Params  Params
	Body    Body
	//
	BaseURL string
	Timeout time.Duration
	//
	DownloadFilePath string
	//
	Proxy string
	//
	IsStream bool
	//
	IsSession bool
	//
	HTTP2 bool

	// TLS Ca Cert
	TLSCaCert     []byte
	TLSCaCertFile string
	// TLS Cert
	TLSCert     []byte
	TLSCertFile string
	// TLS Client Private Key
	TLSKey     []byte
	TLSKeyFile string

	// TLSInsecureSkipVerify means ignore verify tls certificate
	//	use carefully, becuase it may cause security problems,
	//		which means maybe server certificate has been hacked
	TLSInsecureSkipVerify bool
	// UnixDomainSocket socket like /var/run/docker.sock
	UnixDomainSocket string
	//
	Context context.Context
	//
	OnProgress OnProgress
	//
	BasicAuth BasicAuth
	//
	Username string
	Password string
}

Config is the configuration for the fetch

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the default config

func (*Config) Clone added in v1.4.0

func (c *Config) Clone() *Config

Clone returns a clone of the config

func (*Config) Merge

func (c *Config) Merge(config *Config)

Merge merges the config with the given config

type DataSource added in v1.1.0

type DataSource interface {
	Get(key string) string
}

DataSource defines the interface for loading data from a data source.

type Fetch

type Fetch struct {
	Errors []error
	// contains filtered or unexported fields
}

Fetch is the Fetch Client

func Create added in v1.4.0

func Create(baseURL string) *Fetch

Create creates a new fetch with base url Specially useful for Client SDK

func New

func New(cfg ...*Config) *Fetch

New creates a fetch client

func Session added in v1.4.0

func Session() *Fetch

Session is remembered between requests

func (*Fetch) Clone

func (f *Fetch) Clone() *Fetch

Clone creates a new fetch

func (*Fetch) Config added in v1.3.0

func (f *Fetch) Config() (*Config, error)

Config returns the config of fetch

func (*Fetch) Delete

func (f *Fetch) Delete(url string, config ...*Config) *Fetch

Delete is http.delete

func (*Fetch) Download added in v1.1.8

func (f *Fetch) Download(url string, filepath string, config ...*Config) *Fetch

Download downloads file by url

func (*Fetch) Execute

func (f *Fetch) Execute() (*Response, error)

Execute executes the request

func (*Fetch) Get

func (f *Fetch) Get(url string, config ...*Config) *Fetch

Get is http.get

func (*Fetch) Head added in v1.1.7

func (f *Fetch) Head(url string, config ...*Config) *Fetch

Head is http.head

func (*Fetch) Patch

func (f *Fetch) Patch(url string, config ...*Config) *Fetch

Patch is http.patch

func (*Fetch) Post

func (f *Fetch) Post(url string, config ...*Config) *Fetch

Post is http.post

func (*Fetch) Put

func (f *Fetch) Put(url string, config ...*Config) *Fetch

Put is http.put

func (*Fetch) Retry added in v1.4.0

func (f *Fetch) Retry(before func(f *Fetch)) (*Response, error)

Retry retries the request

func (*Fetch) Send

func (f *Fetch) Send() (*Response, error)

Send sends the request

func (*Fetch) SetAccept added in v1.4.0

func (f *Fetch) SetAccept(accept string) *Fetch

SetAccept sets the accept header

func (*Fetch) SetAcceptEncoding added in v1.4.0

func (f *Fetch) SetAcceptEncoding(acceptEncoding string) *Fetch

SetAcceptEncoding sets the accept encoding

func (*Fetch) SetAcceptLanguage added in v1.4.0

func (f *Fetch) SetAcceptLanguage(acceptLanguage string) *Fetch

SetAcceptLanguage sets the accept language

func (*Fetch) SetAuthorization added in v1.1.1

func (f *Fetch) SetAuthorization(token string) *Fetch

SetAuthorization sets the authorization token

func (*Fetch) SetBaseURL

func (f *Fetch) SetBaseURL(url string) *Fetch

SetBaseURL sets the base url

func (*Fetch) SetBasicAuth added in v1.1.1

func (f *Fetch) SetBasicAuth(username, password string) *Fetch

SetBasicAuth sets the basic auth username and password

func (*Fetch) SetBearToken added in v1.1.1

func (f *Fetch) SetBearToken(token string) *Fetch

SetBearToken sets the bear token

func (*Fetch) SetBody

func (f *Fetch) SetBody(body Body) *Fetch

SetBody sets the body

func (*Fetch) SetCacheControl added in v1.4.0

func (f *Fetch) SetCacheControl(cacheControl string) *Fetch

SetCacheControl sets the cache control

func (*Fetch) SetConfig

func (f *Fetch) SetConfig(configs ...*Config) *Fetch

SetConfig sets the config of fetch

func (*Fetch) SetContentType added in v1.4.0

func (f *Fetch) SetContentType(contentType string) *Fetch

SetContentType ...

func (*Fetch) SetContext added in v1.5.1

func (f *Fetch) SetContext(ctx context.Context) *Fetch

SetContext sets the context

func (*Fetch) SetCookie added in v1.4.0

func (f *Fetch) SetCookie(key, value string) *Fetch

SetCookie sets the cookie

func (*Fetch) SetDownloadFilePath added in v1.1.8

func (f *Fetch) SetDownloadFilePath(filepath string) *Fetch

SetDownloadFilePath sets the download file path

func (*Fetch) SetHeader

func (f *Fetch) SetHeader(key, value string) *Fetch

SetHeader sets the header key and value

func (*Fetch) SetMethod

func (f *Fetch) SetMethod(method string) *Fetch

SetMethod sets the method

func (*Fetch) SetParam

func (f *Fetch) SetParam(key, value string) *Fetch

SetParam sets the param key and value

func (*Fetch) SetProgressCallback added in v1.5.4

func (f *Fetch) SetProgressCallback(callback func(percent int64, current, total int64)) *Fetch

SetProgressCallback sets the progress callback

func (*Fetch) SetProxy added in v1.2.0

func (f *Fetch) SetProxy(proxy string) *Fetch

SetProxy sets the proxy

	support http, https, socks5
 example:
		http://127.0.0.1:17890
	  https://127.0.0.1:17890
	  socks5://127.0.0.1:17890

func (*Fetch) SetQuery

func (f *Fetch) SetQuery(key, value string) *Fetch

SetQuery sets the query key and value

func (*Fetch) SetReferrer added in v1.4.0

func (f *Fetch) SetReferrer(referrer string) *Fetch

SetReferrer sets the referrer

func (*Fetch) SetTimeout

func (f *Fetch) SetTimeout(timeout time.Duration) *Fetch

SetTimeout sets the timeout

func (*Fetch) SetURL added in v1.2.1

func (f *Fetch) SetURL(url string) *Fetch

SetURL sets the url of fetch

func (*Fetch) SetUserAgent

func (f *Fetch) SetUserAgent(userAgent string) *Fetch

SetUserAgent sets the user agent

func (*Fetch) Stream added in v1.3.4

func (f *Fetch) Stream(url string, config ...*Config) *Fetch

Stream ...

func (*Fetch) Upload added in v1.5.0

func (f *Fetch) Upload(url string, file io.Reader, config ...*Config) *Fetch

Upload upload a file

type Headers added in v1.4.3

type Headers map[string]string

Headers is the headers of the request

func (Headers) Get added in v1.4.3

func (h Headers) Get(key string) string

Get returns the value of the given key

func (Headers) Set added in v1.4.3

func (h Headers) Set(key, value string)

Set sets the value of the given key

type OnProgress added in v1.8.0

type OnProgress func(percent int64, current, total int64)

OnProgress is the progress callback

func (*OnProgress) MarshalJSON added in v1.8.0

func (op *OnProgress) MarshalJSON() ([]byte, error)

MarshalJSON returns the json string

func (*OnProgress) UnmarshalJSON added in v1.8.0

func (op *OnProgress) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals the json string

type Params added in v1.4.3

type Params map[string]string

Params is the params of the request

func (Params) Get added in v1.4.3

func (p Params) Get(key string) string

Get returns the value of the given key

func (Params) Set added in v1.4.3

func (p Params) Set(key, value string)

Set sets the value of the given key

type Progress added in v1.5.4

type Progress struct {
	Reporter func(percent int64, current, total int64)
	Total    int64
	Current  int64
}

Progress is a progress event

func (*Progress) Write added in v1.5.4

func (p *Progress) Write(b []byte) (n int, err error)

Write writes the data to the progress event

type Query added in v1.4.3

type Query map[string]string

Query is the query of the request

func (Query) Get added in v1.4.3

func (q Query) Get(key string) string

Get returns the value of the given key

func (Query) Set added in v1.4.3

func (q Query) Set(key, value string)

Set sets the value of the given key

type Response

type Response struct {
	Status  int
	Headers http.Header
	Body    []byte

	//
	Request *Config
	//
	Stream io.ReadCloser
	// contains filtered or unexported fields
}

Response is the fetch response

func Delete

func Delete(url string, config *Config) (*Response, error)

Delete is a wrapper for the Delete method of the Client

func Download added in v1.1.8

func Download(url string, filepath string, config ...interface{}) (*Response, error)

Download is a wrapper for the Download method of the Client

func Get

func Get(url string, config ...interface{}) (*Response, error)

Get is a wrapper for the Get method of the Client

func Head(url string, config ...interface{}) (*Response, error)

Head is a wrapper for the Head method of the Client

func Patch

func Patch(url string, config *Config) (*Response, error)

Patch is a wrapper for the Patch method of the Client

func Post

func Post(url string, config *Config) (*Response, error)

Post is a wrapper for the Post method of the Client

func Put

func Put(url string, config *Config) (*Response, error)

Put is a wrapper for the Put method of the Client

func Stream added in v1.3.4

func Stream(url string, config ...interface{}) (*Response, error)

Stream is a wrapper for the Stream method of the Client

func Upload added in v1.5.0

func Upload(url string, file io.Reader, config ...interface{}) (*Response, error)

Upload is a wrapper for the Upload method of the Client

func (*Response) AcceptRanges added in v1.4.9

func (r *Response) AcceptRanges() string

AcceptRanges returns x-accept-ranges of the response

func (*Response) ContentEncoding added in v1.4.4

func (r *Response) ContentEncoding() string

ContentEncoding returns content encoding of the response

func (*Response) ContentLanguage added in v1.4.4

func (r *Response) ContentLanguage() string

ContentLanguage returns content language of the response

func (*Response) ContentLength added in v1.4.4

func (r *Response) ContentLength() int

ContentLength returns content length of the response

func (*Response) ContentType added in v1.4.4

func (r *Response) ContentType() string

ContentType returns content type of the response

func (*Response) Error added in v1.3.4

func (r *Response) Error() error

Error returns error with status and response string.

func (*Response) Get

func (r *Response) Get(key string) gjson.Result

Get returns the value of the key

func (*Response) JSON

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

JSON returns the body as json string

func (*Response) Location added in v1.4.4

func (r *Response) Location() string

Location returns location of the response

func (*Response) Ok added in v1.3.3

func (r *Response) Ok() bool

Ok returns true if status code is 2xx

func (*Response) SetCookie added in v1.4.4

func (r *Response) SetCookie() string

SetCookie returns set-cookie of the response

func (*Response) StatusCode added in v1.4.4

func (r *Response) StatusCode() int

StatusCode returns status code of the response

func (*Response) StatusText added in v1.4.4

func (r *Response) StatusText() string

StatusText returns status text of the response

func (*Response) String

func (r *Response) String() string

String returns the body as string

func (*Response) TransferEncoding added in v1.4.4

func (r *Response) TransferEncoding() string

TransferEncoding returns transfer encoding of the response

func (*Response) UnmarshalJSON added in v1.1.4

func (r *Response) UnmarshalJSON(v interface{}) error

UnmarshalJSON unmarshals body to json struct

@TODO bug when lint (go vet) method UnmarshalJSON(v interface{}) error should have signature UnmarshalJSON([]byte) error

func (*Response) UnmarshalYAML added in v1.1.4

func (r *Response) UnmarshalYAML(v interface{}) error

UnmarshalYAML unmarshals body to yaml struct

func (*Response) Value

func (r *Response) Value() gjson.Result

Value returns the body as gjson.Result

func (*Response) XPoweredBy added in v1.4.4

func (r *Response) XPoweredBy() string

XPoweredBy returns x-powered-by of the response

func (*Response) XRequestID added in v1.4.4

func (r *Response) XRequestID() string

XRequestID returns x-request-id of the response

Jump to

Keyboard shortcuts

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