restc

package module
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: May 30, 2026 License: MIT Imports: 21 Imported by: 7

README

RESTC - HTTP Client in Go

Go Version Test Status Codecov Lint Status License Go Report Card

Description

RESTC is a lightweight Go library for executing HTTP requests with support for headers, cookies, query parameters, and JSON serialization. It includes error handling, automatic retries, context support, and simplified response management.

Features

  • Supports HTTP methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE
  • Easy handling of headers, cookies, and query parameters
  • Automatic JSON serialization and deserialization
  • Bearer token authentication
  • HTTP error handling with typed error responses
  • Retry mechanism with exponential backoff
  • Context support for cancellation and timeouts
  • Custom response/error parsers
  • HTML error body text extraction
  • Optional response body size limit (DoS protection)
  • URL scheme validation (http/https only)
  • Multipart form data and file upload
  • Middleware chain for logging, tracing, metrics, etc.
  • Redirect policy control (follow, block, or limit)
  • Variadic options for flexible client configuration
  • IPv4/IPv6 transport control

Installation

go get github.com/alex-cos/restc

Usage

Creating an HTTP client
// Basic client
client := restc.New("https://api.example.com")

// With custom timeout
client := restc.New("https://api.example.com",
    restc.WithTimeout(10 * time.Second),
)

// With custom http.Client (for TLS config, proxies, etc.)
httpClient := &http.Client{
    Transport: &http.Transport{
        MaxIdleConns: 10,
    },
}
client := restc.NewWithClient("https://api.example.com", httpClient)
Configuring the client
client := restc.New("https://api.example.com")

client.SetTimeout(10 * time.Second)
client.SetEntryPoint("https://api.example.com/v2")
client.SetRetryCount(3)
client.SetRetryWaitTime(100 * time.Millisecond)
client.SetRetryMaxWaitTime(2 * time.Second)
client.SetMaxResponseSize(10 * 1024 * 1024) // 10 MB limit
Client options

You can pass options directly to New or NewWithClient for a more concise configuration:

client := restc.New("https://api.example.com",
    restc.WithTimeout(10 * time.Second),
    restc.WithRetryCount(3),
    restc.WithRetryWaitTime(100 * time.Millisecond),
    restc.WithRetryMaxWaitTime(2 * time.Second),
    restc.WithMaxResponseSize(10 * 1024 * 1024),
    restc.WithHeader("User-Agent", "my-app/1.0"),
    restc.WithHeaders(map[string]string{
        "X-Custom-Header": "value",
    }),
    restc.WithOnlyIPv4(),  // Force IPv4 only
)

Available options:

Option Description
WithTimeout(duration) Set request timeout
WithRetryCount(n) Set number of retry attempts
WithRetryWaitTime(duration) Set initial wait time between retries
WithRetryMaxWaitTime(duration) Set max wait time between retries
WithMaxResponseSize(bytes) Limit response body size (DoS protection)
WithParseResponse(fn) Custom response parser
WithParseError(fn) Custom error response parser
WithHeader(key, value) Set a default header
WithHeaders(map) Set multiple default headers
WithRedirectPolicy(policy) Set redirect behavior
WithMaxRedirects(n) Limit number of redirects
WithOnlyIPv4() Force IPv4-only connections
WithOnlyIPv6() Force IPv6-only connections
Executing a GET request
req := restc.Get("users").
    SetHeader("Accept", restc.TypeApplicationJSON).
    AddQueryParam("limit", "10")

resp, err := client.Execute(req)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Status:", resp.StatusCode())
fmt.Println("Response:", resp.String())
Executing a POST request
type User struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

user := User{
    Name:  "John Doe",
    Email: "john@example.com",
}

req := restc.Post("users").SetBody(user)
resp, err := client.Execute(req)
if err != nil {
    log.Fatal(err)
}
JSON deserialization
type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

req := restc.Get("users/1").
    SetResponseType(&User{})

resp, err := client.Execute(req)
if err != nil {
    log.Fatal(err)
}

user := resp.Content().(*User)
fmt.Println(user.Name)
Error response deserialization
type APIError struct {
    Status  int    `json:"status"`
    Message string `json:"error"`
    Path    string `json:"path"`
}

req := restc.Get("users/1").
    SetResponseType(&User{}).
    SetErrorRespType(&APIError{})

resp, err := client.Execute(req)
if err != nil {
    log.Fatal(err)
}

if resp.IsError() {
    apiErr := resp.Content().(*APIError)
    fmt.Printf("Error %d: %s\n", apiErr.Status, apiErr.Message)
}
Authentication
// Bearer token (default scheme)
req := restc.Get("users").
    SetAuthToken("your-jwt-token")

// Custom auth scheme
req := restc.Get("users").
    SetAuthScheme("Basic").
    SetAuthToken(base64EncodedCredentials)
Query parameters
req := restc.Get("users").
    SetQueryParam("page", "1").
    SetQueryParam("limit", "20").
    SetQueryParams(map[string]string{
        "sort":  "name",
        "order": "asc",
    })
Cookies
req := restc.Get("users").
    SetCookie(&http.Cookie{
        Name:  "session",
        Value: "abc123",
    })
Context support
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

resp, err := client.ExecuteWithContext(ctx, req)
if err != nil {
    if errors.Is(err, context.DeadlineExceeded) {
        log.Println("Request timed out")
    }
}
Custom parsers
client.SetParseResponse(func(request *restc.Request, response *restc.Response) (any, error) {
    // Custom parsing logic
    return myCustomParser(response.Bytes())
})

client.SetParseError(func(request *restc.Request, response *restc.Response) (any, error) {
    // Custom error parsing logic (supports HTML text extraction)
    return restc.DefaultParseError(request, response)
})
Multipart form data & file upload
// Form fields only
req := restc.Post("upload").
    SetFormData(map[string]string{
        "title": "My Document",
        "desc":  "A test file",
    })

