Skip to content
MinatoAkaPublic

About

Lightweight Go Secure HTTP client. myhttp provides native DNS over HTTPS ⁦(DoH)⁩ support for maximum security and portability.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Go Reference Go MIT License Support via Saweria

myhttp

A lightweight Go Secure HTTP client with configurable retries, rate limiting, timeouts, User-Agent and DNS over HTTPS ⁦(DoH)⁩ support.

Install

go get github.com/MinatoAka/myhttp

Quick start

client := myhttp.New(
    myhttp.WithRetry(3, time.Second),
    myhttp.WithRetryPOST(true), // true or false
    myhttp.WithRateLimit(5),
    myhttp.WithTimeout(10*time.Second),
    myhttp.WithUserAgent("myapp/1.0"),
)

resp, err := client.Get("https://example.com")
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

Import github.com/MinatoAka/myhttp and time in your Go file.

Secure DNS (DoH)

Enable DNS resolution over HTTPS (DNS over HTTPS) to prevent DNS poisoning, spoofing, or ISP throttling.

// Use default secure DNS provider (Quad9)
client := myhttp.New(
    myhttp.WithDNS(""), 
)

// Or use a custom DoH provider (e.g., Cloudflare)
client := myhttp.New(
    myhttp.WithDNS("https://cloudflare-dns.com/dns-query"),
)

Note: Passing an empty string "" to WithDNS will automatically default to Quad9 (https://dns.quad9.net/dns-query).

DoH behavior:

  • Resolves both A (IPv4) and AAAA (IPv6) records and follows CNAME chains (max 8 hops).
  • Results are cached per host until the smallest record TTL expires (max 1024 hosts).
  • DNS responses are validated (response flag, query ID, question match, truncation) before use.
  • The endpoint must use HTTPS. Plain http:// is only allowed for loopback addresses (local testing).
  • No silent fallback: if DoH fails, the request fails instead of leaking to plaintext DNS. Enable myhttp.WithDNSFallback(true) to allow falling back to the system resolver.
  • HTTP proxies from the environment (HTTP_PROXY / HTTPS_PROXY) are respected. If the proxy host itself cannot be resolved by your DoH provider, enable WithDNSFallback(true).

Options

Option Description Default
WithRetry(maxRetries int, baseWait time.Duration) Retry network errors and HTTP 5xx. 0 disables retries 3, 1s
WithRetryPOST(enable bool) Allow retrying POST requests. false prevents duplicate actions (e.g., trading orders) false
WithRateLimit(reqPerSec int) Max requests per second per client. 0 disables 0 (disabled)
WithTimeout(d time.Duration) Timeout for the whole call, including retries 15s
WithAttemptTimeout(d time.Duration) Max wait for response headers per attempt; 0 disables. Prevents one hung attempt from consuming the whole timeout 0
WithUserAgent(ua string) Default User-Agent header myhttp/1.0
WithDNS(dnsURL string) Enable DNS over HTTPS (DoH) for secure resolution. Empty string defaults to Quad9 "" (disabled)
WithDNSFallback(enable bool) Fall back to the system resolver when DoH fails or is misconfigured false

myhttp.New() with no options is valid — all defaults apply.

API

Method Signature
New New(opts ...Option) *Client
Get Get(url string) (*http.Response, error)
GetContext GetContext(ctx context.Context, url string) (*http.Response, error)
Do Do(req *http.Request) (*http.Response, error)
CloseIdleConnections CloseIdleConnections()

Get is a shortcut for GetContext(context.Background(), url). For POST, PUT, DELETE, or any request with custom headers, build an *http.Request and send it with Do. Call CloseIdleConnections() when a client is no longer used.

Behavior notes

Retries

  • Triggered by network errors, HTTP 5xx, and HTTP 429 (rate limited).
  • Other 4xx (400/401/403/404) are returned immediately — check resp.StatusCode yourself.
  • If the server sends Retry-After, that value is used instead of backoff. Both formats are supported: delta-seconds (5) and HTTP-date. The value is honored as-is (not capped by the 60s backoff limit); the client timeout/cancel still bounds the wait.
  • Otherwise backoff doubles from baseWait (1s → 2s → 4s) plus 0–500ms jitter, capped at 60s.
  • Sleep between attempts is context-aware: cancelling the request stops retries immediately.
  • When retries are exhausted, Get/Do return a nil response and a *myhttp.RetryError. Use errors.As to read Attempts, StatusCode (0 for network errors), and Err (the last failure).
  • Request bodies are buffered once and replayed on each attempt, so POST/PUT retries are safe.
  • POST requests are NOT retried by default to prevent duplicate actions (e.g., double orders in trading). Use WithRetryPOST(true) to enable retries for POST if your API supports idempotency.
  • WithRetry(0, ...) disables the retry layer entirely.

Rate limiting

  • Applied once per Get/Do call, before the retry layer. Retries inside a call are not gated again.
  • Blocks (sleeps) until the next slot is free; it never returns an error.
  • Shared across all goroutines using the same client.

Timeout

  • WithTimeout covers the entire call, including all retries and backoff sleeps — not each individual attempt.
  • WithAttemptTimeout bounds each attempt's wait for response headers, so a single hung attempt can't consume the whole WithTimeout budget.
  • Example: WithRetry(3, time.Second) can sleep ~7s in backoff alone, so keep the timeout comfortably above that.

Response body

  • The caller closes resp.Body on success.
  • Bodies from failed attempts are closed automatically before retrying.

Test

go test ./...

About

Lightweight Go Secure HTTP client. myhttp provides native DNS over HTTPS ⁦(DoH)⁩ support for maximum security and portability.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages