httpsling

package
v0.6.6 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2024 License: Apache-2.0 Imports: 25 Imported by: 0

README

Slinging HTTP

The httpsling library simplifies the way you make HTTP httpsling. It's intended to provide an easy-to-use interface for sending requests and handling responses, reducing the boilerplate code typically associated with the net/http package.

Overview

Creating a new HTTP client and making a request should be straightforward:

package main

import (
    "github.com/datumforge/datum/pkg/httpsling"
    "log"
)

func main() {
    // Create a client using a base URL
    client := httpsling.URL("http://datumisthebest.com")

    // Alternatively, create a client with custom configuration
    client = httpsling.Create(&httpsling.Config{
        BaseURL: "http://datumisthebest.com",
        Timeout: 30 * time.Second,
    })

    // Perform a GET request
    resp, err := client.Get("/resource")
    if err != nil {
        log.Fatal(err)
    }

    defer resp.Close()

    log.Println(resp.String())
}

Client

The Client struct is your gateway to making HTTP requests. You can configure it to your needs, setting default headers, cookies, timeout durations, etc.

client := httpsling.URL("http://datumisthebest.com")

// Or, with full configuration
client = httpsling.Create(&httpsling.Config{
    BaseURL: "http://datumisthebest.com",
    Timeout: 5 * time.Second,
    Headers: &http.Header{
        HeaderContentType: []string{ContentTypeJSON},
    },
})
Initializing the Client

You can start by creating a Client with specific configurations using the Create method:

client := httpsling.Create(&httpsling.Config{
    BaseURL: "https://the.cats.meow.com",
    Timeout: 30 * time.Second,
    Headers: &http.Header{
        HeaderAuthorization: []string{"Bearer YOUR_ACCESS_TOKEN"},
        HeaderContentType: []string{ContentTypeJSON},
    },
    Cookies: map[string]string{
        "session_token": "YOUR_SESSION_TOKEN",
    },
    TLSConfig: &tls.Config{
        InsecureSkipVerify: true,
    },
    MaxRetries: 3,
    RetryStrategy: httpsling.ExponentialBackoffStrategy(1*time.Second, 2, 30*time.Second),
    RetryIf: httpsling.DefaultRetryIf,
})

This setup creates a Client tailored for your API communication, including base URL, request timeout, default headers, and cookies

Configuring with Set Methods

Alternatively, you can use Set methods for a more dynamic configuration approach:

client := httpsling.URL("https://the.cats.meow.com").
    SetDefaultHeader(HeaderAuthorization, "Bearer YOUR_ACCESS_TOKEN").
    SetDefaultHeader(HeaderContentType, ContentTypeJSON).
    SetDefaultCookie("session_token", "YOUR_SESSION_TOKEN").
    SetTLSConfig(&tls.Config{InsecureSkipVerify: true}).
    SetMaxRetries(3).
    SetRetryStrategy(httpsling.ExponentialBackoffStrategy(1*time.Second, 2, 30*time.Second)).
    SetRetryIf(httpsling.DefaultRetryIf).
    SetProxy("http://localhost:8080")
Configuring BaseURL

Set the base URL for all requests:

client.SetBaseURL("https://the.cats.meow.com")
Setting Headers

Set default headers for all requests:

client.SetDefaultHeader(HeaderAuthorization, "Bearer YOUR_ACCESS_TOKEN")
client.SetDefaultHeader(HeaderContentType, ContentTypeJSON)

Bulk set default headers:

headers := &http.Header{
    HeaderAuthorization: []string{"Bearer YOUR_ACCESS_TOKEN"},
    HeaderContentType:  []string{ContentTypeJSON},
}
client.SetDefaultHeaders(headers)

Add or remove a header:

client.AddDefaultHeader("X-Custom-Header", "Value1")
client.DelDefaultHeader("X-Unneeded-Header")
Managing Cookies

Set default cookies for all requests:

client.SetDefaultCookie("session_id", "123456")

Bulk set default cookies:

cookies := map[string]string{
    "session_id": "123456",
    "preferences": "dark_mode=true",
}
client.SetDefaultCookies(cookies)

Remove a default cookie:

client.DelDefaultCookie("session_id")

This approach simplifies managing base URLs, headers, and cookies across all requests made with the client, ensuring consistency.

Configuring Timeouts

Define a global timeout for all requests to prevent indefinitely hanging operations:

client := httpsling.Create(&httpsling.Config{
    Timeout: 15 * time.Second,
})
TLS Configuration

Custom TLS configurations can be applied for enhanced security measures, such as loading custom certificates:

tlsConfig := &tls.Config{InsecureSkipVerify: true}
client.SetTLSConfig(tlsConfig)

Requests

The library provides a RequestBuilder to construct and dispatch HTTP httpsling. Here are examples of performing various types of requests, including adding query parameters, setting headers, and attaching a body to your httpsling.

GET Request
resp, err := client.Get("/path").
    Query("search", "query").
    Header(HeaderAccept, ContentTypeJSON).
    Send(context.Background())
POST Request
resp, err := client.Post("/path").
    Header(HeaderContentType, ContentTypeJSON).
    JSONBody(map[string]interface{}{"key": "value"}).
    Send(context.Background())
PUT Request
resp, err := client.Put("/stff/{stuff_id}").
    PathParam("stuff_id", "123456").
    JSONBody(map[string]interface{}{"updatedKey": "newValue"}).
    Send(context.Background())
DELETE Request
resp, err := client.Delete("/stffs/{stuff_id}").
    PathParam("stuff_id", "123456meowmeow").
    Send(context.Background())
Retry Mechanism

Automatically retry requests on failure with customizable strategies:

client.SetMaxRetries(3)
client.SetRetryStrategy(httpsling.ExponentialBackoffStrategy(1*time.Second, 2, 30*time.Second))
client.SetRetryIf(func(req *http.Request, resp *http.Response, err error) bool {
	// Only retry for 500 Internal Server Error
	return resp.StatusCode == http.StatusInternalServerError
})
Configuring Retry Strategies
Applying a Default Backoff Strategy

For consistent delay intervals between retries:

client.SetRetryStrategy(httpsling.DefaultBackoffStrategy(5 * time.Second))
Utilizing a Linear Backoff Strategy

To increase delay intervals linearly with each retry attempt:

client.SetRetryStrategy(httpsling.LinearBackoffStrategy(1 * time.Second))
Employing an Exponential Backoff Strategy

For exponential delay increases between attempts, with an option to cap the delay:

client.SetRetryStrategy(httpsling.ExponentialBackoffStrategy(1*time.Second, 2, 30*time.Second))
Customizing Retry Conditions

Define when retries should be attempted based on response status codes or errors:

client.SetRetryIf(func(req *http.Request, resp *http.Response, err error) bool {
    return resp.StatusCode == http.StatusInternalServerError || err != nil
})
Setting Maximum Retry Attempts

To limit the number of retries, use the SetMaxRetries method:

client.SetMaxRetries(3)
Proxy Configuration

Route requests through a proxy server:

client.SetProxy("http://localhost:8080")
Authentication

Supports various authentication methods:

  • Basic Auth:
client.SetAuth(httpsling.BasicAuth{
  Username: "user",
  Password: "pass",
})
  • Bearer Token:
client.SetAuth(httpsling.BearerAuth{
    Token: "YOUR_ACCESS_TOKEN",
})
Query Parameters

Add query parameters to your request using Query, Queries, QueriesStruct, or remove them with DelQuery

