Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ DoH behavior:
| `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` |
Expand All @@ -83,15 +84,16 @@ DoH behavior:
|---|---|
| `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 POST, PUT, DELETE, or any request with custom headers, build an `*http.Request` and send it with `Do`.
`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.
Expand All @@ -111,6 +113,7 @@ DoH behavior:

### 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
Expand Down
61 changes: 53 additions & 8 deletions client.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package myhttp

import (
"context"
"fmt"
"net/http"
"time"
Expand Down Expand Up @@ -28,12 +29,7 @@ func New(opts ...Option) *Client {
}

// Tentukan base transport: Pakai custom DNS jika diaktifkan, jika tidak pakai Default
var baseTransport http.RoundTripper
if cfg.dnsURL != "" {
baseTransport = newDNSTransport(cfg.dnsURL, cfg.dnsFallback)
} else {
baseTransport = http.DefaultTransport
}
baseTransport := newBaseTransport(cfg)

// Build RoundTripper chain:
// base (DNS or Default) → retry → ratelimit → ua
Expand Down Expand Up @@ -63,6 +59,29 @@ func New(opts ...Option) *Client {
}
}

// newBaseTransport — bikin base RoundTripper sesuai config.
func newBaseTransport(cfg options) http.RoundTripper {
if cfg.dnsURL != "" {
tr := newDNSTransport(cfg.dnsURL, cfg.dnsFallback)
if cfg.attemptTimeout > 0 {
tr.ResponseHeaderTimeout = cfg.attemptTimeout
}
return tr
}

if cfg.attemptTimeout <= 0 {
return http.DefaultTransport
}

// Jangan ubah http.DefaultTransport global: clone dulu.
if tr, ok := http.DefaultTransport.(*http.Transport); ok {
clone := tr.Clone()
clone.ResponseHeaderTimeout = cfg.attemptTimeout
return clone
}
return http.DefaultTransport
}

// uaTransport — inject User-Agent
type uaTransport struct {
base http.RoundTripper
Expand All @@ -80,9 +99,30 @@ func (t *uaTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return t.base.RoundTrip(r)
}

// Get — shortcut untuk GET request
func (t *uaTransport) CloseIdleConnections() {
closeIdleConnections(t.base)
}

// closeIdler — RoundTripper yang mendukung penutupan koneksi idle.
type closeIdler interface {
CloseIdleConnections()
}

// closeIdleConnections meneruskan CloseIdleConnections ke transport di bawahnya.
func closeIdleConnections(rt http.RoundTripper) {
if c, ok := rt.(closeIdler); ok {
c.CloseIdleConnections()
}
}

// Get — shortcut untuk GET request tanpa context.
func (c *Client) Get(url string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
return c.GetContext(context.Background(), url)
}

// GetContext — shortcut GET yang bisa dibatalkan lewat context.
func (c *Client) GetContext(ctx context.Context, url string) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("bikin request: %w", err)
}
Expand All @@ -93,3 +133,8 @@ func (c *Client) Get(url string) (*http.Response, error) {
func (c *Client) Do(req *http.Request) (*http.Response, error) {
return c.http.Do(req)
}

// CloseIdleConnections — tutup semua koneksi idle milik client.
func (c *Client) CloseIdleConnections() {
c.http.CloseIdleConnections()
}
105 changes: 97 additions & 8 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package myhttp

import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
Expand Down Expand Up @@ -47,19 +49,22 @@ func TestRetryOn5xx(t *testing.T) {

// TestUserAgent — memastikan UA ter-inject
func TestUserAgent(t *testing.T) {
var gotUA string
gotUA := make(chan string, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotUA = r.Header.Get("User-Agent")
gotUA <- r.Header.Get("User-Agent")
w.WriteHeader(200)
}))
defer server.Close()

client := New(WithUserAgent("shinobi-bot/1.0"))
resp, _ := client.Get(server.URL)
resp, err := client.Get(server.URL)
if err != nil {
t.Fatalf("request gagal: %v", err)
}
defer resp.Body.Close()

if gotUA != "shinobi-bot/1.0" {
t.Errorf("UA = %q, mau %q", gotUA, "shinobi-bot/1.0")
if ua := <-gotUA; ua != "shinobi-bot/1.0" {
t.Errorf("UA = %q, mau %q", ua, "shinobi-bot/1.0")
}
}

Expand Down Expand Up @@ -102,7 +107,10 @@ func TestRateLimit(t *testing.T) {
client := New(WithRateLimit(5)) // 5 req/detik = 200ms/req
start := time.Now()
for i := 0; i < 3; i++ {
resp, _ := client.Get(server.URL)
resp, err := client.Get(server.URL)
if err != nil {
t.Fatalf("request #%d gagal: %v", i+1, err)
}
resp.Body.Close()
}
elapsed := time.Since(start)
Expand All @@ -112,14 +120,92 @@ func TestRateLimit(t *testing.T) {
}
}

// TestAttemptTimeout — satu attempt yang hang harus dipotong, lalu retry.
func TestAttemptTimeout(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<-r.Context().Done() // tunggu client membatalkan request
}))
defer server.Close()

client := New(
WithRetry(1, 10*time.Millisecond),
WithAttemptTimeout(50*time.Millisecond),
WithTimeout(5*time.Second),
)

start := time.Now()
_, err := client.Get(server.URL)
elapsed := time.Since(start)

