hhttp

package module
v1.0.61 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2023 License: MIT Imports: 36 Imported by: 1

README ¶

🤖👋 Human HTTP: makes HTTP fun and easy!

Go Reference Go Report Card

hhttp (Human HTTP) is a fun, user-friendly, and lightweight Go library that allows you to interact with HTTP services as if you were chatting with them face-to-face! 😄 Imagine if you could make HTTP requests by simply asking a server politely, and receiving responses as if you were having a delightful conversation with a friend. That's the essence of hhttp!

🌟 Features

  1. 💬 Simple and expressive: hhttp's API is designed to make your code look like a conversation, making it easier to read and understand.
  2. 🚀 Asynchronous magic: With hhttp's built-in async capabilities, you can send multiple requests in parallel and handle them effortlessly.
  3. 💾 Caching and streaming: Efficiently cache response bodies and stream data on the fly, like a superhero saving the world from slow internet connections.
  4. 📉 Limit and deflate: Limit the amount of data you receive, and decompress it on the fly, giving you more control over your HTTP interactions.
  5. 🎩 Flexible: Customize headers, query parameters, timeouts, and more, for a truly tailor-made experience.

💻 Example

Here's a fun and friendly example of how hhttp makes HTTP requests look like a conversation:

package main

import (
	"fmt"
	"log"

	"github.com/x0xO/hhttp"
)

func main() {
	resp, err := hhttp.NewClient().Get("https://api.example.com/jokes/random").Do() // A simple GET request
	if err != nil { log.Fatal(err) }

	joke := struct {
		ID     int    `json:"id"`
		Setup  string `json:"setup"`
		Punch  string `json:"punch"`
	}{}

	resp.Body.JSON(&joke)

	fmt.Println("Joke of the day:")
	fmt.Printf("%s\n%s\n", joke.Setup, joke.Punch)
}

🚀 Getting Started

To start making friends with HTTP services, follow these simple steps:

  1. Install the hhttp package using go get:
go get -u github.com/x0xO/hhttp
  1. Import the package into your project:
import "github.com/x0xO/hhttp"
  1. Start making requests and have fun! 😄

Give hhttp a try, and watch your HTTP conversations come to life!

Documentation ¶

Index ¶

Constants ¶

This section is empty.

Variables ¶

This section is empty.

Functions ¶

This section is empty.

Types ¶

type AsyncURL ¶

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

AsyncURL struct represents an asynchronous URL with additional information such as data, context, setHeaders, addHeaders, and url.

func NewAsyncURL ¶

func NewAsyncURL(url string) *AsyncURL

NewAsyncURL creates a new AsyncURL object with the provided URL string and returns a pointer to it.

func (*AsyncURL) AddCookies ¶ added in v1.0.14

func (au *AsyncURL) AddCookies(cookies ...http.Cookie) *AsyncURL

AddCookies adds cookies to the AsyncURL object and returns a pointer to the updated object.

func (*AsyncURL) AddHeaders ¶

func (au *AsyncURL) AddHeaders(headers map[string]string) *AsyncURL

AddHeaders adds headers to the AsyncURL object and returns a pointer to the updated object.

func (*AsyncURL) Context ¶

func (au *AsyncURL) Context(context any) *AsyncURL

Context sets the context of the AsyncURL object and returns a pointer to the updated object.

func (*AsyncURL) Data ¶

func (au *AsyncURL) Data(data ...any) *AsyncURL

Data sets the data of the AsyncURL object and returns a pointer to the updated object.

func (*AsyncURL) SetHeaders ¶

func (au *AsyncURL) SetHeaders(headers map[string]string) *AsyncURL

SetHeaders sets the headers of the AsyncURL object and returns a pointer to the updated object.

type Client ¶

type Client struct {
	Async *async
	// contains filtered or unexported fields
}

Client struct provides a customizable HTTP client with configurable options for making requests, handling connections, and managing TLS settings.

func NewClient ¶

func NewClient() *Client

NewClient creates a new Client with default settings.

func (*Client) ClientMiddleware ¶ added in v1.0.30

func (c *Client) ClientMiddleware(m clientMiddleware) *Client

ClientMiddleware add a client middleware.

func (*Client) Delete ¶

func (c *Client) Delete(rawURL string, data ...any) *Request

Delete creates a new DELETE request.

func (*Client) FileUpload ¶

func (c *Client) FileUpload(rawURL, fieldName, filePath string, data ...any) *Request

FileUpload creates a new multipart file upload request.

func (*Client) Get ¶

func (c *Client) Get(rawURL string, data ...any) *Request

Get creates a new GET request.

func (*Client) GetClient ¶ added in v1.0.23

func (c *Client) GetClient() *http.Client

GetClient returns http.Client used by the Client.

func (*Client) GetDialer ¶ added in v1.0.23