// Add a single query parameter
request.Query("search", "query")

// Add multiple query parameters
request.Queries(url.Values{"sort": []string{"date"}, "limit": []string{"10"}})

// Add query parameters from a struct
type queryParams struct {
    Sort  string `url:"sort"`
    Limit int    `url:"limit"`
}
request.QueriesStruct(queryParams{Sort: "date", Limit: 10})

// Remove one or more query parameters
request.DelQuery("sort", "limit")
Headers

Set request headers using Header, Headers, or related methods

request.Header(HeaderAuthorization, "Bearer YOUR_ACCESS_TOKEN")
request.Headers(http.Header{HeaderContentType: []string{ContentTypeJSON}})

// Convenient methods for common headers
request.ContentType(ContentTypeJSON)
request.Accept(ContentTypeJSON)
request.UserAgent("MyCustomClient/1.0")
request.Referer("https://example.com")
Cookies

Add cookies to your request using Cookie, Cookies, or remove them with DelCookie.

// Add a single cookie
request.Cookie("session_token", "YOUR_SESSION_TOKEN")

// Add multiple cookies at once
request.Cookies(map[string]string{
    "session_token": "YOUR_SESSION_TOKEN",
    "user_id": "12345",
})

// Remove one or more cookies
request.DelCookie("session_token", "user_id")

Body Content

Specify the request body directly with Body or use format-specific methods like JSONBody, XMLBody, YAMLBody, TextBody, or RawBody for appropriate content types.

// Setting JSON body
request.JSONBody(map[string]interface{}{"key": "value"})

// Setting XML body
request.XMLBody(myXmlStruct)

// Setting YAML body
request.YAMLBody(myYamlStruct)

// Setting text body
request.TextBody("plain text content")

// Setting raw body
request.RawBody([]byte("raw data"))
Timeout and Retries

Configure request-specific timeout and retry strategies:

request.Timeout(10 * time.Second).MaxRetries(3)
Sending Requests

The Send(ctx) method executes the HTTP request built with the Request builder. It requires a context.Context argument, allowing you to control request cancellation and timeouts.

resp, err := request.Send(context.Background())
if err != nil {
    log.Fatalf("Request failed: %v", err)
}
// Process response...
Advanced Features
Handling Cancellation

To cancel a request, simply use the context's cancel function. This is particularly useful for long-running requests that you may want to abort if they take too long or if certain conditions are met.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() // Ensures resources are freed up after the operation completes or times out

// Cancel the request if it hasn't completed within the timeout
resp, err := request.Send(ctx)
if errors.Is(err, context.Canceled) {
    log.Println("Request was canceled")
}
HTTP Client Customization

Directly customize the underlying http.Client:

customHTTPClient := &http.Client{Timeout: 20 * time.Second}
client.SetHTTPClient(customHTTPClient)
Path Parameters

To insert or modify path parameters in your URL, use PathParam for individual parameters or PathParams for multiple. For removal, use DelPathParam.

// Setting a single path parameter
request.PathParam("userId", "123")

// Setting multiple path parameters at once
request.PathParams(map[string]string{"userId": "123", "postId": "456"})

// Removing path parameters
request.DelPathParam("userId", "postId")

When using client.Get("/users/{userId}/posts/{postId}"), replace {userId} and {postId} with actual values by using PathParams or PathParam.

Form Data

For application/x-www-form-urlencoded content, utilize FormField for individual fields or FormFields for multiple.

// Adding individual form field
request.FormField("name", "John Snow")

// Setting multiple form fields at once
fields := map[string]interface{}{"name": "John", "age": "30"}
request.FormFields(fields)
File Uploads

To include files in a multipart/form-data request, specify each file's form field name, file name, and content using File or add multiple files with Files.

// Adding a single file
file, _ := os.Open("path/to/file")
request.File("profile_picture", "filename.jpg", file)

// Adding multiple files
request.Files(file1, file2)
Authentication

Apply authentication methods directly to the request:

request.Auth(httpsling.BasicAuth{
   Username: "user",
   Password: "pass",
})

Middleware

Add custom middleware to process the request or response:

request.AddMiddleware(func(next httpsling.MiddlewareHandlerFunc) httpsling.MiddlewareHandlerFunc {
    return func(req *http.Request) (*http.Response, error) {
        // Custom logic before request
        resp, err := next(req)
        // Custom logic after response
        return resp, err
    }
})
Understanding Middleware

Middleware functions wrap around HTTP requests, allowing pre- and post-processing of requests and responses. They can modify requests before they are sent, examine responses, and decide whether to modify them, retry the request, or take other actions.

Client-Level Middleware

Client-level middleware is applied to all requests made by a client. It's ideal for cross-cutting concerns like logging, error handling, and metrics collection.

Adding Middleware to a Client:

client := httpsling.Create(&httpsling.Config{BaseURL: "https://the.cats.meow.com"})
client.AddMiddleware(func(next httpsling.MiddlewareHandlerFunc) httpsling.MiddlewareHandlerFunc {
    return func(req *http.Request) (*http.Response, error) {
        // Pre-request manipulation
        fmt.Println("Request URL:", req.URL)

        // Proceed with the request
        resp, err := next(req)

        // Post-response manipulation
        if err == nil {
            fmt.Println("Response status:", resp.Status)
        }

        return resp, err
    }
})
Request-Level Middleware

Request-level middleware applies only to individual httpsling. This is useful for request-specific concerns, such as request tracing or modifying the request based on dynamic context.

Adding Middleware to a Request:

request := client.NewRequestBuilder(MethodGet, "/path").AddMiddleware(func(next httpsling.MiddlewareHandlerFunc) httpsling.MiddlewareHandlerFunc {
    return func(req *http.Request) (*http.Response, error) {
        // Modify the request here
        req.Header.Add("X-Request-ID", "12345")

        // Proceed with the modified request
        return next(req)
    }
})
Implementing Custom Middleware

Custom middleware can perform a variety of tasks, such as authentication, logging, and metrics. Here's a simple logging middleware example:

func loggingMiddleware(next httpsling.MiddlewareHandlerFunc) httpsling.MiddlewareHandlerFunc {
    return func(req *http.Request) (*http.Response, error) {
        log.Printf("Requesting %s %s", req.Method, req.URL)
        resp, err := next(req)
        if err != nil {
            log.Printf("Request to %s failed: %v", req.URL, err)
        } else {
            log.Printf("Received %d response from %s", resp.StatusCode, req.URL)
        }
        return resp, err
    }
}
Integrating OpenTelemetry Middleware

OpenTelemetry middleware can be used to collect tracing and metrics for your requests if you're into that sort of thing. Below is an example of how to set up a basic trace for an HTTP request:

Implementing OpenTelemetry Middleware:

func openTelemetryMiddleware(next httpsling.MiddlewareHandlerFunc) httpsling.MiddlewareHandlerFunc {
    return func(req *http.Request) (*http.Response, error) {
        ctx, span := otel.Tracer("requests").Start(req.Context(), req.URL.Path)
        defer span.End()

        // Add trace ID to request headers if needed
        traceID := span.SpanContext().TraceID().String()
        req.Header.Set("X-Trace-ID", traceID)

        resp, err := next(req)

        // Set span attributes based on response
        if err == nil {
            span.SetAttributes(attribute.Int("http.status_code", resp.StatusCode))
        } else {
            span.RecordError(err)
        }

        return resp, err
    }
}

Responses