// With file from disk
req := restc.Post("upload").
    SetFormData(map[string]string{"title": "Avatar"}).
    SetFile("photo", "/path/photo.jpg")

// With file from io.Reader
req := restc.Post("upload").
    SetFormData(map[string]string{"id": "123"}).
    SetFileReader("document", "report.pdf", pdfReader)

// Multiple files
req := restc.Post("upload").
    SetFileReader("doc1", "a.txt", readerA).
    SetFileReader("doc2", "b.txt", readerB)
URL-encoded form data
req := restc.Post("login").
    SetFormURLEncoded(map[string]string{
        "username": "john",
        "password": "secret",
    })
Middleware
// Logging middleware
client.UseMiddleware(func(req *restc.Request, next func(req *restc.Request) (*restc.Response, error)) (*restc.Response, error) {
    start := time.Now()
    resp, err := next(req)
    log.Printf("[%s] %s %d (%s)", req.String(), resp.Status(), resp.StatusCode(), time.Since(start))
    return resp, err
})

// Short-circuit middleware (skip execution)
client.UseMiddleware(func(req *restc.Request, next func(req *restc.Request) (*restc.Response, error)) (*restc.Response, error) {
    if req.GetAuthToken() == "" {
        return nil, errors.New("missing auth token")
    }
    return next(req)
})

// Multiple middlewares execute in order (onion model)
client.UseMiddleware(loggingMiddleware, tracingMiddleware, metricsMiddleware)
Recovery middleware

The recovery middleware catches panics from downstream middlewares and the request execution, preventing the process from crashing.

// Recovery must be registered FIRST to protect the entire chain
client.UseMiddleware(recovery.Handler())
client.UseMiddleware(loggingMiddleware)
client.UseMiddleware(metricsMiddleware)

// With custom logger
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
client.UseMiddleware(recovery.NewRecoveryMiddlewareWith(logger).Handler())

When a panic is caught, the middleware logs the error with stack trace and returns a "panic recovered: ..." error.

Prometheus metrics middleware

The prometheus middleware collects request metrics and exposes them for Prometheus scraping. Three metrics are recorded:

  • <prefix>_requests_total — counter with method and status_code labels
  • <prefix>_request_duration_seconds — histogram with method and status_code labels
  • <prefix>_requests_in_flight — gauge of currently executing requests

The default prefix is "restc". Use an empty string "" to keep the default.

import "github.com/alex-cos/restc/middleware"

// Automatic registration with the default prometheus registry
metrics := middleware.NewPrometheusMetrics("")
client.UseMiddleware(metrics.Handler())

// With a custom registry (useful in tests)
reg := prometheus.NewRegistry()
metrics := middleware.NewPrometheusMetricsWith("myapp", reg)
client.UseMiddleware(metrics.Handler())
Redirect policy
// Block all redirects (stop at first 3xx)
client.SetRedirectPolicy(restc.NoRedirect)

// Follow redirects (default behavior)
client.SetRedirectPolicy(restc.FollowRedirects)

// Limit the number of sucessive redirects
client.SetMaxRedirects(3)

Response API

resp, _ := client.Execute(req)

resp.StatusCode()      // int - HTTP status code
resp.Status()          // string - "200 OK"
resp.IsError()         // bool - true if status >= 400
resp.String()          // string - response body as string
resp.Bytes()           // []byte - raw response body
resp.Content()         // any - parsed content (via SetResponseType/SetErrorRespType)
resp.Proto()           // string - "HTTP/2.0"
resp.Header()          // http.Header - response headers
resp.Cookies()         // []*http.Cookie - response cookies
resp.ContentType()     // string - Content-Type header
resp.ReceivedAt()      // time.Time - when response was received

Constants

Content types
restc.TypeApplicationJSON           // "application/json"
restc.TypeApplicationXML            // "application/xml"
restc.TypeApplicationFormURLEncoded // "application/x-www-form-urlencoded"
restc.TypeMultipartFormData         // "multipart/form-data"
restc.TypeTextHTML                  // "text/html"
restc.TypeTextPLAIN                 // "text/plain"
restc.TypeTextXML                   // "text/xml"
// ... and many more
HTTP headers
restc.ContentType     // "Content-Type"
restc.Authorization   // "Authorization"
restc.Accept          // "Accept"
restc.UserAgent       // "User-Agent"
// ... and many more
HTTP methods
restc.MethodGet
restc.MethodPost
restc.MethodPut
restc.MethodPatch
restc.MethodDelete
restc.MethodHead
restc.MethodOptions
restc.MethodTrace

Retry mechanism

Retries use exponential backoff with configurable wait times:

client.SetRetryCount(3)                          // 3 retry attempts (4 total)
client.SetRetryWaitTime(100 * time.Millisecond)  // initial wait
client.SetRetryMaxWaitTime(2 * time.Second)      // max wait between retries

The retry mechanism only retries on transient errors (network timeouts, dial errors). Non-retriable errors (context cancellation, invalid URL scheme, parse errors) fail immediately.

Security

  • Only http and https URL schemes are accepted
  • Response body size can be limited with SetMaxResponseSize to prevent memory exhaustion

Documentation

Index

Constants