func (c *Client) GetDialer() *net.Dialer

GetDialer returns the net.Dialer used by the Client.

func (*Client) GetTLSConfig ¶ added in v1.0.30

func (c *Client) GetTLSConfig() *tls.Config

GetTLSClientConfig returns the tls.Config used by the Client.

func (*Client) GetTransport ¶

func (c *Client) GetTransport() *http.Transport

GetTransport returns the http.transport used by the Client.

func (*Client) Head ¶

func (c *Client) Head(rawURL string) *Request

Head creates a new HEAD request.

func (*Client) Multipart ¶

func (c *Client) Multipart(rawURL string, multipartValues map[string]string) *Request

Multipart creates a new multipart form data request.

func (*Client) Patch ¶

func (c *Client) Patch(rawURL string, data any) *Request

Patch creates a new PATCH request.

func (*Client) Post ¶

func (c *Client) Post(rawURL string, data any) *Request

Post creates a new POST request.

func (*Client) Put ¶

func (c *Client) Put(rawURL string, data any) *Request

Put creates a new PUT request.

func (*Client) RequestMiddleware ¶ added in v1.0.30

func (c *Client) RequestMiddleware(m requestMiddleware) *Client

RequestMiddleware add a request middleware which hooks before request sent.

func (*Client) ResponseMiddleware ¶ added in v1.0.30

func (c *Client) ResponseMiddleware(m responseMiddleware) *Client

ResponseMiddleware add a response middleware which hooks after response received.

func (*Client) SetOptions ¶

func (c *Client) SetOptions(opt *Options) *Client

SetOptions sets the provided options for the client and returns the updated client. It configures various settings like HTTP2, sessions, keep-alive, dial TLS, resolver, interface address, timeout, and redirect policy.

type Options ¶

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

Options a struct that holds options for configuring the HTTP client.

func NewOptions ¶

func NewOptions() *Options

NewOptions creates a new Options instance with default values.

func (*Options) BasicAuth ¶

func (opt *Options) BasicAuth(authentication any) *Options

BasicAuth sets the basic authentication credentials for the client.

func (*Options) BearerAuth ¶

func (opt *Options) BearerAuth(authentication string) *Options

BearerAuth sets the bearer token for the client.

func (*Options) CacheBody ¶

func (opt *Options) CacheBody(enable ...bool) *Options

CacheBody configures whether the client should cache the body of the response.

func (*Options) ContentType ¶

func (opt *Options) ContentType(contentType string) *Options

ContentType sets the content type for the client.

func (*Options) DNS ¶

func (opt *Options) DNS(dns string) *Options

DNS sets the custom DNS resolver address.

func (*Options) DNSCache ¶ added in v1.0.21

func (opt *Options) DNSCache(ttl time.Duration, maxUsage int64) *Options

DNSCache configures the DNS cache settings of the HTTP client.

DNS caching can improve the performance of HTTP clients by caching the DNS lookup results for the specified Time-To-Live (TTL) duration and limiting the usage of the cached DNS result.

Parameters:

- ttl: the TTL duration for the DNS cache. After this duration, the DNS cache for a host will be invalidated.

- maxUsage: the maximum number of times a cached DNS lookup result can be used. After this number is reached, the DNS cache for a host will be invalidated.

Returns the same Options object, allowing for chaining of configuration calls.

Example:

opt := hhttp.NewOptions().DNSCache(time.Second*30, 10)
cli := hhttp.NewClient().SetOptions(opt)

The client will now use a DNS cache with a 30-second TTL and a maximum usage count of 10.

func (*Options) DNSOverTLS ¶

func (opt *Options) DNSOverTLS() *dnsOverTLS

DNSOverTLS configures the client to use DNS over TLS.

func (*Options) DisableKeepAlive ¶ added in v1.0.33

func (opt *Options) DisableKeepAlive() *Options

DisableKeepAlive disable keep-alive connections.

func (*Options) FollowOnlyHostRedirects ¶

func (opt *Options) FollowOnlyHostRedirects() *Options

FollowOnlyHostRedirects configures whether the client should only follow redirects within the same host.

func (*Options) ForwardHeadersOnRedirect ¶ added in v1.0.34

func (opt *Options) ForwardHeadersOnRedirect() *Options

ForwardHeadersOnRedirect adds a middleware to the Options object that ensures HTTP headers are forwarded during a redirect.

func (*Options) GetRemoteAddress ¶

func (opt *Options) GetRemoteAddress() *Options

GetRemoteAddress configures whether the client should get the remote address.

func (*Options) HTTP2 ¶

func (opt *Options) HTTP2(enable ...bool) *Options

HTTP2 configures whether the client should use HTTP/2.

func (*Options) History ¶

func (opt *Options) History() *Options