Handling responses is necessary in determining the outcome of your HTTP requests - the library has some built-in response code validators and other tasty things.

type APIResponse struct {
    Data string `json:"data"`
}

var apiResp APIResponse
if err := resp.ScanJSON(&apiResp); err != nil {
    log.Fatal(err)
}

log.Printf("Status Code: %d\n", resp.StatusCode())
log.Printf("Response Data: %s\n", apiResp.Data)
Parsing Response Body

By leveraging the Scan, ScanJSON, ScanXML, and ScanYAML methods, you can decode responses based on the Content-Type

JSON Responses

Given a JSON response, you can unmarshal it directly into a Go struct using either the specific ScanJSON method or the generic Scan method, which automatically detects the content type:

var jsonData struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

// Unmarshal using ScanJSON
if err := response.ScanJSON(&jsonData); err != nil {
    log.Fatalf("Error unmarshalling JSON: %v", err)
}

// Alternatively, unmarshal using Scan
if err := response.Scan(&jsonData); err != nil {
    log.Fatalf("Error unmarshalling response: %v", err)
}
XML Responses

For XML responses, use ScanXML or Scan to decode into a Go struct. Here's an example assuming the response contains XML data:

var xmlData struct {
    Name string `xml:"name"`
    Age  int    `xml:"age"`
}

// Unmarshal using ScanXML
if err := response.ScanXML(&xmlData); err != nil {
    log.Fatalf("Error unmarshalling XML: %v", err)
}

// Alternatively, unmarshal using Scan
if err := response.Scan(&xmlData); err != nil {
    log.Fatalf("Error unmarshalling response: %v", err)
}
YAML Responses

YAML content is similarly straightforward to handle. The ScanYAML or Scan method decodes the YAML response into the specified Go struct:

var yamlData struct {
    Name string `yaml:"name"`
    Age  int    `yaml:"age"`
}

// Unmarshal using ScanYAML
if err := response.ScanYAML(&yamlData); err != nil {
    log.Fatalf("Error unmarshalling YAML: %v", err)
}

// Alternatively, unmarshal using Scan
if err := response.Scan(&yamlData); err != nil {
    log.Fatalf("Error unmarshalling response: %v", err)
}
Storing Response Content

For saving the response body to a file or streaming it to an io.Writer:

  • Save: Write the response body to a designated location

    // Save response to a file
    if err := response.Save("downloaded_file.txt"); err != nil {
        log.Fatalf("Failed to save file: %v", err)
    }
    
Evaluating Response Success

To assess whether the HTTP request was successful:

  • IsSuccess: Check if the status code signifies a successful response

    if response.IsSuccess() {
        fmt.Println("The request succeeded hot diggity dog")
    }
    

Enabling Logging

To turn on logging, you must explicitly initialize and set a Logger in the client configuration. Here's how to create and use the DefaultLogger, which logs to os.Stderr by default, and is configured to log errors only:

logger := httpsling.NewDefaultLogger(os.Stderr, slog.LevelError)
client := httpsling.Create(&httpsling.Config{
    Logger: logger,
})

Or, for an already instantiated client:

client.SetLogger(httpsling.NewDefaultLogger(os.Stderr, slog.LevelError))
Adjusting Log Levels

Adjusting the log level is straightforward. After defining your logger, simply set the desired level. This allows you to control the verbosity of the logs based on your requirements.

logger := httpsling.NewDefaultLogger(os.Stderr, httpsling.LevelError)
logger.SetLevel(httpsling.LevelInfo) // Set to Info level to capture more detailed logs

client := httpsling.Create(&httpsling.Config{
    Logger: logger,
})

The available log levels are:

  • LevelDebug
  • LevelInfo
  • LevelWarn
  • LevelError
Implementing a Custom Logger

For more advanced scenarios where you might want to integrate with an existing logging system or format logs differently, implement the Logger interface. This requires methods for each level of logging (Debugf, Infof, Warnf, Errorf) and a method to set the log level (SetLevel).

Here is a simplified example:

type MyLogger struct {
    // Include your custom logging mechanism here
}

func (l *MyLogger) Debugf(format string, v ...any) {
    // Custom debug logging implementation
}

func (l *MyLogger) Infof(format string, v ...any) {
    // Custom info logging implementation
}

func (l *MyLogger) Warnf(format string, v ...any) {
    // Custom warn logging implementation
}

func (l *MyLogger) Errorf(format string, v ...any) {
    // Custom error logging implementation
}

func (l *MyLogger) SetLevel(level httpsling.Level) {
    // Implement setting the log level in your logger
}

// Usage
myLogger := &MyLogger{}
myLogger.SetLevel(httpsling.LevelDebug) // Example setting to Debug level

client := httpsling.Create(&httpsling.Config{
    Logger: myLogger,
})

Stream Callbacks

Stream callbacks are functions that you define to handle chunks of data as they are received from the server. The Requests library supports three types of stream callbacks:

  • StreamCallback: Invoked for each chunk of data received
  • StreamErrCallback: Invoked when an error occurs during streaming
  • StreamDoneCallback: Invoked once streaming is completed, regardless of whether it ended due to an error or successfully
Configuring Stream Callbacks

To configure streaming for a request, use the Stream method on a RequestBuilder instance. This method accepts a StreamCallback function, which will be called with each chunk of data received from the server.

streamCallback := func(data []byte) error {
    fmt.Println("Received stream data:", string(data))
    return nil // Return an error if needed to stop streaming
}

request := client.Get("/stream-endpoint").Stream(streamCallback)
Handling Stream Errors

To handle errors that occur during streaming, set a StreamErrCallback using the StreamErr method on the Response object.

streamErrCallback := func(err error) {
    fmt.Printf("Stream error: %v\n", err)
}

response, _ := request.Send(context.Background())
response.StreamErr(streamErrCallback)
Completing Stream Processing

Once streaming is complete, you can use the StreamDone method on the Response object to set a StreamDoneCallback. This callback is invoked after the stream is fully processed, either successfully or due to an error.

streamDoneCallback := func() {
    fmt.Println("Stream processing completed")
}

response.StreamDone(streamDoneCallback)
Example: Consuming an SSE Stream

The following example demonstrates how to consume a Server-Sent Events (SSE) stream, processing each event as it arrives, handling errors, and performing cleanup once the stream ends.

// Configure the stream callback to handle data chunks
streamCallback := func(data []byte) error {
    fmt.Println("Received stream event:", string(data))
    return nil
}

// Configure error and done callbacks
streamErrCallback := func(err error) {
    fmt.Printf("Error during streaming: %v\n", err)
}

streamDoneCallback := func() {
    fmt.Println("Stream ended")
}

// Create the streaming request
client := httpsling.Create(&httpsling.Config{BaseURL: "https://example.com"})
request := client.Get("/events").Stream(streamCallback)

// Send the request and configure callbacks
response, err := request.Send(context.Background())
if err != nil {
    fmt.Printf("Failed to start streaming: %v\n", err)
    return
}

response.StreamErr(streamErrCallback).StreamDone(streamDoneCallback)

Inspirations

This library was inspired by and built upon the work of several other HTTP client libraries:

Props to dghubble for a great name with sling, which was totally ripped off to make httpsling <3. I chose not to use any of these directly because I wanted to have layers of control we may need within our services echosystem.

Documentation

Overview

Package httpsling is a wrapper for creating and sending http httpsling (e.g. for webhooks, external 3d party integrations)

Index

Constants

View Source
const (
	// Authentication
	HeaderAuthorization      = "Authorization"
	HeaderProxyAuthenticate  = "Proxy-Authenticate"
	HeaderProxyAuthorization = "Proxy-Authorization"
	HeaderWWWAuthenticate    = "WWW-Authenticate"

	// Caching
	HeaderAge           = "Age"
	HeaderCacheControl  = "Cache-Control"
	HeaderClearSiteData = "Clear-Site-Data"
	HeaderExpires       = "Expires"
	HeaderPragma        = "Pragma"
	HeaderWarning       = "Warning"

	// Client hints
	HeaderAcceptCH         = "Accept-CH"
	HeaderAcceptCHLifetime = "Accept-CH-Lifetime"
	HeaderContentDPR       = "Content-DPR"
	HeaderDPR              = "DPR"
	HeaderEarlyData        = "Early-Data"
	HeaderSaveData         = "Save-Data"
	HeaderViewportWidth    = "Viewport-Width"
	HeaderWidth            = "Width"

	// Conditionals
	HeaderETag              = "ETag"
	HeaderIfMatch           = "If-Match"
	HeaderIfModifiedSince   = "If-Modified-Since"
	HeaderIfNoneMatch       = "If-None-Match"
	HeaderIfUnmodifiedSince = "If-Unmodified-Since"
	HeaderLastModified      = "Last-Modified"
	HeaderVary              = "Vary"

	// Connection management
	HeaderConnection      = "Connection"
	HeaderKeepAlive       = "Keep-Alive"
	HeaderProxyConnection = "Proxy-Connection"

	// Content negotiation
	HeaderAccept         = "Accept"
	HeaderAcceptCharset  = "Accept-Charset"
	HeaderAcceptEncoding = "Accept-Encoding"
	HeaderAcceptLanguage = "Accept-Language"

	// Controls
	HeaderCookie      = "Cookie"
	HeaderExpect      = "Expect"
	HeaderMaxForwards = "Max-Forwards"
	HeaderSetCookie   = "Set-Cookie"

	// CORS
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderOrigin                        = "Origin"
	HeaderTimingAllowOrigin             = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies"

	// Do Not Track
	HeaderDNT = "DNT"
	HeaderTk  = "Tk"

	// Downloads
	HeaderContentDisposition = "Content-Disposition"

	// Message body information
	HeaderContentEncoding = "Content-Encoding"
	HeaderContentLanguage = "Content-Language"
	HeaderContentLength   = "Content-Length"
	HeaderContentLocation = "Content-Location"
	HeaderContentType     = "Content-Type"

	// Content Types
	ContentTypeForm                   = "application/x-www-form-urlencoded" // https://datatracker.ietf.org/doc/html/rfc1866
	ContentTypeMultipart              = "multipart/form-data"               // https://datatracker.ietf.org/doc/html/rfc2388
	ContentTypeJSON                   = "application/json"                  // https://datatracker.ietf.org/doc/html/rfc4627
	ContentTypeJSONUTF8               = "application/json;charset=utf-8"    // https://datatracker.ietf.org/doc/html/rfc4627
	ContentTypeXML                    = "application/xml"                   // https://datatracker.ietf.org/doc/html/rfc3023
	ContentTypeXMLUTF8                = "application/xml;charset=utf-8"
	ContentTypeYAML                   = "application/yaml" // https://www.rfc-editor.org/rfc/rfc9512.html
	ContentTypeYAMLUTF8               = "application/yaml;charset=utf-8"
	ContentTypeText                   = "text/plain"
	ContentTypeApplicationOctetStream = "application/octet-stream"

	// Proxies
	HeaderForwarded       = "Forwarded"
	HeaderVia             = "Via"
	HeaderXForwardedFor   = "X-Forwarded-For"
	HeaderXForwardedHost  = "X-Forwarded-Host"
	HeaderXForwardedProto = "X-Forwarded-Proto"

	// Redirects
	HeaderLocation = "Location"

	// Request context
	HeaderFrom           = "From"
	HeaderHost           = "Host"
	HeaderReferer        = "Referer"
	HeaderReferrerPolicy = "Referrer-Policy"
	HeaderUserAgent      = "User-Agent"

	// Response context
	HeaderAllow  = "Allow"
	HeaderServer = "Server"

	// Range requests.
	HeaderAcceptRanges = "Accept-Ranges"
	HeaderContentRange = "Content-Range"
	HeaderIfRange      = "If-Range"
	HeaderRange        = "Range"

	// Security
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy       = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                        = "Expect-CT"
	HeaderFeaturePolicy                   = "Feature-Policy"
	HeaderPublicKeyPins                   = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXDownloadOptions                = "X-Download-Options"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXPoweredBy                      = "X-Powered-By"
	HeaderXXSSProtection                  = "X-XSS-Protection"

	// Server-sent event
	HeaderLastEventID = "Last-Event-ID"
	HeaderNEL         = "NEL"
	HeaderPingFrom    = "Ping-From"
	HeaderPingTo      = "Ping-To"
	HeaderReportTo    = "Report-To"

	// Transfer coding
	HeaderTE               = "TE"
	HeaderTrailer          = "Trailer"
	HeaderTransferEncoding = "Transfer-Encoding"

	// WebSockets
	HeaderSecWebSocketAccept     = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions" /* #nosec G101 */
	HeaderSecWebSocketKey        = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol   = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion    = "Sec-WebSocket-Version"

	// Other
	HeaderAcceptPatch         = "Accept-Patch"
	HeaderAcceptPushPolicy    = "Accept-Push-Policy"
	HeaderAcceptSignature     = "Accept-Signature"
	HeaderAltSvc              = "Alt-Svc"
	HeaderDate                = "Date"
	HeaderIndex               = "Index"
	HeaderLargeAllocation     = "Large-Allocation"
	HeaderLink                = "Link"
	HeaderPushPolicy          = "Push-Policy"
	HeaderRetryAfter          = "Retry-After"
	HeaderServerTiming        = "Server-Timing"
	HeaderSignature           = "Signature"
	HeaderSignedHeaders       = "Signed-Headers"
	HeaderSourceMap           = "SourceMap"
	HeaderUpgrade             = "Upgrade"
	HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control"
	HeaderXPingback           = "X-Pingback"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderXRobotsTag          = "X-Robots-Tag"
	HeaderXUACompatible       = "X-UA-Compatible"
)

Variables

View Source
var (
	// ErrUnsupportedContentType is returned when the content type is unsupported
	ErrUnsupportedContentType = errors.New("unsupported content type")
	// ErrUnsupportedDataType is returned when the data type is unsupported
	ErrUnsupportedDataType = errors.New("unsupported data type")
	// ErrEncodingFailed is returned when the encoding fails
	ErrEncodingFailed = errors.New("encoding failed")
	// ErrRequestCreationFailed is returned when the request cannot be created
	ErrRequestCreationFailed = errors.New("failed to create request")
	// ErrResponseReadFailed is returned when the response cannot be read
	ErrResponseReadFailed = errors.New("failed to read response")
	// ErrUnsupportedScheme is returned when the proxy scheme is unsupported
	ErrUnsupportedScheme = errors.New("unsupported proxy scheme")
	// ErrUnsupportedFormFieldsType is returned when the form fields type is unsupported
	ErrUnsupportedFormFieldsType = errors.New("unsupported form fields type")
	// ErrNotSupportSaveMethod is returned when the provided type for saving is not supported
	ErrNotSupportSaveMethod = errors.New("the provided type for saving is not supported")
	// ErrInvalidTransportType is returned when the transport type is invalid
	ErrInvalidTransportType = errors.New("invalid transport type")
	// ErrResponseNil is returned when the response is nil
	ErrResponseNil = errors.New("response is nil")
	// ErrFailedToCloseResponseBody is returned when the response body cannot be closed
	ErrFailedToCloseResponseBody = errors.New("failed to close response body")
	// ErrMapper
	ErrMapper = "%w: %v"
)
View Source
var DefaultFormEncoder = &FormEncoder{}

