grequest

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2025 License: MIT Imports: 18 Imported by: 0

README

logo

A simple and lightweight HTTP client for Go, inspired by Requests (Python) and Guzzle (PHP).

Grequests provides a declarative, chainable API to streamline HTTP requests in Go, supporting JSON manipulation, form submissions, cookies, file handling, authentication, and proxy configuration—all while remaining lightweight and dependency-free.


Features

  • Lightweight & Efficient: No third-party dependencies, built directly on net/http.
  • Flexible Request Handling: Supports GET, POST, PUT, DELETE, and other HTTP methods.
  • JSON Parsing: Convert responses into Go structs or string maps.
  • Header & Cookie Management: Easily set, retrieve, and persist headers and cookies.
  • File Handling: Upload and download files seamlessly.
  • Authentication: Supports Basic, Bearer, and custom token authentication.
  • Proxy Support: Configure custom proxy servers for HTTP requests.

Installation

Install Grequests using Go modules:

go get github.com/lib4u/grequest

Or build from source:

git clone https://github.com/lib4u/grequest.git
cd grequest
go build -o grequest ./
./grequest --version

Usage

Basic GET Request

req := app.Get("https://jsonplaceholder.typicode.com/todos/1").Do()
fmt.Println(req.Body().GetStrings())

Parsing JSON Response

type Todo struct {
    UserID    int    `json:"userId"`
    ID        int    `json:"id"`
    Title     string `json:"title"`
    Completed bool   `json:"completed"`
}

var todo Todo
req := app.Get("https://jsonplaceholder.typicode.com/todos/1").Do()
err := req.Body().GetWithJsonStruct(&todo)
if err != nil {
    fmt.Println("Error decoding JSON")
}
fmt.Println(todo.Title)

POST Request with JSON Payload

data := LoginRequest{
    Username: "example",
    Password: "12345",
}
req := app.Post("https://example.site/login").Body().SetJson(data).Do()
fmt.Println(req.Status().GetCode())

Downloading a File

app.Get("https://example.com/image.png").Do().Body().SaveFile()

Multipart Form Submission

req := app.Post("https://example.site/form/")
req.Header().Set("Client", "number_1")
form := req.FormData().WithMultipart()
form.AddField("first_name", "John")
form.AddFile("photo", "my_photo.png")
form.Push()
req.Do()

Authenticated Requests

// Basic Authentication
app.Post("https://example.site/secret").Auth().SetBasic("user", "password").Do()

// Bearer Token Authentication
app.Post("https://example.site/secret").Auth().SetBearer("myToken").Do()

// Custom Token Authentication
app.Post("https://example.site/secret").Auth().SetToken("Token", "myToken").Do()

// Custom Header Authentication
app.Post("https://example.site/secret").Auth().SetHeader("JSESSIONID", "12345").Do()
//Save cookie to file 
//By default this saved in  cookies/example.site/cookies.json
req := app.Post("https://example.site/cookies")
req.Cookie().Save()

// Load saved cookies form cookies/example.site/cookies.json
reqWithCookie := app.Post("https://example.site/cookies")
reqWithCookie.Cookie().Load()
reqWithCookie.Do()

// Clear cookies
reqWithCookie.Cookie().Clear()

Contributing

  1. Fork the repository and clone it locally.
  2. Create a new branch (git checkout -b feature/branch-name).
  3. Make your changes and commit (git commit -m "Description of changes").
  4. Push your changes and create a pull request.

License

Grequests is licensed under the MIT License. See the LICENSE file for details.

For more details, visit the GitHub repository.


Documentation

Index

Constants

View Source
const (
	MethodGet     = "GET"
	MethodHead    = "HEAD"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodPatch   = "PATCH" // RFC 5789
	MethodDelete  = "DELETE"
	MethodConnect = "CONNECT"
	MethodOptions = "OPTIONS"
	MethodTrace   = "TRACE"
)

Variables

View Source
var (

	// Errors
	ErrInvalidHost             = errors.New("Invalid Host Request")
	ErrInvalidURL              = errors.New("Invalid URL")
	ErrInvalidRedirectLocation = errors.New("Invalid Redirect Location")
	ErrTooManyRedirection      = errors.New("Too many Redirect")
	ErrTooManyRetry            = errors.New("Too many Retry")
)

Functions

This section is empty.

Types

type Auth

type Auth struct {
	Client *HTTPClient
}

func (*Auth) SetBasic

func (c *Auth) SetBasic(user, pass string) *HTTPClient

Sets basic auth in request

func (*Auth) SetBearer

func (c *Auth) SetBearer(token string) *HTTPClient

Sets bearer token in header request

