Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk/go): close the Go SDK review follow-ups (#764)

Yudhi Armyndharis920e984d60b0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fd59f7818..53594f80c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,8 +19,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`WithUserAgent`, `WithHeader`, `WithInsecureHTTP`). Errors are typed: match the sentinels with
`errors.Is` (`ErrBadRequest`, `ErrUnauthorized`, `ErrForbidden`, `ErrNotFound`, `ErrConflict`,
`ErrRateLimited`, `ErrNotImplemented`) or unwrap the concrete `*APIError` with `errors.As`. Retries
- are opt-in (`WithRetry`), honour `Retry-After`, rewind request bodies via `GetBody`, and are skipped
- for non-idempotent methods on network errors so a dropped connection cannot replay a send. Redirects
+ are opt-in (`WithRetry`), honour `Retry-After`, and rewind request bodies via `GetBody`. Because the
+ API has no idempotency key, a `POST` is never replayed after a network error, and on a retryable
+ status only for `429`/`503` — which prove the gateway declined the request before acting on it —
+ since a `500`/`502`/`504` can arrive after the message was already sent. Redirects
are never followed, so the bearer-equivalent `X-API-Key` is never re-sent to a redirect target. A
`TestRouting` table asserts the exact method and path of every service call, and the suite runs in CI
(`gofmt`/`go vet`/`go test -race`) on both SDK and server-contract changes, so route drift fails at
diff --git a/sdk/README.md b/sdk/README.md
index 84995a906..8e64aedbe 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -170,6 +170,9 @@ go get github.com/rmyndharis/OpenWA/sdk/go
```go
import (
"context"
+ "fmt"
+ "log"
+
openwa "github.com/rmyndharis/OpenWA/sdk/go"
)
@@ -197,10 +200,13 @@ testing, retry, tracing, or metrics. See [`go/README.md`](go/README.md).
- **Use HTTPS in production.** The API key is sent as `X-API-Key` on every
request and is bearer-equivalent — never send it over plaintext `http://`
outside local development.
-- **No automatic retries.** A failed request raises/throws immediately; wrap
- calls in your own backoff if you need retries (especially for `429`). The
- injectable transport (`fetch` / `transport` / `httpClient`) is the extension
- point for retry or observability middleware.
+- **No automatic retries by default.** A failed request raises/throws
+ immediately; wrap calls in your own backoff if you need retries (especially
+ for `429`). The injectable transport (`fetch` / `transport` / `httpClient`) is
+ the extension point for retry or observability middleware. The Go client is
+ the exception: it ships an opt-in policy (`WithRetry(DefaultRetryPolicy())`)
+ that handles `429`/`5xx`, honors `Retry-After`, and rewinds request bodies —
+ still off unless you ask for it.
- **Redirects are never followed.** A `3xx` surfaces to the caller rather than
being followed, so the API key is never re-sent to a redirect target.
- **Default per-request timeout** is 30s (configurable). Path segments (chat /
diff --git a/sdk/go/auth.go b/sdk/go/auth.go
index 3da3027fe..71b7ffb4f 100644
--- a/sdk/go/auth.go
+++ b/sdk/go/auth.go
@@ -3,7 +3,7 @@ package openwa
import "context"
// AuthService validates the configured API key.
-// Backed by src/modules/auth/auth.controller.ts.
+// Backed by src/modules/auth/auth-validate.controller.ts.
type AuthService struct{ client *Client }
// Validate confirms the API key is valid and returns its role.
diff --git a/sdk/go/client.go b/sdk/go/client.go
index c14a8ca38..689f08e48 100644
--- a/sdk/go/client.go
+++ b/sdk/go/client.go
@@ -37,6 +37,7 @@ import (
"io"
"net/http"
"net/url"
+ "os"
"reflect"
"strconv"
"strings"
@@ -152,6 +153,16 @@ func New(baseURL, apiKey string, opts ...Option) (*Client, error) {
return c, nil
}
+const insecureWarning = "openwa: baseURL uses insecure http:// — the API key is sent in cleartext; use https:// in production"
+
+// warnIfInsecure warns once, at construction, when the API key would travel in
+// cleartext to a non-localhost host.
+//
+// Unlike the SDK's per-request logging, this does not stay silent under the
+// default nopLogger: the caller most likely to point at a plaintext http:// URL
+// by accident is the one who has not wired a logger up yet, so a discarded
+// warning would be no warning at all. An injected logger receives it instead of
+// stderr, and WithInsecureHTTP silences it entirely.
func warnIfInsecure(cfg *config) {
if cfg.allowInsecure {
return
@@ -161,11 +172,14 @@ func warnIfInsecure(cfg *config) {
return
}
host := strings.Trim(u.Hostname(), "[]")
- if u.Scheme == "http" && !localhostHosts[host] {
- cfg.logger.Log(context.Background(), LevelWarn,
- "openwa: baseURL uses insecure http:// — the API key is sent in cleartext; use https:// in production",
- "host", host)
+ if u.Scheme != "http" || localhostHosts[host] {
+ return
+ }
+ if _, isNop := cfg.logger.(nopLogger); isNop {
+ fmt.Fprintf(os.Stderr, "%s (host: %s)\n", insecureWarning, host)
+ return
}
+ cfg.logger.Log(context.Background(), LevelWarn, insecureWarning, "host", host)
}
// Do issues a raw request against the API and decodes the JSON response into
diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go
index 5727ac951..817bb7a8c 100644
--- a/sdk/go/client_test.go
+++ b/sdk/go/client_test.go
@@ -253,6 +253,87 @@ func TestRetryPolicy(t *testing.T) {
}
}
+// statusTransport always replies with the same status, counting attempts.
+type statusTransport struct {
+ status int
+ calls int32
+}
+
+func (t *statusTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ atomic.AddInt32(&t.calls, 1)
+ if req.Body != nil {
+ io.Copy(io.Discard, req.Body)
+ }
+ return &http.Response{
+ StatusCode: t.status,
+ Body: io.NopCloser(strings.NewReader(`{"statusCode":500,"message":"boom","error":"Internal"}`)),
+ Header: http.Header{},
+ Request: req,
+ }, nil
+}
+
+// A 500/502/504 can be returned after the gateway already sent the message, so
+// replaying a POST on those would double-send. Only 429/503 — which prove the
+// server declined before acting — may retry a non-idempotent request.
+func TestRetryDoesNotReplayPostOnAmbiguousStatus(t *testing.T) {
+ for _, status := range []int{500, 502, 504} {
+ t.Run(http.StatusText(status), func(t *testing.T) {
+ rt := &statusTransport{status: status}
+ c := newTestClient(t, rt, WithRetry(RetryPolicy{
+ MaxRetries: 3, BaseDelay: time.Millisecond, MaxDelay: 5 * time.Millisecond,
+ RetryableStatuses: []int{429, 500, 502, 503, 504},
+ }))
+
+ _, err := c.Messages.SendText(context.Background(), "s1", SendTextRequest{ChatID: "x", Text: "y"})
+ if err == nil {
+ t.Fatal("expected an error")
+ }
+ if rt.calls != 1 {
+ t.Fatalf("POST on %d must not be replayed: got %d attempts, want 1", status, rt.calls)
+ }
+ })
+ }
+}
+
+// The same statuses ARE retried for an idempotent method — the conservative
+// rule must not blunt retries where replay is safe.
+func TestRetryStillReplaysIdempotentOnAmbiguousStatus(t *testing.T) {
+ rt := &statusTransport{status: 500}
+ c := newTestClient(t, rt, WithRetry(RetryPolicy{
+ MaxRetries: 2, BaseDelay: time.Millisecond, MaxDelay: 5 * time.Millisecond,
+ RetryableStatuses: []int{429, 500, 502, 503, 504},
+ }))
+
+ _, err := c.Sessions.List(context.Background(), nil)
+ if err == nil {
+ t.Fatal("expected an error")
+ }
+ if rt.calls != 3 {
+ t.Fatalf("GET on 500 should retry: got %d attempts, want 3", rt.calls)
+ }
+}
+
+// 429/503 mean the server declined before acting, so a POST may still retry.
+func TestRetryReplaysPostOnBackpressure(t *testing.T) {
+ for _, status := range []int{429, 503} {
+ t.Run(http.StatusText(status), func(t *testing.T) {
+ rt := &statusTransport{status: status}
+ c := newTestClient(t, rt, WithRetry(RetryPolicy{
+ MaxRetries: 2, BaseDelay: time.Millisecond, MaxDelay: 5 * time.Millisecond,
+ RetryableStatuses: []int{429, 500, 502, 503, 504},
+ }))
+
+ _, err := c.Messages.SendText(context.Background(), "s1", SendTextRequest{ChatID: "x", Text: "y"})
+ if err == nil {
+ t.Fatal("expected an error")
+ }
+ if rt.calls != 3 {
+ t.Fatalf("POST on %d is backpressure and should retry: got %d attempts, want 3", status, rt.calls)
+ }
+ })
+ }
+}
+
func TestMiddlewarePipeline(t *testing.T) {
rt := &recordTransport{status: 200, body: `[]`}
var hits int32
@@ -505,6 +586,70 @@ func TestBulkAudioSerializesPTT(t *testing.T) {
}
}
+// capturingLogger records what the SDK logs.
+type capturingLogger struct{ msgs []string }
+
+func (l *capturingLogger) Log(_ context.Context, _ string, msg string, _ ...any) {
+ l.msgs = append(l.msgs, msg)
+}
+
+// The insecure-http warning must reach an injected logger...
+func TestInsecureHTTPWarnsInjectedLogger(t *testing.T) {
+ lg := &capturingLogger{}
+ if _, err := New("http://wa.example.com:2785", "k", WithLogger(lg)); err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ if len(lg.msgs) != 1 || !strings.Contains(lg.msgs[0], "insecure http://") {
+ t.Fatalf("expected an insecure-http warning, got %v", lg.msgs)
+ }
+}
+
+// ...and must stay silent for https, localhost, or when explicitly suppressed.
+func TestInsecureHTTPWarningSuppressed(t *testing.T) {
+ cases := []struct {
+ name string
+ url string
+ opts []Option
+ }{
+ {"https", "https://wa.example.com", nil},
+ {"localhost", "http://localhost:2785", nil},
+ {"loopback ip", "http://127.0.0.1:2785", nil},
+ {"explicitly allowed", "http://wa.example.com", []Option{WithInsecureHTTP()}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ lg := &capturingLogger{}
+ if _, err := New(tc.url, "k", append([]Option{WithLogger(lg)}, tc.opts...)...); err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ if len(lg.msgs) != 0 {
+ t.Fatalf("expected no warning, got %v", lg.msgs)
+ }
+ })
+ }
+}
+
+// The server types status timestamps as Date, which serializes to RFC 3339.
+func TestStatusTimestampsDecodeRFC3339(t *testing.T) {
+ rt := &recordTransport{status: 200, body: `{"statuses":[{"id":"s1","contact":{"id":"[email protected]"},"timestamp":"2026-07-17T10:30:00.000Z","expiresAt":"2026-07-18T10:30:00.000Z"}]}`}
+ c := newTestClient(t, rt)
+
+ out, err := c.Status.List(context.Background(), "s1")
+ if err != nil {
+ t.Fatalf("Status.List: %v", err)
+ }
+ if len(out) != 1 {
+ t.Fatalf("want 1 status, got %d", len(out))
+ }
+ got := out[0]
+ if want := time.Date(2026, 7, 17, 10, 30, 0, 0, time.UTC); !got.Timestamp.Equal(want) {
+ t.Fatalf("Timestamp = %v, want %v", got.Timestamp, want)
+ }
+ if want := time.Date(2026, 7, 18, 10, 30, 0, 0, time.UTC); !got.ExpiresAt.Equal(want) {
+ t.Fatalf("ExpiresAt = %v, want %v", got.ExpiresAt, want)
+ }
+}
+
func TestContextCancel(t *testing.T) {
rt := &recordTransport{status: 200, body: `[]`}
c := newTestClient(t, rt)
diff --git a/sdk/go/retry.go b/sdk/go/retry.go
index 106ccd2d6..85f039506 100644
--- a/sdk/go/retry.go
+++ b/sdk/go/retry.go
@@ -27,10 +27,41 @@ var idempotentMethods = map[string]bool{
// could double-send a WhatsApp message.
func isIdempotent(method string) bool { return idempotentMethods[method] }
+// backpressureStatuses are the statuses that mean the server declined the
+// request before acting on it: 429 (rate limited) and 503 (unavailable). Only
+// these are safe to retry for a non-idempotent method.
+//
+// The rest of the retryable set (500/502/504) can be returned AFTER the gateway
+// has already sent the WhatsApp message — a 504 from a reverse proxy is the
+// textbook case — so replaying a POST on those would duplicate the send. The
+// SDK has no idempotency key to deduplicate with, so it declines the retry
+// rather than risk a second message.
+var backpressureStatuses = map[int]bool{
+ http.StatusTooManyRequests: true, // 429
+ http.StatusServiceUnavailable: true, // 503
+}
+
+// retryableForMethod reports whether a retryable status may be retried for this
+// method. Idempotent methods may retry any status in the policy; a
+// non-idempotent one (POST) is limited to the backpressure statuses.
+func retryableForMethod(method string, status int) bool {
+ if isIdempotent(method) {
+ return true
+ }
+ return backpressureStatuses[status]
+}
+
// RetryPolicy controls automatic retries. Retries are OFF by default — pass one
// with WithRetry to opt in. Only network errors and the statuses in
// RetryableStatuses are retried; a non-retryable response is returned as-is.
//
+// Non-idempotent requests (POST — every send endpoint) are retried
+// conservatively, because the SDK has no idempotency key to deduplicate with:
+// never after a network error, and on a retryable status only for 429 and 503,
+// which prove the server declined the request before acting on it. A
+// 500/502/504 may arrive after the gateway already sent the message, so a POST
+// is not replayed on those. Idempotent methods retry the full policy.
+//
// Because every request the SDK issues sets req.GetBody, request bodies are
// safely rewound on each attempt.
type RetryPolicy struct {
@@ -146,9 +177,11 @@ func retryMiddleware(p RetryPolicy, log Logger) Middleware {
retryable = isIdempotent(req.Method)
case resp != nil && p.retryableStatus(resp.StatusCode):
// A retryable HTTP status is the server explicitly telling
- // us to back off. Safe to retry for any method: the server
- // has rejected the request before processing it.
- retryable = true
+ // us to back off — but only 429/503 prove it declined the
+ // request before acting on it. A 500/502/504 can arrive
+ // after the gateway already sent the message, so replaying
+ // a POST on those would double-send.
+ retryable = retryableForMethod(req.Method, resp.StatusCode)
}
if !retryable || attempt >= p.MaxRetries {
return resp, err
diff --git a/sdk/go/types_status.go b/sdk/go/types_status.go
index d06df5096..53620e612 100644
--- a/sdk/go/types_status.go
+++ b/sdk/go/types_status.go
@@ -1,5 +1,7 @@
package openwa
+import "time"
+
// StatusContact is the poster of a status entry (from a GET list).
type StatusContact struct {
ID string `json:"id"`
@@ -16,8 +18,10 @@ type StatusRecord struct {
MediaURL string `json:"mediaUrl,omitempty"`
BackgroundColor string `json:"backgroundColor,omitempty"`
Font *int `json:"font,omitempty"`
- Timestamp any `json:"timestamp,omitempty"`
- ExpiresAt any `json:"expiresAt,omitempty"`
+ // The server types these as Date, which serializes to RFC 3339, so
+ // time.Time decodes them directly. Zero when the server omits the field.
+ Timestamp time.Time `json:"timestamp,omitempty"`
+ ExpiresAt time.Time `json:"expiresAt,omitempty"`
}
// StatusListResponse is the {"statuses": [...]} envelope returned by GET
@@ -30,9 +34,9 @@ type StatusListResponse struct {
// It intentionally differs from StatusRecord: the POST response has statusId +
// timing, no contact/media.
type StatusResult struct {
- StatusID string `json:"statusId"`
- Timestamp any `json:"timestamp,omitempty"`
- ExpiresAt any `json:"expiresAt,omitempty"`
+ StatusID string `json:"statusId"`
+ Timestamp time.Time `json:"timestamp,omitempty"`
+ ExpiresAt time.Time `json:"expiresAt,omitempty"`
}
// SendTextStatusRequest posts a text status. Recipients is required.