DefaultFormEncoder instance

View Source
var DefaultJSONDecoder = &JSONDecoder{
	UnmarshalFunc: json.Unmarshal,
}

DefaultJSONDecoder instance using the standard json.Unmarshal function

View Source
var DefaultJSONEncoder = &JSONEncoder{
	MarshalFunc: json.Marshal,
}

DefaultJSONEncoder instance using the standard json.Marshal function

View Source
var DefaultXMLDecoder = &XMLDecoder{
	UnmarshalFunc: xml.Unmarshal,
}

DefaultXMLDecoder instance using the standard xml.Unmarshal function

View Source
var DefaultXMLEncoder = &XMLEncoder{
	MarshalFunc: xml.Marshal,
}

DefaultXMLEncoder instance using the standard xml.Marshal function

View Source
var DefaultYAMLDecoder = &YAMLDecoder{
	UnmarshalFunc: yaml.Unmarshal,
}

DefaultYAMLDecoder instance using the goccy/go-yaml Unmarshal function

View Source
var DefaultYAMLEncoder = &YAMLEncoder{
	MarshalFunc: yaml.Marshal,
}

DefaultYAMLEncoder instance using the goccy/go-yaml Marshal function

Functions

func DefaultBackoffStrategy

func DefaultBackoffStrategy(delay time.Duration) func(int) time.Duration

DefaultBackoffStrategy provides a simple constant delay between retries

func DefaultRetryIf

func DefaultRetryIf(req *http.Request, resp *http.Response, err error) bool

DefaultRetryIf is a simple retry condition that retries on 5xx status codes

func ExponentialBackoffStrategy

func ExponentialBackoffStrategy(initialInterval time.Duration, multiplier float64, maxBackoffTime time.Duration) func(int) time.Duration

ExponentialBackoffStrategy increases the delay exponentially with each retry attempt

func GetBuffer

func GetBuffer() *bytebufferpool.ByteBuffer

GetBuffer retrieves a buffer from the pool

func LinearBackoffStrategy

func LinearBackoffStrategy(initialInterval time.Duration) func(int) time.Duration

LinearBackoffStrategy increases the delay linearly with each retry attempt

func PutBuffer

func PutBuffer(b *bytebufferpool.ByteBuffer)

PutBuffer returns a buffer to the pool

Types

type AuthMethod

type AuthMethod interface {
	// Apply adds the authentication method to the request
	Apply(req *http.Request)
	// Valid checks if the authentication method is valid
	Valid() bool
}

AuthMethod defines the interface for applying authentication strategies to httpsling

type AuthType added in v0.6.1

type AuthType string

AuthType represents the type of authentication method

var (
	// BearerAuthType is the Bearer token authentication type using the Authorization header
	BearerAuthType AuthType = "Bearer"
	// BasicAuthType is the Basic authentication type using a username and password
	BasicAuthType AuthType = "Basic"
)

type BackoffStrategy

type BackoffStrategy func(attempt int) time.Duration

BackoffStrategy defines a function that returns the delay before the next retry

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

BasicAuth represents HTTP Basic Authentication credentials

func (BasicAuth) Apply

func (b BasicAuth) Apply(req *http.Request)

Apply adds the Basic Auth credentials to the request

func (BasicAuth) Valid

func (b BasicAuth) Valid() bool

Valid checks if the Basic Auth credentials are present

type BearerAuth

type BearerAuth struct {
	Token string
}

BearerAuth represents an OAuth 2.0 Bearer token

func (BearerAuth) Apply

func (b BearerAuth) Apply(req *http.Request)

Apply adds the Bearer token to the request's Authorization header

func (BearerAuth) Valid

func (b BearerAuth) Valid() bool

Valid checks if the Bearer token is present

type Client

type Client struct {

	// BaseURL is the base URL for all httpsling made by this client
	BaseURL string
	// Headers are the default headers to be sent with each request
	Headers *http.Header
	// Cookies are the default cookies to be sent with each request
	Cookies []*http.Cookie
	// Middlewares are the request/response manipulation middlewares
	Middlewares []Middleware
	// TLSConfig is the TLS configuration for the client
	TLSConfig *tls.Config
	// MaxRetries is the maximum number of retry attempts
	MaxRetries int
	// RetryStrategy is the backoff strategy for retries
	RetryStrategy BackoffStrategy
	// RetryIf is the custom retry condition function
	RetryIf RetryIfFunc
	// HTTPClient is the underlying HTTP client
	HTTPClient *http.Client
	// JSONEncoder is the JSON encoder for the client
	JSONEncoder Encoder
	// JSONDecoder is the JSON decoder for the client
	JSONDecoder Decoder
	// XMLEncoder is the XML encoder for the client
	XMLEncoder Encoder
	// XMLDecoder is the XML decoder for the client
	XMLDecoder Decoder
	// YAMLEncoder is the YAML encoder for the client
	YAMLEncoder Encoder
	// YAMLDecoder is the YAML decoder for the client
	YAMLDecoder Decoder
	// Logger is the logger instance for the client
	Logger Logger
	// auth is the authentication method for the client
	Auth AuthMethod
	// contains filtered or unexported fields
}

Client represents an HTTP client and is the main control mechanism for making HTTP requests

func Create

func Create(config *Config) *Client

Create initializes a new HTTP client with the given configuration

func URL

func URL(baseURL string) *Client

URL creates a new HTTP client with the given base URL

func (*Client) AddDefaultHeader

func (c *Client) AddDefaultHeader(key, value string)

AddDefaultHeader adds a default header

func (*Client) AddMiddleware

func (c *Client) AddMiddleware(middlewares ...Middleware)

AddMiddleware adds a middleware to the client

func (*Client) Connect

func (c *Client) Connect(path string) *RequestBuilder

Connect initiates a CONNECT request

func (*Client) Custom

func (c *Client) Custom(path, method string) *RequestBuilder

Custom initiates a custom request

func (*Client) DelDefaultCookie

func (c *Client) DelDefaultCookie(name string)

DelDefaultCookie removes a default cookie from the client

func (*Client) DelDefaultHeader

func (c *Client) DelDefaultHeader(key string)

DelDefaultHeader removes a default header

func (*Client) Delete

func (c *Client) Delete(path string) *RequestBuilder

Delete initiates a DELETE request

func (*Client) Get

func (c *Client) Get(path string) *RequestBuilder

Get initiates a GET request

func (*Client) Head

func (c *Client) Head(path string) *RequestBuilder

Head initiates a HEAD request

func (*Client) InsecureSkipVerify

func (c *Client) InsecureSkipVerify() *Client

InsecureSkipVerify sets the TLS configuration to skip certificate verification

func (*Client) NewRequestBuilder

func (c *Client) NewRequestBuilder(method, path string) *RequestBuilder

NewRequestBuilder creates a new RequestBuilder with default settings

func (*Client) Options

func (c *Client) Options(path string) *RequestBuilder

Options initiates an OPTIONS request