View Source
const (
	// DefaultTimeout is the default timeout for HTTP requests.
	DefaultTimeout = 12 * time.Second
	// DefaultWaitTime is the default wait time between retries.
	DefaultWaitTime = time.Duration(100) * time.Millisecond
	// DefaultMaxWaitTime is the maximum wait time between retries.
	DefaultMaxWaitTime = time.Duration(2000) * time.Millisecond
	// DefaultUserAgent is the default "User-Agent" value.
	DefaultUserAgent = "restc/1.0"
)
View Source
const (
	// Application types.
	TypeApplicationAtomXML             = "application/atom+xml"
	TypeApplicationCBOR                = "application/cbor"
	TypeApplicationEDI                 = "application/EDI-X12"
	TypeApplicationEDIFACT             = "application/EDIFACT"
	TypeApplicationFormURLEncoded      = "application/x-www-form-urlencoded"
	TypeApplicationGeoJSON             = "application/geo+json"
	TypeApplicationGZIP                = "application/gzip"
	TypeApplicationHALJSON             = "application/hal+json"
	TypeApplicationJSON                = "application/json"
	TypeApplicationJSONPatch           = "application/json-patch+json"
	TypeApplicationJSONProblem         = "application/problem+json"
	TypeApplicationJavascript          = "application/javascript"
	TypeApplicationLDJSON              = "application/ld+json"
	TypeApplicationMSAccess            = "application/msaccess"
	TypeApplicationMSWord              = "application/msword"
	TypeApplicationMsgPack             = "application/msgpack"
	TypeApplicationNDJSON              = "application/x-ndjson"
	TypeApplicationOctetStream         = "application/octet-stream"
	TypeApplicationOGG                 = "application/ogg"
	TypeApplicationOpenXMLSheet        = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
	TypeApplicationOpenXMLPresentation = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
	TypeApplicationOpenXMLWord         = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
	TypeApplicationPDF                 = "application/pdf"
	TypeApplicationProtobuf            = "application/x-protobuf"
	TypeApplicationRAR                 = "application/vnd.rar"
	TypeApplicationRTF                 = "application/rtf"
	TypeApplicationSVGXML              = "application/svg+xml"
	TypeApplicationTAR                 = "application/x-tar"
	TypeApplicationTypescript          = "application/typescript"
	TypeApplicationWASM                = "application/wasm"
	TypeApplicationXHTML               = "application/xhtml+xml"
	TypeApplicationXML                 = "application/xml"
	TypeApplicationXMLDTD              = "application/xml-dtd"
	TypeApplicationXMLProblem          = "application/problem+xml"
	TypeApplicationYAML                = "application/x-yaml"
	TypeApplicationZIP                 = "application/zip"
	TypeApplication7ZIP                = "application/x-7z-compressed"

	// Multipart types.
	TypeMultipartAlternative = "multipart/alternative"
	TypeMultipartFormData    = "multipart/form-data"
	TypeMultipartMixed       = "multipart/mixed"
	TypeMultipartRelated     = "multipart/related"

	// Text types.
	TypeTextCalendar   = "text/calendar"
	TypeTextCSS        = "text/css"
	TypeTextCSV        = "text/csv"
	TypeTextHTML       = "text/html"
	TypeTextJavascript = "text/javascript"
	TypeTextMarkdown   = "text/markdown"
	TypeTextPLAIN      = "text/plain"
	TypeTextVCard      = "text/vcard"
	TypeTextXML        = "text/xml"
	TypeTextYAML       = "text/yaml"

	// Image types.
	TypeImageAPNG   = "image/apng"
	TypeImageAVIF   = "image/avif"
	TypeImageBMP    = "image/bmp"
	TypeImageGIF    = "image/gif"
	TypeImageICO    = "image/x-icon"
	TypeImageJPG    = "image/jpeg"
	TypeImagePNG    = "image/png"
	TypeImageSVGXML = "image/svg+xml"
	TypeImageTIFF   = "image/tiff"
	TypeImageWEBP   = "image/webp"

	// Video types.
	TypeVideoAVI       = "video/x-msvideo"
	TypeVideoFLV       = "video/x-flv"
	TypeVideoM3U8      = "application/x-mpegURL"
	TypeVideoMP4       = "video/mp4"
	TypeVideoMPEG      = "video/mpeg"
	TypeVideoOGG       = "video/ogg"
	TypeVideoQUICKTIME = "video/quicktime"
	TypeVideoTS        = "video/MP2T"
	TypeVideoWEBM      = "video/webm"
	TypeVideoWMV       = "video/x-ms-wmv"

	// Audio types.
	TypeAudioAAC  = "audio/aac"
	TypeAudioFLAC = "audio/flac"
	TypeAudioMIDI = "audio/midi"
	TypeAudioMP3  = "audio/mpeg"
	TypeAudioMP4  = "audio/mp4"
	TypeAudioOGG  = "audio/ogg"
	TypeAudioOPUS = "audio/opus"
	TypeAudioWAV  = "audio/x-wav"
	TypeAudioWEBM = "audio/webm"
	TypeAudioWMV  = "audio/x-ms-wma"

	// Font types.
	TypeFontOTF   = "font/otf"
	TypeFontTTF   = "font/ttf"
	TypeFontWOFF  = "font/woff"
	TypeFontWOFF2 = "font/woff2"
)

Content type constants for various MIME types.

