surf

package module
v1.0.46 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2024 License: MIT Imports: 39 Imported by: 4

README ΒΆ

πŸ€–πŸ‘‹ Surf: makes HTTP fun and easy!

Go Reference Go Report Card Go

Surf 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 surf!

🌟 Features

  1. πŸ’¬ Simple and Expressive: Surf's API is designed to make your code look like a conversation, making it easier to read and understand.
  2. πŸ’Ύ Caching and Streaming: Efficiently cache response bodies and stream data on the fly, like a superhero saving the world from slow internet connections.
  3. πŸ“‰ Limit and Deflate: Limit the amount of data you receive and decompress it on the fly, giving you more control over your HTTP interactions.
  4. 🎩 Flexible: Customize headers, query parameters, timeouts, and more for a truly tailor-made experience.
  5. πŸ” Browser Impersonation: Mimic various browsers such as Chrome, Firefox, and others, with a wide range of possible fingerprints for enhanced privacy and compatibility.

πŸ’» Example

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

package main

import (
	"fmt"
	"log"

	"github.com/enetx/surf"
)

func main() {
	resp, err := surf.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 surf package using go get:
go get -u github.com/enetx/surf
  1. Import the package into your project:
import "github.com/enetx/surf"
  1. Start making requests and have fun! πŸ˜„

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

Requires GOEXPERIMENT=rangefunc.

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

This section is empty.

Types ΒΆ

type Client ΒΆ

type Client struct {
	// 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 ΒΆ

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

ClientMiddleware add a client middleware.

func (*Client) CloseIdleConnections ΒΆ

func (c *Client) CloseIdleConnections()

CloseIdleConnections removes all entries from the cached transports. Specifically used when Singleton is enabled for JA3 or Impersonate functionalities.

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 ΒΆ

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

GetClient returns http.Client used by the Client.

func (*Client) GetDialer ΒΆ

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

GetDialer returns the net.Dialer used by the Client.

func (*Client) GetTLSConfig ΒΆ

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

GetTLSConfig returns the tls.Config used by the Client.

func (*Client) GetTransport ΒΆ

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

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) Raw ΒΆ

func (c *Client) Raw(raw, scheme string) *Request

Raw creates a new HTTP request using the provided raw data and scheme. The raw parameter should contain the raw HTTP request data as a string. The scheme parameter specifies the scheme (e.g., http, https) for the request.

func (*Client) RequestMiddleware ΒΆ

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

RequestMiddleware add a request middleware which hooks before request sent.

func (*Client) ResponseMiddleware ΒΆ

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
}

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() *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) DNSOverTLS ΒΆ

func (opt *Options) DNSOverTLS() *dnsOverTLS

DNSOverTLS configures the client to use DNS over TLS.

func (*Options) DisableCompression ΒΆ

func (opt *Options) DisableCompression() *Options

DisableCompression disables compression for the HTTP client.

func (*Options) DisableKeepAlive ΒΆ

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) ForceHTTP1 ΒΆ

func (opt *Options) ForceHTTP1() *Options

ForceHTTP1MW configures the client to use HTTP/1.1 forcefully.

func (*Options) ForwardHeadersOnRedirect ΒΆ

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) H2C ΒΆ

func (opt *Options) H2C() *Options

H2C configures the client to handle HTTP/2 Cleartext (h2c).

func (*Options) HTTP2Settings ΒΆ

func (opt *Options) HTTP2Settings() *http2s

HTTP2Settings configures settings related to HTTP/2 and returns an http2s struct.

func (*Options) Impersonate ΒΆ

func (opt *Options) Impersonate() *impersonate

Impersonate configures something related to impersonation and returns an impersonate struct.

func (*Options) InterfaceAddr ΒΆ

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

InterfaceAddr sets the network interface address for the client.

func (*Options) JA3 ΒΆ

func (opt *Options) JA3() *ja3

JA3 configures the client to use a specific TLS fingerprint.

func (*Options) MaxRedirects ΒΆ

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

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

func (*Options) NotFollowRedirects ΒΆ

func (opt *Options) NotFollowRedirects() *Options

NotFollowRedirects disables following redirects for the client.

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, codes ...int) *Options

Retry configures the retry behavior of the client.

Parameters:

retryMax: Maximum number of retries to be attempted.
retryWait: Duration to wait between retries.
codes: Optional list of HTTP status codes that trigger retries.
       If no codes are provided, default codes will be used
       (500, 429, 503 - Internal Server Error, Too Many Requests, Service Unavailable).

func (*Options) Session ΒΆ

func (opt *Options) Session() *Options

Session configures whether the client should maintain a session.

func (*Options) Singleton ΒΆ

func (opt *Options) Singleton() *Options

Singleton configures the client to use a singleton instance, ensuring there's only one client instance. This is needed specifically for JA3 or Impersonate functionalities.

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 ΒΆ

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 is 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 any) *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 ΒΆ

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

GetRequest returns the underlying http.Request of the custom request.

func (*Request) SetHeaders ΒΆ

func (req *Request) SetHeaders(headers any) *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 Response ΒΆ

type Response struct {
	*Client // Client is the associated client for the response.

	URL *url.URL // URL of the response.

	Body *body // Response body.

	Headers       headers       // Response headers.
	Status        string        // HTTP status string.
	UserAgent     string        // User agent string.
	Proto         string        // HTTP protocol version.
	Cookies       cookies       // Response cookies.
	Time          time.Duration // Total time taken for the response.
	ContentLength int64         // Length of the response content.
	StatusCode    int           // HTTP status code.
	Attempts      int           // Number of attempts made.
	// contains filtered or unexported fields
}

Response represents a custom response structure.

func (Response) Debug ΒΆ

func (resp Response) Debug() *debug

Debug returns a debug instance associated with a Response.

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 ΒΆ

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

GetResponse returns the underlying http.Response of the custom response.

func (Response) Referer ΒΆ

func (resp Response) Referer() string

Referer returns the referer of the response.

func (Response) RemoteAddress ΒΆ

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
internal
pkg

Jump to

Keyboard shortcuts

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