func (*Client) Patch

func (c *Client) Patch(path string) *RequestBuilder

Patch initiates a PATCH request

func (*Client) Post

func (c *Client) Post(path string) *RequestBuilder

Post initiates a POST request

func (*Client) Put

func (c *Client) Put(path string) *RequestBuilder

Put initiates a PUT request

func (*Client) RemoveProxy

func (c *Client) RemoveProxy()

RemoveProxy clears any configured proxy, allowing direct connections

func (*Client) SetAuth

func (c *Client) SetAuth(auth AuthMethod)

SetAuth configures an authentication method for the client

func (*Client) SetBaseURL

func (c *Client) SetBaseURL(baseURL string)

SetBaseURL sets the base URL for the client

func (*Client) SetCookieJar added in v0.6.0

func (c *Client) SetCookieJar(jar *cookiejar.Jar)

SetDefaultCookieJar sets the default cookie jar for the client

func (*Client) SetDefaultAccept

func (c *Client) SetDefaultAccept(accept string)

SetDefaultAccept sets the default accept header for the client

func (*Client) SetDefaultContentType

func (c *Client) SetDefaultContentType(contentType string)

SetDefaultContentType sets the default content type for the client

func (*Client) SetDefaultCookie

func (c *Client) SetDefaultCookie(name, value string)

SetDefaultCookie sets a default cookie for the client

func (*Client) SetDefaultCookieJar

func (c *Client) SetDefaultCookieJar() error

SetDefaultCookieJar sets the creates a new cookie jar and sets it for the client

func (*Client) SetDefaultCookies

func (c *Client) SetDefaultCookies(cookies map[string]string)

SetDefaultCookies sets the default cookies for the client

func (*Client) SetDefaultHeader

func (c *Client) SetDefaultHeader(key, value string)

SetDefaultHeader adds or updates a default header

func (*Client) SetDefaultHeaders

func (c *Client) SetDefaultHeaders(headers *http.Header)

SetDefaultHeaders sets the default headers for the client

func (*Client) SetDefaultReferer

func (c *Client) SetDefaultReferer(referer string)

SetDefaultReferer sets the default referer for the client

func (*Client) SetDefaultTimeout

func (c *Client) SetDefaultTimeout(timeout time.Duration)

SetDefaultTimeout sets the default timeout for the client

func (*Client) SetDefaultTransport

func (c *Client) SetDefaultTransport(transport http.RoundTripper)

SetDefaultTransport sets the default transport for the client

func (*Client) SetDefaultUserAgent

func (c *Client) SetDefaultUserAgent(userAgent string)

SetDefaultUserAgent sets the default user agent for the client

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(httpClient *http.Client)

SetHTTPClient sets the HTTP client for the client

func (*Client) SetJSONMarshal

func (c *Client) SetJSONMarshal(marshalFunc func(v any) ([]byte, error))

SetJSONMarshal sets the JSON marshal function for the client's JSONEncoder

func (*Client) SetJSONUnmarshal

func (c *Client) SetJSONUnmarshal(unmarshalFunc func(data []byte, v any) error)

SetJSONUnmarshal sets the JSON unmarshal function for the client's JSONDecoder

func (*Client) SetLogger

func (c *Client) SetLogger(logger Logger) *Client

SetLogger sets logger instance in client

func (*Client) SetMaxRetries

func (c *Client) SetMaxRetries(maxRetries int) *Client

SetMaxRetries sets the maximum number of retry attempts

func (*Client) SetProxy

func (c *Client) SetProxy(proxyURL string) error

SetProxy configures the client to use a proxy. Supports http, https, and socks5 proxies

func (*Client) SetRetryIf

func (c *Client) SetRetryIf(retryIf RetryIfFunc) *Client

SetRetryIf sets the custom retry condition function

func (*Client) SetRetryStrategy

func (c *Client) SetRetryStrategy(strategy BackoffStrategy) *Client

SetRetryStrategy sets the backoff strategy for retries

func (*Client) SetTLSConfig

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

SetTLSConfig sets the TLS configuration for the client

func (*Client) SetXMLMarshal

func (c *Client) SetXMLMarshal(marshalFunc func(v any) ([]byte, error))

SetXMLMarshal sets the XML marshal function for the client's XMLEncoder

func (*Client) SetXMLUnmarshal

func (c *Client) SetXMLUnmarshal(unmarshalFunc func(data []byte, v any) error)

SetXMLUnmarshal sets the XML unmarshal function for the client's XMLDecoder

func (*Client) SetYAMLMarshal

func (c *Client) SetYAMLMarshal(marshalFunc func(v any) ([]byte, error))

SetYAMLMarshal sets the YAML marshal function for the client's YAMLEncoder

func (*Client) SetYAMLUnmarshal

func (c *Client) SetYAMLUnmarshal(unmarshalFunc func(data []byte, v any) error)

SetYAMLUnmarshal sets the YAML unmarshal function for the client's YAMLDecoder

func (*Client) Trace

func (c *Client) Trace(path string) *RequestBuilder

Trace initiates a TRACE request

type Config

type Config struct {
	// The base URL for all httpsling made by this client
	BaseURL string
	// Default headers to be sent with each request
	Headers *http.Header
	// Default Cookies to be sent with each request
	Cookies map[string]string
	// Timeout for httpsling
	Timeout time.Duration
	// Cookie jar for the client
	CookieJar *cookiejar.Jar
	// Middlewares for request/response manipulation
	Middlewares []Middleware
	// TLS configuration for the client
	TLSConfig *tls.Config
	// Custom transport for the client
	Transport http.RoundTripper
	// Maximum number of retry attempts
	MaxRetries int
	// RetryStrategy defines the backoff strategy for retries
	RetryStrategy BackoffStrategy
	// RetryIf defines the custom retry condition function
	RetryIf RetryIfFunc
	// Logger instance for the client
	Logger Logger
}

Config sets up the initial configuration for the HTTP client - you need to initialize multiple if you want the behaviors to be different

type CustomAuth

type CustomAuth struct {
	Header string
}

CustomAuth allows for custom Authorization header values

func (CustomAuth) Apply

func (c CustomAuth) Apply(req *http.Request)

Apply sets a custom Authorization header value

func (CustomAuth) Valid

func (c CustomAuth) Valid() bool

Valid checks if the custom Authorization header value is present

type Decoder

type Decoder interface {
	// Decode decodes the data from the reader into the provided value
	Decode(r io.Reader, v any) error
}

Decoder is the interface that wraps the Decode method

type DefaultLogger

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

DefaultLogger is a default logger that uses `slog` as the underlying logger

func (*DefaultLogger) Debugf

func (l *DefaultLogger) Debugf(format string, v ...any)

Debugf logs a message at the Debug level

func (*DefaultLogger) Errorf

func (l *DefaultLogger) Errorf(format string, v ...any)

Errorf logs a message at the Error level

func (*DefaultLogger) Infof

func (l *DefaultLogger) Infof(format string, v ...any)

Infof logs a message at the Info level

func (*DefaultLogger) SetLevel

func (l *DefaultLogger) SetLevel(level Level)

SetLevel sets the log level of the logger

func (*DefaultLogger) Warnf

func (l *DefaultLogger) Warnf(format string, v ...any)

Warnf logs a message at the Warn level

type Encoder

type Encoder interface {
	// Encode encodes the provided value into a reader
	Encode(v any) (io.Reader, error)
	// ContentType returns the content type of the encoded data
	ContentType() string
}