func (*Auth) SetToken

func (c *Auth) SetToken(token string) *HTTPClient

Sets custom auth token in header request

type BasicAuth

type BasicAuth struct {
	User string
	Pass string
}

type Body

type Body struct {
	Client *HTTPClient
	// contains filtered or unexported fields
}

func (*Body) GetBytes

func (c *Body) GetBytes() []byte

Gets response body and return in bytes

func (*Body) GetRaw

func (c *Body) GetRaw() io.Reader

Gets raw io.ReadCloser from body

func (*Body) GetStrings

func (c *Body) GetStrings() string

Gets response body and return as string

func (*Body) GetWithJson

func (c *Body) GetWithJson() (interface{}, error)

Gets response body and return as interface map array

func (*Body) GetWithJsonStruct

func (c *Body) GetWithJsonStruct(target interface{}) error

Gets response body and make to struct

func (*Body) Path

func (c *Body) Path(path string) *Body

Sets path for save

func (*Body) SaveFile

func (c *Body) SaveFile() *Body

Save response body to file

func (*Body) Set

func (c *Body) Set(body io.Reader) *HTTPClient

Sets the request body with io.Reader

func (*Body) SetByte

func (c *Body) SetByte(body []byte) *HTTPClient

Sets the request body with bytes

func (*Body) SetJson

func (c *Body) SetJson(data interface{}) *HTTPClient

Sets the request body with json

func (*Body) SetString

func (c *Body) SetString(body string) *HTTPClient

Sets the request body with only string

func (*Body) ToFile

func (c *Body) ToFile(fileName string)

Save response body to file

type ContentType

type ContentType struct {
	Client *HTTPClient
}

func (*ContentType) Get

func (c *ContentType) Get() string

Gets content type fron response headers and return as string

func (*ContentType) Set

func (c *ContentType) Set(value string) *HTTPClient

Sets content type in request header

func (*ContentType) SetFormUrlencoded

func (c *ContentType) SetFormUrlencoded() *HTTPClient

Sets content type in request header

func (*ContentType) SetMultipartFormData

func (c *ContentType) SetMultipartFormData() *HTTPClient

Sets content type in request header

type Cookie struct {
	Client *HTTPClient
	// contains filtered or unexported fields
}

func (*Cookie) Get

func (c *Cookie) Get() []*http.Cookie

Gets cookies as *http.Cookie

func (*Cookie) Load

func (c *Cookie) Load() *Cookie

func (*Cookie) Path

func (c *Cookie) Path(path string) *Cookie

Sets path for save

func (*Cookie) Save

func (c *Cookie) Save() *Cookie

Save cookies to file for next requests by default saves to the cookies/domainname directory

func (*Cookie) SetCookieJar

func (c *Cookie) SetCookieJar(jar *cookiejar.Jar) *HTTPClient

func (*Cookie) SetCookies

func (c *Cookie) SetCookies(cookies []*http.Cookie) *HTTPClient

Sets cookies as *http.Cookie

func (*Cookie) SetString

func (c *Cookie) SetString(cookie string) *HTTPClient

Sets cookies as string ex: name=xxxx; count=x

type FormData

type FormData struct {
	Client *HTTPClient
	// contains filtered or unexported fields
}

func (*FormData) AddField

func (c *FormData) AddField(key, value string) *FormData

Sets form data field

func (*FormData) AddFile

func (c *FormData) AddFile(key, path string) *FormData

Attach file to request

func (*FormData) Push

func (c *FormData) Push() *HTTPClient

Push form fields

func (*FormData) SetFieldEncode

func (c *FormData) SetFieldEncode(key, value string) *FormData

func (*FormData) SetFields

func (c *FormData) SetFields(fields *map[string]string) *HTTPClient

Sets form data fields

func (*FormData) WithMultipart

func (c *FormData) WithMultipart() *FormData

SetMultipart

type HTTPClient

type HTTPClient struct {
	Timeout time.Duration

	BodyBytes []byte
	// contains filtered or unexported fields
}

func Delete

func Delete(u string) *HTTPClient

Init Delete http method

func Get

func Get(u string) *HTTPClient

Init get http method

func Head(u string) *HTTPClient

Init Head http method

func New

func New() *HTTPClient

func Patch

func Patch(u string) *HTTPClient

Init Path http method

func Post

func Post(u string) *HTTPClient

Init Post http method

func Put

func Put(u string) *HTTPClient

Init Put http method

func (*HTTPClient) Auth

func (c *HTTPClient) Auth() *Auth

Init status

func (*HTTPClient) Body

func (c *HTTPClient) Body() *Body

Sets the request body with io.Reader