View Source
const (
	// Accept is the media types that are acceptable.
	Accept = "Accept"
	// AcceptCharset is the character sets that are acceptable.
	AcceptCharset = "Accept-Charset"
	// AcceptEncoding is the encodings that are acceptable.
	AcceptEncoding = "Accept-Encoding"
	// AcceptLanguage is the natural languages that are acceptable.
	AcceptLanguage = "Accept-Language"
	// AcceptDatetime is the acceptable datetime.
	AcceptDatetime = "Accept-Datetime"
	// Authorization is the credentials for authenticating the user agent.
	Authorization = "Authorization"
	// CacheControl is the cache control directives.
	CacheControl = "Cache-Control"
	// Connection controls whether the network connection stays open.
	Connection = "Connection"
	// ContentLength is the size of the request body in bytes.
	ContentLength = "Content-Length"
	// ContentMD5 is the MD5 checksum of the request body.
	ContentMD5 = "Content-MD5"
	// ContentType is the media type of the request body.
	ContentType = "Content-Type"
	// Cookie contains stored cookies.
	Cookie = "Cookie"
	// Date is the date and time at which the message was sent.
	Date = "Date"
	// DoNotTrack is the user's tracking preference.
	DoNotTrack = "DNT"
	// Expect indicates expectations that need to be fulfilled.
	Expect = "Expect"
	// Forwarded provides information about the original request.
	Forwarded = "Forwarded"
	// From is the email address of the user.
	From = "From"
	// Host specifies the host and port of the server.
	Host = "Host"
	// IfMatch is the entity tag.
	IfMatch = "If-Match"
	// IfModifiedSince is the modification date constraint.
	IfModifiedSince = "If-Modified-Since"
	// IfNoneMatch is the entity tag condition.
	IfNoneMatch = "If-None-Match"
	// IfRange is the byte range request.
	IfRange = "If-Range"
	// IfUnmodifiedSince is the modification date constraint.
	IfUnmodifiedSince = "If-Unmodified-Since"
	// MaxForwards limits the number of proxies or gateways.
	MaxForwards = "Max-Forwards"
	// Origin indicates the origin of the request.
	Origin = "Origin"
	// Pragma is the implementation-specific directives.
	Pragma = "Pragma"
	// ProxyAuthorization contains credentials for the proxy.
	ProxyAuthorization = "Proxy-Authorization"
	// Range indicates the byte range to be sent.
	Range = "Range"
	// Referer is the address of the previous web page.
	Referer = "Referer"
	// TE indicates the transfer encodings the client is willing to accept.
	TE = "TE"
	// Trailer indicates that the header provides additional fields.
	Trailer = "Trailer"
	// TransferEncoding is the form of encoding used to transfer the payload.
	TransferEncoding = "Transfer-Encoding"
	// UserAgent contains information about the user agent.
	UserAgent = "User-Agent"
	// Via indicates intermediate proxies or gateways.
	Via = "Via"
	// Warning contains warnings about the request.
	Warning = "Warning"

	// AcceptPatch is the patch content types the server supports.
	AcceptPatch = "Accept-Patch"
	// AcceptRanges indicates unit types the server supports.
	AcceptRanges = "Accept-Ranges"
	// Age is the time the object was in a proxy cache.
	Age = "Age"
	// Allow lists the methods allowed for the requested URL.
	Allow = "Allow"
	// AltSvc is the alternative services.
	AltSvc = "Alt-Svc"
	// ContentDisposition indicates if content is inline or attachment.
	ContentDisposition = "Content-Disposition"
	// ContentEncoding is the encoding transformations applied.
	ContentEncoding = "Content-Encoding"
	// ContentLanguage describes the language(s) of the payload.
	ContentLanguage = "Content-Language"
	// ContentLocation indicates the location of the resource.
	ContentLocation = "Content-Location"
	// ContentRange indicates where in the full payload the partial content applies.
	ContentRange = "Content-Range"
	// ETag is the identifier for a specific version of a resource.
	ETag = "ETag"
	// Expires is the date/time after which the response is stale.
	Expires = "Expires"
	// LastModified is the date/time the resource was last modified.
	LastModified = "Last-Modified"
	// Link provides references to other resources.
	Link = "Link"
	// Location is used in redirection or when a resource has been created.
	Location = "Location"
	// P3P is the platform for privacy preferences.
	P3P = "P3P"
	// ProxyAuthenticate is the authentication method for the proxy.
	ProxyAuthenticate = "Proxy-Authenticate"
	// Refresh is automatically refresh the page.
	Refresh = "Refresh"
	// RetryAfter indicates the client should wait before retrying the request.
	RetryAfter = "Retry-After"
	// Server provides information about the server software.
	Server = "Server"
	// SetCookie contains cookies to be sent back to the server.
	SetCookie = "Set-Cookie"
	// StrictTransportSecurity forces secure communication.
	StrictTransportSecurity = "Strict-Transport-Security"
	// Upgrade is the protocol to switch to.
	Upgrade = "Upgrade"
	// Vary indicates the fields that vary in the response.
	Vary = "Vary"
	// WWWAuthenticate is the authentication method for the resource.
	WWWAuthenticate = "WWW-Authenticate"

	// AccessControlAllowCredentials indicates if credentials can be exposed.
	AccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	// AccessControlAllowHeaders indicates which headers can be used.
	AccessControlAllowHeaders = "Access-Control-Allow-Headers"
	// AccessControlAllowMethods indicates which methods can be used.
	AccessControlAllowMethods = "Access-Control-Allow-Methods"
	// AccessControlAllowOrigin indicates if the resource can be accessed.
	AccessControlAllowOrigin = "Access-Control-Allow-Origin"
	// AccessControlExposeHeaders indicates which headers can be exposed.
	AccessControlExposeHeaders = "Access-Control-Expose-Headers"
	// AccessControlMaxAge indicates how long the preflight can be cached.
	AccessControlMaxAge = "Access-Control-Max-Age"
	// AccessControlRequestHeaders indicates which headers can be used.
	AccessControlRequestHeaders = "Access-Control-Request-Headers"
	// AccessControlRequestMethod indicates which method can be used.
	AccessControlRequestMethod = "Access-Control-Request-Method"
	// ClearSiteData is the clearance of browser data.
	ClearSiteData = "Clear-Site-Data"
	// ContentSecurityPolicy restricts where resources can be loaded from.
	ContentSecurityPolicy = "Content-Security-Policy"
	// ContentSecurityPolicyReportOnly restricts where resources can be loaded from.
	ContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	// CrossOriginEmbedderPolicy controls embedding of cross-origin resources.
	CrossOriginEmbedderPolicy = "Cross-Origin-Embedder-Policy"
	// CrossOriginOpenerPolicy controls access to the browsing context.
	CrossOriginOpenerPolicy = "Cross-Origin-Opener-Policy"
	// CrossOriginResourcePolicy controls access to the resource.
	CrossOriginResourcePolicy = "Cross-Origin-Resource-Policy"
	// NEL is the network error logging.
	NEL = "NEL"
	// PermissionsPolicy controls which features can be used.
	PermissionsPolicy = "Permissions-Policy"
	// ReferrerPolicy indicates which referrer to send.
	ReferrerPolicy = "Referrer-Policy"
	// ReportTo is the reporting endpoints.
	ReportTo = "Report-To"
	// TimingAllowOrigin indicates which origins can see timing data.
	TimingAllowOrigin = "Timing-Allow-Origin"

	// SecCHUA is the client hints user agent architecture.
	SecCHUA = "Sec-CH-UA"
	// SecCHUAMobile is the client hints user agent mobile.
	SecCHUAMobile = "Sec-CH-UA-Mobile"
	// SecCHUAPlatform is the client hints user agent platform.
	SecCHUAPlatform = "Sec-CH-UA-Platform"
	// SecFetchDest is the fetch destination.
	SecFetchDest = "Sec-Fetch-Dest"
	// SecFetchMode is the fetch mode.
	SecFetchMode = "Sec-Fetch-Mode"
	// SecFetchSite is the fetch site.
	SecFetchSite = "Sec-Fetch-Site"
	// SecFetchUser is the fetch user preference.
	SecFetchUser = "Sec-Fetch-User"
	// SecGPC is the global privacy control flag.
	SecGPC = "Sec-GPC"
	// SaveData is the save data preference.
	SaveData = "Save-Data"
	// UpgradeInsecureRequests is the upgrade insecure requests preference.
	UpgradeInsecureRequests = "Upgrade-Insecure-Requests"

	// XAspNetVersion is the ASP.NET version.
	XAspNetVersion = "X-AspNet-Version"
	// XAspNetMvcVersion is the ASP.NET MVC version.
	XAspNetMvcVersion = "X-AspNetMvc-Version"
	// XContentSecurityPolicy is the content security policy.
	XContentSecurityPolicy = "X-Content-Security-Policy"
	// XContentTypeOptions prevents sniffing the content type.
	XContentTypeOptions = "X-Content-Type-Options"
	// XCSRFToken is the CSRF token.
	XCSRFToken = "X-CSRF-Token" //nolint:gosec
	// XCorrelationId is the correlation ID.
	XCorrelationId = "X-Correlation-Id"
	// XDNSPrefetchControl controls DNS prefetching.
	XDNSPrefetchControl = "X-DNS-Prefetch-Control"
	// XDownloadOptions indicates how to handle the download.
	XDownloadOptions = "X-Download-Options"
	// XForwardedFor is the original client IP address.
	XForwardedFor = "X-Forwarded-For"
	// XForwardedProto is the original protocol.
	XForwardedProto = "X-Forwarded-Proto"
	// XFrameOptions protects against clickjacking.
	XFrameOptions = "X-Frame-Options"
	// XHTTPMethodOverride overrides the HTTP method.
	XHTTPMethodOverride = "X-HTTP-Method-Override"
	// XPermittedCrossDomainPolicies controls cross-domain requests.
	XPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies"
	// XPoweredBy indicates the technology supporting the server.
	XPoweredBy = "X-Powered-By"
	// XRealIP is the real client IP address.
	XRealIP = "X-Real-IP"
	// XRequestedWith is the XMLHttpRequest header.
	XRequestedWith = "X-Requested-With"
	// XRequestId is the request ID.
	XRequestId = "X-Request-Id"
	// XRobotsTag controls indexing by robots.
	XRobotsTag = "X-Robots-Tag"
	// XRatelimitLimit is the rate limit maximum requests.
	XRatelimitLimit = "X-Ratelimit-Limit"
	// XRatelimitRemaining is the rate limit remaining requests.
	XRatelimitRemaining = "X-Ratelimit-Remaining"
	// XRatelimitReset is the rate limit reset time.
	XRatelimitReset = "X-Ratelimit-Reset"
	// XTraceId is the trace ID.
	XTraceId = "X-Trace-Id"
	// XUACompatible indicates the user agent compatibility.
	XUACompatible = "X-UA-Compatible"
	// XXSSProtection is the XSS filter.
	XXSSProtection = "X-XSS-Protection"
)