Encoder is the interface that wraps the Encode method

type File

type File struct {
	// Name is the form field name
	Name string
	// FileName is the file name
	FileName string
	// Content is the file content
	Content io.ReadCloser
	// FileMime is the file mime type
	FileMime string
}

File represents a form file

func (*File) SetContent

func (f *File) SetContent(content io.ReadCloser)

SetContent sets the content of the file

func (*File) SetFileName

func (f *File) SetFileName(fileName string)

SetFileName sets the file name

func (*File) SetName

func (f *File) SetName(name string)

SetName sets the form field name

type FormEncoder

type FormEncoder struct{}

FormEncoder handles encoding of form data

func (*FormEncoder) Encode

func (e *FormEncoder) Encode(v any) (io.Reader, error)

Encode encodes the given value into URL-encoded form data

type JSONDecoder

type JSONDecoder struct {
	UnmarshalFunc func(data []byte, v any) error
}

JSONDecoder handles decoding of JSON data

func (*JSONDecoder) Decode

func (d *JSONDecoder) Decode(r io.Reader, v any) error

Decode reads the data from the reader and unmarshals it into the provided value

type JSONEncoder

type JSONEncoder struct {
	// MarshalFunc is the custom marshal function to use
	MarshalFunc func(v any) ([]byte, error)
}

JSONEncoder handles encoding of JSON data

func (*JSONEncoder) ContentType

func (e *JSONEncoder) ContentType() string

ContentType returns the content type for JSON data

func (*JSONEncoder) Encode

func (e *JSONEncoder) Encode(v any) (io.Reader, error)

Encode marshals the provided value into JSON format

type Level

type Level int

Level is a type that represents the log level

const (
	LevelDebug Level = iota
	LevelInfo
	LevelWarn
	LevelError
)

The levels of logs

type Logger

type Logger interface {
	Debugf(format string, v ...any)
	Infof(format string, v ...any)
	Warnf(format string, v ...any)
	Errorf(format string, v ...any)
	SetLevel(level Level)
}

Logger is a logger interface that output logs with a format

func NewDefaultLogger

func NewDefaultLogger(output io.Writer, level Level) Logger

NewDefaultLogger creates a new `DefaultLogger` with the given output and log level

type Middleware

type Middleware func(next MiddlewareHandlerFunc) MiddlewareHandlerFunc

Middleware takes MiddlewareHandlerFunc and wraps around a next function call, which can be another middleware or the final transport layer call

type MiddlewareHandlerFunc

type MiddlewareHandlerFunc func(req *http.Request) (*http.Response, error)

MiddlewareHandlerFunc defines a function that takes an http.Request and returns an http.Response

type RequestBuilder

type RequestBuilder struct {

	// BeforeRequest is a hook that can be used to modify the request object
	// before the request has been fired. This is useful for adding authentication
	// and other functionality not provided in this library
	BeforeRequest func(req *http.Request) error
	// contains filtered or unexported fields
}

RequestBuilder facilitates building and executing HTTP requests

func (*RequestBuilder) Accept

func (b *RequestBuilder) Accept(accept string) *RequestBuilder

Accept sets the Accept header for the request

func (*RequestBuilder) AddHeader

func (b *RequestBuilder) AddHeader(key, value string) *RequestBuilder

AddHeader adds a header to the request

func (*RequestBuilder) AddMiddleware

func (b *RequestBuilder) AddMiddleware(middlewares ...Middleware)

AddMiddleware adds a middleware to the request

func (*RequestBuilder) Auth

func (b *RequestBuilder) Auth(auth AuthMethod) *RequestBuilder

Auth applies an authentication method to the request

func (*RequestBuilder) Body

func (b *RequestBuilder) Body(body interface{}) *RequestBuilder

Body sets the request body

func (*RequestBuilder) ContentType

func (b *RequestBuilder) ContentType(contentType string) *RequestBuilder

ContentType sets the Content-Type header for the request

func (*RequestBuilder) Cookie

func (b *RequestBuilder) Cookie(key, value string) *RequestBuilder

Cookie adds a cookie to the request

func (*RequestBuilder) Cookies

func (b *RequestBuilder) Cookies(cookies map[string]string) *RequestBuilder

Cookies method for map

func (*RequestBuilder) DelCookie

func (b *RequestBuilder) DelCookie(key ...string) *RequestBuilder

DelCookie removes one or more cookies from the request

func (*RequestBuilder) DelFile

func (b *RequestBuilder) DelFile(key ...string) *RequestBuilder

DelFile removes one or more files from the request

func (*RequestBuilder) DelFormField

func (b *RequestBuilder) DelFormField(key ...string) *RequestBuilder

DelFormField removes one or more form fields

func (*RequestBuilder) DelHeader

func (b *RequestBuilder) DelHeader(key ...string) *RequestBuilder

DelHeader removes one or more headers from the request

func (*RequestBuilder) DelPathParam

func (b *RequestBuilder) DelPathParam(key ...string) *RequestBuilder

DelPathParam removes one or more path params fields from the RequestBuilder instance

func (*RequestBuilder) DelQuery

func (b *RequestBuilder) DelQuery(key ...string) *RequestBuilder

DelQuery removes one or more query parameters from the request

func (*RequestBuilder) File

func (b *RequestBuilder) File(key, filename string, content io.ReadCloser) *RequestBuilder

File adds a file to the request

func (*RequestBuilder) Files

func (b *RequestBuilder) Files(files ...*File) *RequestBuilder

Files sets multiple files at once

func (*RequestBuilder) Form

func (b *RequestBuilder) Form(v any) *RequestBuilder

Form sets form fields and files for the request

func (*RequestBuilder) FormField

func (b *RequestBuilder) FormField(key, val string) *RequestBuilder

FormField adds or updates a form field

func (*RequestBuilder) FormFields

func (b *RequestBuilder) FormFields(fields any) *RequestBuilder

FormFields sets multiple form fields at once

func (*RequestBuilder) Header

func (b *RequestBuilder) Header(key, value string) *RequestBuilder

Header sets (or replaces) a header in the request

func (*RequestBuilder) Headers

func (b *RequestBuilder) Headers(headers http.Header) *RequestBuilder

Headers set headers to the request

func (*RequestBuilder) JSONBody

func (b *RequestBuilder) JSONBody(v interface{}) *RequestBuilder

JSONBody sets the request body as JSON

func (*RequestBuilder) MaxRetries

func (b *RequestBuilder) MaxRetries(maxRetries int) *RequestBuilder

MaxRetries sets the maximum number of retry attempts

func (*RequestBuilder) Method

func (b *RequestBuilder) Method(method string) *RequestBuilder

Method sets the HTTP method for the request

func (*RequestBuilder) Path

func (b *RequestBuilder) Path(path string) *RequestBuilder

Path sets the URL path for the request

func (*RequestBuilder) PathParam

func (b *RequestBuilder) PathParam(key, value string) *RequestBuilder

PathParam sets a single path param field and its value in the RequestBuilder instance

func (*RequestBuilder) PathParams

func (b *RequestBuilder) PathParams(params map[string]string) *RequestBuilder

PathParams sets multiple path params fields and their values at one go in the RequestBuilder instance

func (*RequestBuilder) Queries

func (b *RequestBuilder) Queries(params url.Values) *RequestBuilder

Queries adds query parameters to the request

func (*RequestBuilder) QueriesStruct

func (b *RequestBuilder) QueriesStruct(queryStruct interface{}) *RequestBuilder