func (*HTTPClient) Close

func (c *HTTPClient) Close() []error

func (*HTTPClient) ContentType

func (c *HTTPClient) ContentType() *ContentType

func (*HTTPClient) Cookie

func (c *HTTPClient) Cookie() *Cookie

This method init client with cookie

func (*HTTPClient) Delete

func (c *HTTPClient) Delete(u string) *HTTPClient

func (*HTTPClient) Do

func (c *HTTPClient) Do() *HTTPClient

Makes a request to the http server

func (*HTTPClient) DoWithContext

func (c *HTTPClient) DoWithContext(ctx context.Context) *HTTPClient

func (*HTTPClient) FormData

func (c *HTTPClient) FormData() *FormData

Init status

func (*HTTPClient) Get

func (c *HTTPClient) Get(u string) *HTTPClient

func (*HTTPClient) GetCurrentUrl

func (c *HTTPClient) GetCurrentUrl() *url.URL

func (*HTTPClient) GetErrors

func (c *HTTPClient) GetErrors() []error

func (*HTTPClient) GetResponse

func (c *HTTPClient) GetResponse() (*http.Response, []error)

func (*HTTPClient) Head

func (c *HTTPClient) Head(u string) *HTTPClient

func (*HTTPClient) Header

func (c *HTTPClient) Header() *Header

Sets the header with io.Reader

func (*HTTPClient) MaxRedirect

func (c *HTTPClient) MaxRedirect(maxRedirect int) *HTTPClient

Set max redirect count 0 = disable redirects

func (*HTTPClient) Patch

func (c *HTTPClient) Patch(u string) *HTTPClient

func (*HTTPClient) Post

func (c *HTTPClient) Post(u string) *HTTPClient

func (*HTTPClient) Proxy

func (c *HTTPClient) Proxy() *Proxy

func (*HTTPClient) Put

func (c *HTTPClient) Put(u string) *HTTPClient

func (*HTTPClient) Request

func (c *HTTPClient) Request()

func (*HTTPClient) ResetClient

func (c *HTTPClient) ResetClient() *HTTPClient

func (*HTTPClient) RetryIf

func (c *HTTPClient) RetryIf(statusCodes ...int) *HTTPClient

Sets the conditions for retrying a http request

func (*HTTPClient) RetryMax

func (c *HTTPClient) RetryMax(maxRetries int) *HTTPClient

Sets the counts for retrying a http request

func (*HTTPClient) SetMethod

func (c *HTTPClient) SetMethod(method string) *HTTPClient

func (*HTTPClient) SetRequest

func (c *HTTPClient) SetRequest(req *http.Request) *HTTPClient

func (*HTTPClient) SetTLSConfig

func (c *HTTPClient) SetTLSConfig(config *tls.Config) *HTTPClient

func (*HTTPClient) SetTimeout

func (c *HTTPClient) SetTimeout(timeout time.Duration) *HTTPClient

func (*HTTPClient) SetTimeoutSecons

func (c *HTTPClient) SetTimeoutSecons(second time.Duration) *HTTPClient

func (*HTTPClient) SetURL

func (c *HTTPClient) SetURL(u string) *HTTPClient

func (*HTTPClient) SetUserAgent

func (c *HTTPClient) SetUserAgent(agent string) *HTTPClient

func (*HTTPClient) Status

func (c *HTTPClient) Status() *Status

Init status

type Header struct {
	Client *HTTPClient
}

func (*Header) Add

func (c *Header) Add(header *map[string]string) *HTTPClient

Sets headers from string map object

func (*Header) Del

func (c *Header) Del(key string) *HTTPClient

Delete header by key

func (*Header) Get

func (c *Header) Get(key string) string

Gets header string by key

func (*Header) GetWithStringMap

func (c *Header) GetWithStringMap() map[string]string

Gets header and convert in string map

func (*Header) Set

func (c *Header) Set(key string, value string) *HTTPClient

Sets header key with string value

type Proxy

type Proxy struct {
	Client *HTTPClient
}

func (*Proxy) SetProxy

func (c *Proxy) SetProxy(uri string) *HTTPClient

type Request

type Request struct {
	Cookie []*http.Cookie
	// contains filtered or unexported fields
}

type SerializableCookies

type SerializableCookies struct {
	URL     string         `json:"url"`
	Cookies []*http.Cookie `json:"cookies"`
}

type Status

type Status struct {
	Client *HTTPClient
}

func (*Status) Get

func (c *Status) Get() string

Get status code with string like 200=OK

func (*Status) GetCode

func (c *Status) GetCode() int

Get status code with int

Jump to

Keyboard shortcuts

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