Standard HTTP header constants.

View Source
const (
	// MethodGet HTTP method.
	MethodGet = "GET"
	// MethodPost HTTP method.
	MethodPost = "POST"
	// MethodPut HTTP method.
	MethodPut = "PUT"
	// MethodDelete HTTP method.
	MethodDelete = "DELETE"
	// MethodPatch HTTP method.
	MethodPatch = "PATCH"
	// MethodHead HTTP method.
	MethodHead = "HEAD"
	// MethodOptions HTTP method.
	MethodOptions = "OPTIONS"
	// MethodTrace HTTP method.
	MethodTrace = "TRACE"
)

HTTP method constants.

Variables

View Source
var (
	// ErrMaxRedirects is returned when the maximum number of redirects is exceeded.
	ErrMaxRedirects = errors.New("maximum redirects exceeded")
	// ErrHTTPRequest is returned when an HTTP request fails.
	ErrHTTPRequest = errors.New("failed to execute HTTP request")
	// ErrReadBody is returned when reading the response body fails.
	ErrReadBody = errors.New("failed to read body response")
	// ErrParseJSON is returned when parsing a JSON response fails.
	ErrParseJSON = errors.New("failed to parse JSON response")
	// ErrParseXML is returned when parsing an XML response fails.
	ErrParseXML = errors.New("failed to parse XML response")
	// ErrParseHTML is returned when parsing an HTML response fails.
	ErrParseHTML = errors.New("failed to parse HTML response")
	// ErrUnexpectedType is returned when the response content type is not supported.
	ErrUnexpectedType = errors.New("unexpected response type")
)