QueriesStruct adds query parameters to the request based on a struct tagged with url tags

func (*RequestBuilder) Query

func (b *RequestBuilder) Query(key, value string) *RequestBuilder

Query adds a single query parameter to the request

func (*RequestBuilder) RawBody

func (b *RequestBuilder) RawBody(v []byte) *RequestBuilder

RawBody sets the request body as raw bytes

func (*RequestBuilder) Referer

func (b *RequestBuilder) Referer(referer string) *RequestBuilder

Referer sets the Referer header for the request

func (*RequestBuilder) RetryIf

func (b *RequestBuilder) RetryIf(retryIf RetryIfFunc) *RequestBuilder

RetryIf sets the custom retry condition function

func (*RequestBuilder) RetryStrategy

func (b *RequestBuilder) RetryStrategy(strategy BackoffStrategy) *RequestBuilder

RetryStrategy sets the backoff strategy for retries

func (*RequestBuilder) Send

func (b *RequestBuilder) Send(ctx context.Context) (*Response, error)

Send executes the HTTP request

func (*RequestBuilder) Stream

func (b *RequestBuilder) Stream(callback StreamCallback) *RequestBuilder

Stream sets the stream callback for the request

func (*RequestBuilder) StreamDone

func (b *RequestBuilder) StreamDone(callback StreamDoneCallback) *RequestBuilder

StreamDone sets the done callback for the request.

func (*RequestBuilder) StreamErr

func (b *RequestBuilder) StreamErr(callback StreamErrCallback) *RequestBuilder

StreamErr sets the error callback for the request.

func (*RequestBuilder) TextBody

func (b *RequestBuilder) TextBody(v string) *RequestBuilder

TextBody sets the request body as plain text

func (*RequestBuilder) Timeout

func (b *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder

Timeout sets the request timeout

func (*RequestBuilder) UserAgent

func (b *RequestBuilder) UserAgent(userAgent string) *RequestBuilder

UserAgent sets the User-Agent header for the request

func (*RequestBuilder) XMLBody

func (b *RequestBuilder) XMLBody(v interface{}) *RequestBuilder

XMLBody sets the request body as XML

func (*RequestBuilder) YAMLBody

func (b *RequestBuilder) YAMLBody(v interface{}) *RequestBuilder

YAMLBody sets the request body as YAML

type Response

type Response struct {

	// RawResponse is the original HTTP response
	RawResponse *http.Response
	// BodyBytes is the response body as a juicy byte slice
	BodyBytes []byte
	// Context is the request context
	Context context.Context
	// Client is the HTTP client
	Client *Client
	// contains filtered or unexported fields
}

Response represents an HTTP response

func NewResponse

func NewResponse(ctx context.Context, resp *http.Response, client *Client, stream StreamCallback, streamErr StreamErrCallback, streamDone StreamDoneCallback) (*Response, error)

NewResponse creates a new wrapped response object leveraging the buffer pool

func (*Response) Body

func (r *Response) Body() []byte

Body returns the response body as a juicy byte slice

func (*Response) Close

func (r *Response) Close() error

Close closes the response body

func (*Response) ContentLength

func (r *Response) ContentLength() int

ContentLength returns the length of the response body

func (*Response) ContentType

func (r *Response) ContentType() string

ContentType returns the value of the HeaderContentType header

func (*Response) Cookies

func (r *Response) Cookies() []*http.Cookie

Cookies parses and returns the cookies set in the response

func (*Response) Header

func (r *Response) Header() http.Header

Header returns the response headers

func (*Response) IsContentType

func (r *Response) IsContentType(contentType string) bool

IsContentType Checks if the response Content-Type header matches a given content type

func (*Response) IsEmpty

func (r *Response) IsEmpty() bool

IsEmpty checks if the response body is empty

func (*Response) IsJSON

func (r *Response) IsJSON() bool

IsJSON checks if the response Content-Type indicates JSON

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess checks if the response status code indicates success

func (*Response) IsXML

func (r *Response) IsXML() bool

IsXML checks if the response Content-Type indicates XML

func (*Response) IsYAML

func (r *Response) IsYAML() bool

IsYAML checks if the response Content-Type indicates YAML

func (*Response) Location

func (r *Response) Location() (*url.URL, error)

Location returns the URL redirected address

func (*Response) Save

func (r *Response) Save(v any) error

Save saves the response body to a file or io.Writer

func (*Response) Scan

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

Scan attempts to unmarshal the response body based on its content type

func (*Response) ScanJSON

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

ScanJSON unmarshals the response body into a struct via JSON decoding

func (*Response) ScanXML

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

ScanXML unmarshals the response body into a struct via XML decoding

func (*Response) ScanYAML

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

ScanYAML unmarshals the response body into a struct via YAML decoding

func (*Response) Status

func (r *Response) Status() string

Status returns the status string of the response

func (*Response) StatusCode

func (r *Response) StatusCode() int

StatusCode returns the HTTP status code of the response

func (*Response) String

func (r *Response) String() string

String returns the response body as a string

func (*Response) URL

func (r *Response) URL() *url.URL

URL returns the request URL that elicited the response

type RetryConfig

type RetryConfig struct {
	// MaxRetries is the maximum number of retry attempts
	MaxRetries int
	// Strategy is the backoff strategy function
	Strategy BackoffStrategy
	// RetryIf is the custom retry condition function
	RetryIf RetryIfFunc
}

RetryConfig defines the configuration for retrying requests

type RetryIfFunc

type RetryIfFunc func(req *http.Request, resp *http.Response, err error) bool

RetryIfFunc defines the function signature for retry conditions

type StreamCallback

type StreamCallback func([]byte) error

StreamCallback is a callback function that is called when data is received

type StreamDoneCallback

type StreamDoneCallback func()

StreamDoneCallback is a callback function that is called when the stream is done

type StreamErrCallback

type StreamErrCallback func(error)

StreamErrCallback is a callback function that is called when an error occurs

type XMLDecoder

type XMLDecoder struct {
	UnmarshalFunc func(data []byte, v any) error
}

XMLDecoder handles decoding of XML data

func (*XMLDecoder) Decode

func (d *XMLDecoder) Decode(r io.Reader, v any) error

Decode unmarshals the XML data from the reader into the provided value

type XMLEncoder

type XMLEncoder struct {
	MarshalFunc func(v any) ([]byte, error)
}

XMLEncoder handles encoding of XML data

func (*XMLEncoder) ContentType

func (e *XMLEncoder) ContentType() string

ContentType returns the content type for XML data

func (*XMLEncoder) Encode

func (e *XMLEncoder) Encode(v any) (io.Reader, error)

Encode marshals the provided value into XML format

type YAMLDecoder

type YAMLDecoder struct {
	UnmarshalFunc func(data []byte, v any) error
}

YAMLDecoder handles decoding of YAML data

func (*YAMLDecoder) Decode

func (d *YAMLDecoder) Decode(r io.Reader, v any) error

Decode reads the data from the reader and unmarshals it into the provided value

type YAMLEncoder

type YAMLEncoder struct {
	MarshalFunc func(v any) ([]byte, error)
}

YAMLEncoder handles encoding of YAML data

func (*YAMLEncoder) ContentType

func (e *YAMLEncoder) ContentType() string

ContentType returns the content type for YAML data

func (*YAMLEncoder) Encode

func (e *YAMLEncoder) Encode(v any) (io.Reader, error)

Encode marshals the provided value into YAML format

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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