History configures whether the client should keep a history of requests (for debugging purposes only). WARNING: use only for debugging, not in async mode, no concurrency safe!!!

func (*Options) InterfaceAddr ¶

func (opt *Options) InterfaceAddr(address string) *Options

InterfaceAddr sets the network interface address for the client.

func (*Options) MaxRedirects ¶

func (opt *Options) MaxRedirects(maxRedirects int) *Options

MaxRedirects sets the maximum number of redirects the client should follow.

func (*Options) Proxy ¶

func (opt *Options) Proxy(proxy any) *Options

Proxy sets the proxy settings for the client.

func (*Options) RedirectPolicy ¶

func (opt *Options) RedirectPolicy(f func(*http.Request, []*http.Request) error) *Options

RedirectPolicy sets a custom redirect policy for the client.

func (*Options) Retry ¶

func (opt *Options) Retry(retryMax int, retryWait ...time.Duration) *Options

Retry configures the retry behavior of the client.

func (*Options) Session ¶

func (opt *Options) Session() *Options

Session configures whether the client should maintain a session.

func (Options) String ¶

func (opt Options) String() string

String generate a string representation of the Options instance.

func (*Options) Timeout ¶

func (opt *Options) Timeout(timeout time.Duration) *Options

Timeout sets the timeout duration for the client.

func (*Options) UnixDomainSocket ¶ added in v1.0.2

func (opt *Options) UnixDomainSocket(socketPath string) *Options

UnixDomainSocket sets the path for a Unix domain socket in the Options. This allows the HTTP client to connect to the server using a Unix domain socket instead of a traditional TCP/IP connection.

func (*Options) UserAgent ¶

func (opt *Options) UserAgent(userAgent any) *Options

UserAgent sets the user agent for the client.

type Request ¶

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

Request a struct that holds information about an HTTP request.

func (*Request) AddCookies ¶

func (req *Request) AddCookies(cookies ...http.Cookie) *Request

AddCookies adds cookies to the request.

func (*Request) AddHeaders ¶

func (req *Request) AddHeaders(headers map[string]string) *Request

AddHeaders adds headers to the request, appending to any existing headers with the same name.

func (*Request) Do ¶

func (req *Request) Do() (*Response, error)

Do performs the HTTP request and returns a Response object or an error if the request failed.

func (*Request) GetRequest ¶ added in v1.0.30

func (req *Request) GetRequest() *http.Request

func (*Request) SetHeaders ¶

func (req *Request) SetHeaders(headers map[string]string) *Request

SetHeaders sets headers for the request, replacing existing ones with the same name.

func (*Request) WithContext ¶

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

WithContext associates the provided context with the request.

type Requests ¶

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

Requests a struct that manages concurrent HTTP requests.

func (*Requests) Do ¶

func (reqs *Requests) Do() (chan *asyncResponse, chan error)

Do performs all queued requests concurrently, returning channels with results and errors.

func (*Requests) Pool ¶

func (reqs *Requests) Pool(workers int) *Requests

Pool sets the number of worker goroutines for the concurrent requests.

func (*Requests) RateLimiter ¶

func (reqs *Requests) RateLimiter(maxRequestsPerSecond int) *Requests

RateLimiter sets a rate limiter for the concurrent requests, limiting the number of requests per second.

func (*Requests) WithContext ¶

func (reqs *Requests) WithContext(ctx context.Context) *Requests

WithContext associates the provided context with the concurrent requests.

type Response ¶

type Response struct {
	*Client

	URL *url.URL

	Body *body

	Headers       headers
	Status        string
	UserAgent     string
	Proto         string
	History       history
	Cookies       cookies
	Time          time.Duration
	ContentLength int64
	StatusCode    int
	Attempts      int
	// contains filtered or unexported fields
}

func (Response) Debug ¶

func (resp Response) Debug() *debug

func (Response) GetCookies ¶

func (resp Response) GetCookies(rawURL string) []*http.Cookie

GetCookies returns the cookies from the response for the given URL.

func (Response) GetResponse ¶ added in v1.0.36

func (resp Response) GetResponse() *http.Response

func (Response) Referer ¶

func (resp Response) Referer() string

Referer returns the referer of the response.

func (Response) RemoteAddress ¶ added in v1.0.10

func (resp Response) RemoteAddress() net.Addr

RemoteAddress returns the remote address of the response.

func (*Response) SetCookies ¶

func (resp *Response) SetCookies(rawURL string, cookies []*http.Cookie) error

SetCookies sets cookies for the given URL in the response.

func (Response) TLSGrabber ¶

func (resp Response) TLSGrabber() *tlsData

TLSGrabber returns a tlsData struct containing information about the TLS connection if it exists.

Directories ¶

Path Synopsis
pkg

Jump to

Keyboard shortcuts

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