Package Functions & Client Methods
Package-Level HTTP Methods
Send requests directly without creating a client. Uses a lazily-initialized default client internally.
Get
func Get(url string, options ...RequestOption) (*Result, error)Sends a GET request.
result, err := httpc.Get("https://api.example.com/data",
httpc.WithBearerToken(token),
httpc.WithQuery("page", 1),
)Post
func Post(url string, options ...RequestOption) (*Result, error)Sends a POST request.
result, err := httpc.Post("https://api.example.com/users",
httpc.WithJSON(map[string]any{"name": "test"}),
)Put / Patch / Delete / Head / Options
func Put(url string, options ...RequestOption) (*Result, error)
func Patch(url string, options ...RequestOption) (*Result, error)
func Delete(url string, options ...RequestOption) (*Result, error)
func Head(url string, options ...RequestOption) (*Result, error)
func Options(url string, options ...RequestOption) (*Result, error)Request
func Request(ctx context.Context, method, url string, options ...RequestOption) (*Result, error)Generic request method with context support for timeout and cancellation control.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
result, err := httpc.Request(ctx, "GET", "https://api.example.com/data")Client Methods
The Client interface provides the same HTTP methods as the package-level functions, plus a Request method that takes a context.
New
func New(cfg Config) (Client, error)Creates a new HTTP client. Pass a Config value (recommended: obtain one via DefaultConfig() or a preset function, then modify as needed). Returns an error for invalid configuration (e.g. invalid SecurityConfig.SSRFExemptCIDRs).
// Using default config (or call NewDefault() for the same effect)
client, err := httpc.New(httpc.DefaultConfig())
// Using a preset
client, err := httpc.New(httpc.SecureConfig())
// Using custom config
cfg := httpc.DefaultConfig()
cfg.Timeouts.Request = 60 * time.Second
client, err := httpc.New(cfg)NewDefault
func NewDefault() (Client, error)Convenience constructor, equivalent to New(DefaultConfig()). The recommended entry point for zero-configuration scenarios.
client, err := httpc.NewDefault()
defer func() { _ = client.Close() }()Client HTTP Methods
result, err := client.Get(url, options...)
result, err := client.Post(url, options...)
result, err := client.Put(url, options...)
result, err := client.Patch(url, options...)
result, err := client.Delete(url, options...)
result, err := client.Head(url, options...)
result, err := client.Options(url, options...)
result, err := client.Request(ctx, "GET", url, options...)Close
A Client interface method that releases the resources held by the client (connection pool, Transport). It must not be used after being called.
// Client interface method
Close() errorclient, _ := httpc.NewDefault()
defer client.Close()Default Client Management
SetDefaultClient
func SetDefaultClient(client Client) errorSets a custom client as the default client used by package-level functions. The previous default client is automatically closed.
WARNING
Only accepts clients created via httpc.New() or httpc.NewDefault(). A closed client cannot be set.
client, _ := httpc.New(httpc.PerformanceConfig())
httpc.SetDefaultClient(client)
// Subsequent package-level functions now use PerformanceConfig
result, _ := httpc.Get(url)CloseDefaultClient
func CloseDefaultClient() errorCloses and resets the default client. A new client will be created on the next package-level function call.
Download Functions
Package-level download functions use the default client. The Client interface and DomainClient also provide methods of the same name; all three share an identical signature.
Download
func Download(ctx context.Context, url string, cfg *DownloadConfig, options ...RequestOption) (*DownloadResult, error)Download is the single canonical download entry point spanning the package-level function, the Client interface, and DomainClient — a single signature that replaces the previous {config} x {context} variant matrix.
cfg must not be nil, and cfg.FilePath must be set (otherwise ErrEmptyFilePath is returned). Pass context.Background() when no cancellation or timeout control is needed; request options are used to set headers, authentication, query parameters, and more.
cfg := httpc.DefaultDownloadConfig()
cfg.FilePath = "/tmp/file.zip"
cfg.Overwrite = true
cfg.ResumeDownload = true
cfg.ProgressCallback = func(downloaded, total int64, speed float64) {
fmt.Printf("\r%.1f%%", float64(downloaded)/float64(total)*100)
}
// Package-level function (uses the default client)
result, err := httpc.Download(context.Background(), url, cfg)
// Client interface method
result, err = client.Download(ctx, url, cfg)
// DomainClient method (path is relative to baseURL; response cookies are auto-captured)
result, err = dc.Download(ctx, "/files/report.pdf", cfg)TIP
The old download functions (DownloadFile, DownloadWithOptions, DownloadFileWithContext, and DownloadWithOptionsWithContext) were removed in v1.5.2. Migrate to the unified Download(ctx, url, cfg, options...) and configure path, overwrite, resume, and checksum via DownloadConfig.
Helper Functions
SetSecurityWarnOutput
func SetSecurityWarnOutput(w io.Writer)Redirects security-warning output (e.g. TestingConfig, InsecureSkipVerify warnings). Pass io.Discard to silence all warnings.
// Silence all security warnings
httpc.SetSecurityWarnOutput(io.Discard)
// Redirect to a custom log
httpc.SetSecurityWarnOutput(log.Writer())WARNING
This function is primarily for testing. Production environments should use SecureConfig() or DefaultConfig() rather than suppressing warnings.
Formatting Tools
FormatBytes
func FormatBytes(bytes int64) stringFormats a byte count as a human-readable string (e.g. "1.50 KB", "500 B"). Commonly used for displaying download results and in log output.
result, _ := httpc.Download(context.Background(), url, cfg)
fmt.Printf("Downloaded %s\n", httpc.FormatBytes(result.BytesWritten))
// Downloaded 12.34 MB| Input | Output |
|---|---|
500 | 500 B |
1536 | 1.50 KB |
1048576 | 1.00 MB |
1073741824 | 1.00 GB |
FormatSpeed
func FormatSpeed(bytesPerSecond float64) stringFormats a bytes-per-second rate as a human-readable string (e.g. "1.50 MB/s"). Commonly paired with DownloadResult.AverageSpeed or the speed parameter of DownloadProgressCallback.
result, _ := httpc.Download(context.Background(), url, cfg)
fmt.Printf("Average speed %s\n", httpc.FormatSpeed(result.AverageSpeed))
// Average speed 5.67 MB/s
// Used inside a progress callback
cfg.ProgressCallback = func(downloaded, total int64, speed float64) {
fmt.Printf("\r%s / %s (%s)",
httpc.FormatBytes(downloaded),
httpc.FormatBytes(total),
httpc.FormatSpeed(speed),
)
}| Input (bytes/s) | Output |
|---|---|
500 | 500 B/s |
1536 | 1.50 KB/s |
1048576 | 1.00 MB/s |
TIP
Both use binary units (1024-step), with the unit sequence B -> KB -> MB -> GB -> TB -> PB -> EB.
Domain Client
NewDomain
func NewDomain(baseURL string, cfg Config) (DomainClienter, error)Creates a domain-scoped client that automatically manages cookies and headers. Pass a Config value (cookies are auto-enabled).
dc, err := httpc.NewDomain("https://api.example.com", httpc.DefaultConfig())
defer dc.Close()
dc.SetHeader("Authorization", "Bearer "+token)
result, err := dc.Get("/users")NewDomainDefault
func NewDomainDefault(baseURL string) (DomainClienter, error)Convenience constructor, equivalent to NewDomain(baseURL, DefaultConfig()).
dc, err := httpc.NewDomainDefault("https://api.example.com")
defer dc.Close()See Also
- Result - Response result types and methods
- Request Options - Request configuration options
- Domain Client - Domain-scoped client
- File Download - Download functions and types