if err == nil {
t.Fatal("harusnya error karena semua attempt timeout")
}

var retryErr *RetryError
if !errors.As(err, &retryErr) {
t.Fatalf("error = %T (%v), mau *RetryError", err, err)
}
if retryErr.Attempts != 2 {
t.Errorf("Attempts = %d, mau 2", retryErr.Attempts)
}
if elapsed > 3*time.Second {
t.Errorf("terlalu lama: %v (timeout per attempt tidak bekerja)", elapsed)
}
}

// TestGetContextCanceled — GetContext harus menghormati context yang dibatalkan.
func TestGetContextCanceled(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer server.Close()

client := New(WithRetry(0, 0), WithTimeout(5*time.Second))
ctx, cancel := context.WithCancel(context.Background())
cancel()

if _, err := client.GetContext(ctx, server.URL); err == nil {
t.Fatal("harusnya error karena context dibatalkan")
}
}

// closeIdleSpy — transport palsu untuk memastikan CloseIdleConnections diteruskan.
type closeIdleSpy struct{ closed bool }

func (s *closeIdleSpy) RoundTrip(*http.Request) (*http.Response, error) {
return nil, errors.New("tidak dipakai")
}

func (s *closeIdleSpy) CloseIdleConnections() { s.closed = true }

// TestCloseIdleConnectionsChain — CloseIdleConnections harus sampai ke transport dasar.
func TestCloseIdleConnectionsChain(t *testing.T) {
spy := &closeIdleSpy{}
transport := &uaTransport{
base: newRateLimitTransport(&retryTransport{base: spy}, 1),
userAgent: "test/1.0",
}

transport.CloseIdleConnections()
if !spy.closed {
t.Error("CloseIdleConnections tidak diteruskan sampai transport dasar")
}

// Client nyata tidak boleh panic.
New().CloseIdleConnections()
}

// TestRetryPostBody — Memastikan body POST tidak hilang saat retry
// PENTING: HARUS aktifkan WithRetryPOST(true) agar test ini jalan
func TestRetryPostBody(t *testing.T) {
var attempts int32
var mu sync.Mutex
var receivedBody string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
mu.Lock()
receivedBody = string(body)
mu.Unlock()
n := atomic.AddInt32(&attempts, 1)
if n < 3 {
w.WriteHeader(http.StatusInternalServerError) // Paksa retry
Expand All @@ -146,8 +232,11 @@ func TestRetryPostBody(t *testing.T) {
if resp.StatusCode != 200 {
t.Errorf("Status = %d, mau 200", resp.StatusCode)
}
if receivedBody != `{"pair":"ethidr"}` {
t.Errorf("Body hilang saat retry! Diterima: %q", receivedBody)
mu.Lock()
gotBody := receivedBody
mu.Unlock()
if gotBody != `{"pair":"ethidr"}` {
t.Errorf("Body hilang saat retry! Diterima: %q", gotBody)
}
}

Expand Down
28 changes: 19 additions & 9 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import "time"

// options — struct internal untuk menyimpan config
type options struct {
retries int
retryBaseWait time.Duration
rateLimit int // request per detik (0 = unlimited)
timeout time.Duration
userAgent string
dnsURL string // URL untuk custom DNS resolution
dnsFallback bool // Izinkan fallback ke resolver sistem kalau DoH gagal
retryPOST bool // Izinkan retry untuk method POST (default: false)
retries int
retryBaseWait time.Duration
rateLimit int // request per detik (0 = unlimited)
timeout time.Duration
attemptTimeout time.Duration // batas tunggu response header per attempt
userAgent string
dnsURL string // URL untuk custom DNS resolution
dnsFallback bool // Izinkan fallback ke resolver sistem kalau DoH gagal
retryPOST bool // Izinkan retry untuk method POST (default: false)
}

// Option — tipe fungsi yang memodifikasi options
Expand All @@ -32,13 +33,22 @@ func WithRateLimit(reqPerSec int) Option {
}
}

// WithTimeout — timeout per request
// WithTimeout — timeout untuk seluruh pemanggilan (termasuk semua retry).
func WithTimeout(d time.Duration) Option {
return func(o *options) {
o.timeout = d
}
}

// WithAttemptTimeout — batas waktu menunggu response header untuk tiap attempt.
// Berguna supaya satu attempt yang hang tidak menghabiskan seluruh budget retry.
// Timeout keseluruhan tetap diatur oleh WithTimeout. Nilai 0 berarti tanpa batas.
func WithAttemptTimeout(d time.Duration) Option {
return func(o *options) {
o.attemptTimeout = d
}
}

// WithUserAgent — set User-Agent
func WithUserAgent(ua string) Option {
return func(o *options) {
Expand Down
4 changes: 4 additions & 0 deletions ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,7 @@ func (t *rateLimitTransport) RoundTrip(req *http.Request) (*http.Response, error

return t.base.RoundTrip(req)
}

func (t *rateLimitTransport) CloseIdleConnections() {
closeIdleConnections(t.base)
}
4 changes: 4 additions & 0 deletions retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ func (t *retryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return nil, &RetryError{Attempts: attempts, StatusCode: lastStatus, Err: lastErr}
}

func (t *retryTransport) CloseIdleConnections() {
closeIdleConnections(t.base)
}

// RetryError — error yang dikembalikan ketika semua attempt gagal.
// Gunakan errors.As untuk mengambil detailnya.
type RetryError struct {
Expand Down
Loading