Package Functions & Client Methods
Package-Level HTTP Methods
No need to create a client - send requests directly. 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 package-level functions, plus a Request method with context.
New
func New(config ...*Config) (Client, error)Creates a new HTTP client. Pass no config or nil to use DefaultConfig().
client, err := httpc.New()
client, err := httpc.New(nil)
client, err := httpc.New(httpc.SecureConfig())
cfg := httpc.DefaultConfig()
cfg.Timeouts.Request = 60 * time.Second
client, err := httpc.New(cfg)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
Client interface method that releases resources held by the client (connection pool, Transport). Cannot be used after calling.
// Client interface method
Close() errorclient, _ := httpc.New()
defer client.Close()Default Client Management
SetDefaultClient
func SetDefaultClient(client Client) errorSets a custom client as the default client for package-level functions. The old default client is automatically closed.
WARNING
Only accepts clients created via httpc.New(). Cannot set a closed client.
client, _ := httpc.New(httpc.PerformanceConfig())
httpc.SetDefaultClient(client)
// Subsequent package-level functions use PerformanceConfig
result, _ := httpc.Get(url)CloseDefaultClient
func CloseDefaultClient() errorCloses the default client and resets it. 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 with the same name, all sharing 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 shared across the package-level function, the Client interface, and DomainClient — replacing the previous {config} x {context} variant matrix with a single signature.
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)Migration note
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 (such as TestingConfig, InsecureSkipVerify warnings). Pass io.Discard to silence all warnings.
// Silence all security warnings
httpc.SetSecurityWarnOutput(io.Discard)
// Redirect to 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, config ...*Config) (DomainClienter, error)Creates a domain-scoped client with automatic cookie and header management.
dc, err := httpc.NewDomain("https://api.example.com")
defer dc.Close()
dc.SetHeader("Authorization", "Bearer "+token)
result, err := dc.Get("/users")See Also
- Result - Response result types and methods
- Request Options - Request configuration options
- Domain Client - Domain-scoped client
- File Download - Download functions and types