Client errors.

View Source
var (
	// ErrInvalidMethod is returned when an invalid HTTP method is used.
	ErrInvalidMethod = errors.New("invalid HTTP method")
	// ErrUnsupportedScheme is returned when an unsupported URL scheme is used.
	ErrUnsupportedScheme = errors.New("unsupported URL scheme")
	// ErrUnsupportedBody is returned when an unsupported body type is used.
	ErrUnsupportedBody = errors.New("unsupported body type")
	// ErrInvalidEntryPoint is returned when the entry point URL is invalid.
	ErrInvalidEntryPoint = errors.New("failed to parse given entry point")
	// ErrBuildRequest is returned when building the HTTP request fails.
	ErrBuildRequest = errors.New("failed to build HTTP request")
	// ErrMultipart is returned when a multipart form error occurs.
	ErrMultipart = errors.New("multipart form error")
)

Request errors.

Functions

func DefaultParseError

func DefaultParseError(request *Request, response *Response) (any, error)

DefaultParseError is the default function for parsing error responses (4xx, 5xx). It supports JSON, XML, and HTML content types.

func DefaultParseResponse

func DefaultParseResponse(request *Request, response *Response) (any, error)

DefaultParseResponse is the default function for parsing successful responses. It supports JSON and XML content types.

func NewIpv4Transport added in v1.5.0

func NewIpv4Transport(transports ...*http.Transport) *http.Transport

NewIpv4Transport creates an http.Transport that uses only IPv4 connections.

func NewIpv6Transport added in v1.5.0

func NewIpv6Transport(transports ...*http.Transport) *http.Transport

NewIpv6Transport creates an http.Transport that uses only IPv6 connections.

Types

type Client

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

Client is an HTTP client for making REST API requests. It provides methods for configuring and executing HTTP requests.

func New

func New(entryPoint string, opts ...Option) *Client

New creates a new Client with the given entry point URL and options. The entry point is used as the base URL for relative paths in requests.

func NewWithClient

func NewWithClient(entryPoint string, httpClient HTTPClient, opts ...Option) *Client

NewWithClient creates a new Client with the given entry point URL, custom HTTP client, and options. This allows using a custom http.Client configuration.

func (*Client) Execute

func (c *Client) Execute(request *Request) (*Response, error)

Execute sends the HTTP request and returns the response. It uses context.Background() for the request context.

func (*Client) ExecuteWithContext

func (c *Client) ExecuteWithContext(ctx context.Context, request *Request) (*Response, error)

ExecuteWithContext sends the HTTP request with the given context and returns the response.

func (*Client) SetContentType added in v1.5.2

func (c *Client) SetContentType(contentType string)

SetContentType sets the default Content-Type header for all requests.

func (*Client) SetEntryPoint

func (c *Client) SetEntryPoint(entryPoint string)

SetEntryPoint sets the base URL for requests.

func (*Client) SetHeader

func (c *Client) SetHeader(header, value string)

SetHeader sets a default header to be sent with all requests.

func (*Client) SetHeaders

func (c *Client) SetHeaders(headers map[string]string)

SetHeaders sets multiple default headers to be sent with all requests.

func (*Client) SetMaxRedirects

func (c *Client) SetMaxRedirects(maximum int)

SetMaxRedirects sets the maximum number of redirects to follow.

func (*Client) SetMaxResponseSize

func (c *Client) SetMaxResponseSize(size int64)

SetMaxResponseSize sets the maximum response body size in bytes. If the response body exceeds this size, it will be truncated.

func (*Client) SetParseError

func (c *Client) SetParseError(parseError ParseResponse)

SetParseError sets the function to parse error responses.

func (*Client) SetParseResponse

func (c *Client) SetParseResponse(parseResponse ParseResponse)

SetParseResponse sets the function to parse successful responses.

func (*Client) SetRedirectPolicy

func (c *Client) SetRedirectPolicy(policy RedirectPolicy)

SetRedirectPolicy sets the redirect policy (FollowRedirects or NoRedirect).

func (*Client) SetRetryCount

func (c *Client) SetRetryCount(count int)

SetRetryCount sets the number of retries on failure.

func (*Client) SetRetryMaxWaitTime

func (c *Client) SetRetryMaxWaitTime(wait time.Duration)

SetRetryMaxWaitTime sets the maximum wait time between retries.

func (*Client) SetRetryWaitTime

func (c *Client) SetRetryWaitTime(wait time.Duration)

SetRetryWaitTime sets the wait time between retries.

func (*Client) SetTimeout

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

SetTimeout sets the timeout for HTTP requests.

func (*Client) SetTransport added in v1.5.2

func (c *Client) SetTransport(transport *http.Transport)

SetTransport sets the transport layer for the client.

func (*Client) UseMiddleware

func (c *Client) UseMiddleware(middleware ...Middleware)

UseMiddleware adds middleware to be executed before each request.

type ClientMiddleware

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

ClientMiddleware manages a chain of middleware to be executed for each request.

func NewClientMiddleware

func NewClientMiddleware() *ClientMiddleware

NewClientMiddleware creates a new empty ClientMiddleware.

func (*ClientMiddleware) Execute

func (cm *ClientMiddleware) Execute(req *Request, next HandlerFunc) (*Response, error)

Execute runs the middleware chain with the given request and final handler.

func (*ClientMiddleware) Use

func (cm *ClientMiddleware) Use(middleware ...Middleware)

Use adds middleware to the middleware chain.

type FileUpload

type FileUpload struct {
	FieldName string
	FileName  string
	Reader    io.Reader
}

FileUpload represents a file to be uploaded in a multipart request.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient interface represents an HTTP client capable of executing requests.

type HandlerFunc

type HandlerFunc func(req *Request) (*Response, error)

HandlerFunc is a function that handles an HTTP request and returns a response or error.

type Middleware

type Middleware func(req *Request, next HandlerFunc) (*Response, error)

Middleware is a function that intercepts the request/response flow. It can modify the request before passing it to the next handler, or modify the response after receiving it.

type Option added in v1.5.0

type Option func(*Client)

Option is a function that configures a Client. It is used with New or NewWithClient to configure the client.

func WithContentType added in v1.5.2

func WithContentType(contentType string) Option

WithContentType sets the default Content-Type header for all requests.

func WithHeader added in v1.5.0

func WithHeader(header, value string) Option

WithHeader sets a default header to be sent with all requests.

func WithHeaders added in v1.5.0

func WithHeaders(headers map[string]string) Option

WithHeaders sets multiple default headers to be sent with all requests.

func WithMTLS added in v1.5.1

func WithMTLS(caCertFile, certFile, keyFile string) Option

WithMTLS configures the mutual TLS authentication with preserving the actual transport layer.

func WithMaxRedirects added in v1.5.0

func WithMaxRedirects(maximum int) Option

WithMaxRedirects sets the maximum number of redirects to follow.

func WithMaxResponseSize added in v1.5.0

func WithMaxResponseSize(size int64) Option

WithMaxResponseSize sets the maximum response body size in bytes.

func WithOnlyIPv4 added in v1.5.1

func WithOnlyIPv4() Option

WithOnlyIPv4 configures the client to use only IPv4.

func WithOnlyIPv6 added in v1.5.0

func WithOnlyIPv6() Option

WithOnlyIPv6 configures the client to use only IPv6.

func WithParseError added in v1.5.0

func WithParseError(parseError ParseResponse) Option

WithParseError sets the function to parse error responses.

func WithParseResponse added in v1.5.0

func WithParseResponse(parseResponse ParseResponse) Option

WithParseResponse sets the function to parse successful responses.

func WithProxy added in v1.5.1

func WithProxy(proxyURL, user, password string) Option

WithProxy configures the client to use the specified HTTP proxy. If user and password are provided, basic auth is added to the proxy URL.

func WithRedirectPolicy added in v1.5.0

func WithRedirectPolicy(policy RedirectPolicy) Option

WithRedirectPolicy sets the redirect policy.

func WithRetryCount added in v1.5.0

func WithRetryCount(count int) Option

WithRetryCount sets the number of retries on failure.

func WithRetryMaxWaitTime added in v1.5.0

func WithRetryMaxWaitTime(wait time.Duration) Option

WithRetryMaxWaitTime sets the maximum wait time between retries.

func WithRetryWaitTime added in v1.5.0

func WithRetryWaitTime(wait time.Duration) Option

WithRetryWaitTime sets the initial wait time between retries.

func WithTLSConfig added in v1.5.1

func WithTLSConfig(config *tls.Config) Option

WithTLSConfig accepts a complete TLS configuration with preserving the actual transport layer.

func WithTimeout added in v1.5.0

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the timeout for HTTP requests.

func WithTransportPool added in v1.5.1

func WithTransportPool(
	maxIdleConnsPerHost int,
	maxIdleConns int,
	maxConnsPerHost int,
	idleConnTimeout time.Duration,
) Option

WithTransportPool configures the HTTP transport connection pool settings. maxIdleConnsPerHost: max idle connections per host (default: 2) maxIdleConns: total max idle connections (default: 100) maxConnsPerHost: max connections per host, 0 = unlimited idleConnTimeout: how long idle connections stay in the pool.

type ParseResponse

type ParseResponse func(request *Request, response *Response) (any, error)

ParseResponse is a function that parses an HTTP response into a custom type.

type RedirectConfig

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

RedirectConfig holds configuration for redirect handling.

type RedirectPolicy

type RedirectPolicy int

RedirectPolicy defines the behavior for handling HTTP redirects.

const (
	// FollowRedirects indicates that the client should follow redirects.
	FollowRedirects RedirectPolicy = iota
	// NoRedirect indicates that the client should not follow redirects.
	NoRedirect
)

type Request

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

Request represents an HTTP request with method, URL, headers, body, and other options. It uses a fluent API with method chaining for configuration.

func Delete

func Delete(url string) *Request

Delete creates a new DELETE request for the given URL.

func Get

func Get(url string) *Request

Get creates a new GET request for the given URL.

func Head(url string) *Request

Head creates a new HEAD request for the given URL.

func NewRequest

func NewRequest(method, url string) *Request

NewRequest creates a new Request with the given HTTP method and URL.

func Options

func Options(url string) *Request

Options creates a new OPTIONS request for the given URL.

func Patch

func Patch(url string) *Request

Patch creates a new PATCH request for the given URL.

func Post

func Post(url string) *Request

Post creates a new POST request for the given URL.

func Put

func Put(url string) *Request

Put creates a new PUT request for the given URL.

func Trace

func Trace(url string) *Request

Trace creates a new TRACE request for the given URL.

func (*Request) AddQueryParam

func (r *Request) AddQueryParam(param, value string) *Request

AddQueryParam adds a query parameter to the request URL. Multiple values can be added for the same parameter. Returns the Request for method chaining.

func (*Request) Clone

func (r *Request) Clone() *Request

Clone creates a deep copy of the request. Note: FileUpload Readers are shared between the original and the clone because io.Reader cannot be duplicated. Consuming the reader on one request will affect the other.

func (*Request) GetCreatedAt added in v1.5.1

func (r *Request) GetCreatedAt() time.Time

GetCreatedAt returns the date and time of the creation.

func (*Request) GetErrorRespType

func (r *Request) GetErrorRespType() any

GetErrorRespType returns the type for unmarshaling error responses.

func (*Request) GetResponseType

func (r *Request) GetResponseType() any

GetResponseType returns the type for unmarshaling successful responses.

func (*Request) Method

func (r *Request) Method() string

Method returns the HTTP method of the request.

func (*Request) SetAuthScheme

func (r *Request) SetAuthScheme(scheme string) *Request

SetAuthScheme sets the authentication scheme (e.g., "Bearer", "Basic"). Returns the Request for method chaining.

func (*Request) SetAuthToken

func (r *Request) SetAuthToken(authToken string) *Request

SetAuthToken sets the authentication token for the request. The token will be sent in the Authorization header using the specified auth scheme. Returns the Request for method chaining.

func (*Request) SetBody

func (r *Request) SetBody(body any) *Request

SetBody sets the request body. Supports string, []byte, io.Reader, or any value that can be JSON marshaled. Returns the Request for method chaining.

func (*Request) SetContentType

func (r *Request) SetContentType(ct string) *Request

SetContentType sets the Content-Type header of the request. Returns the Request for method chaining.

func (*Request) SetCookie

func (r *Request) SetCookie(hc *http.Cookie) *Request

SetCookie adds a cookie to the request. Returns the Request for method chaining.

func (*Request) SetCookies

func (r *Request) SetCookies(rs []*http.Cookie) *Request

SetCookies adds multiple cookies to the request. Returns the Request for method chaining.

func (*Request) SetErrorRespType

func (r *Request) SetErrorRespType(responseType any) *Request

SetErrorRespType sets the type to unmarshal error responses into. Returns the Request for method chaining.

func (*Request) SetFile

func (r *Request) SetFile(fieldName, filePath string) *Request

SetFile adds a file from a file path to the multipart form. fieldName is the form field name and filePath is the path to the file. Returns the Request for method chaining.

func (*Request) SetFileReader

func (r *Request) SetFileReader(fieldName, fileName string, reader io.Reader) *Request

SetFileReader adds a file from an io.Reader to the multipart form. fieldName is the form field name and fileName is the file name. Returns the Request for method chaining.

func (*Request) SetFormData

func (r *Request) SetFormData(data map[string]string) *Request

SetFormData sets form data fields for multipart form submission. Returns the Request for method chaining.

func (*Request) SetFormURLEncoded

func (r *Request) SetFormURLEncoded(data map[string]string) *Request

SetFormURLEncoded sets the body as URL-encoded form data. Returns the Request for method chaining.

func (*Request) SetHeader

func (r *Request) SetHeader(header, value string) *Request

SetHeader sets a header for the request. Returns the Request for method chaining.

func (*Request) SetHeaders

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

SetHeaders sets multiple headers for the request. Returns the Request for method chaining.

func (*Request) SetMethod

func (r *Request) SetMethod(m string) *Request

SetMethod sets the HTTP method of the request. Returns the Request for method chaining.

func (*Request) SetQueryParam

func (r *Request) SetQueryParam(param, value string) *Request

SetQueryParam sets a query parameter, replacing any existing value. Returns the Request for method chaining.

func (*Request) SetQueryParams

func (r *Request) SetQueryParams(params map[string]string) *Request

SetQueryParams sets multiple query parameters. Returns the Request for method chaining.

func (*Request) SetQueryParamsFromValues

func (r *Request) SetQueryParamsFromValues(params _url.Values) *Request

SetQueryParamsFromValues sets query parameters from url.Values. Returns the Request for method chaining.

func (*Request) SetResponseType

func (r *Request) SetResponseType(responseType any) *Request

SetResponseType sets the type to unmarshal successful responses into. Returns the Request for method chaining.

func (*Request) SetTimeout

func (r *Request) SetTimeout(timeout time.Duration) *Request

SetTimeout sets a timeout for this specific request. Returns the Request for method chaining.

func (*Request) SetURL

func (r *Request) SetURL(url string) *Request

SetURL sets the URL of the request. Returns the Request for method chaining.

func (*Request) String

func (r *Request) String() string

String returns a string representation of the request.

func (*Request) URL

func (r *Request) URL() string

URL returns the URL of the request.

type Response

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

Response represents an HTTP response with status, headers, and body. It wraps the standard library http.Response and provides additional functionality.

func NewResponse

func NewResponse(rawResponse *http.Response) *Response

NewResponse creates a new Response from an http.Response.

func (*Response) Bytes

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

Bytes returns the response body as bytes.

func (*Response) Content

func (r *Response) Content() any

Content returns the parsed response content. Content is available after successful parsing with DefaultParseResponse.

func (*Response) ContentType

func (r *Response) ContentType() string

ContentType returns the Content-Type header value.

func (*Response) Cookies

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

Cookies returns the cookies sent in the response.

func (*Response) Header

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

Header returns the response headers.

func (*Response) IsError

func (r *Response) IsError() bool

IsError returns true if the response status code is 400 or higher.

func (*Response) Proto

func (r *Response) Proto() string

Proto returns the protocol version (e.g., "HTTP/1.1").

func (*Response) ReceivedAt

func (r *Response) ReceivedAt() time.Time

ReceivedAt returns the time when the response was received.

func (*Response) Status

func (r *Response) Status() string

Status returns the status string from the response (e.g., "200 OK").

func (*Response) StatusCode

func (r *Response) StatusCode() int

StatusCode returns the HTTP status code (e.g., 200, 404).

func (*Response) String

func (r *Response) String() string

String returns the response body as a trimmed string.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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