Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(sdk): add Go SDK (#720)
Leynardo Yosefe8725094f076
diff --git a/sdk/README.md b/sdk/README.mdindex 7dcb681f2..84995a906 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -16,6 +16,7 @@ hand-written resource methods.| Python | [`rmyndharis-openwa`](python/) | sync (httpx), PEP 561 typed || PHP | [`rmyndharis/openwa`](php/) | sync (Guzzle, PHP 8.1+) || Java | [`com.rmyndharis:openwa`](java/) | sync (java.net.http + Gson, Java 17) |+| Go | [`github.com/rmyndharis/OpenWA/sdk/go`](go/) | stdlib-only, context-first, injectable transport (Go 1.22+) |## Coverage@@ -160,6 +161,37 @@ Requires Java 17+. Errors are a typed, unchecked hierarchy — branch withcustom `HttpTransport` that records the request — no network. See[`java/README.md`](java/README.md) for the full guide.+## Go++```bash+go get github.com/rmyndharis/OpenWA/sdk/go+```++```go+import (+ "context"+ openwa "github.com/rmyndharis/OpenWA/sdk/go"+)++client, err := openwa.New("http://localhost:2785", "owa_k1_…")+if err != nil {+ log.Fatal(err)+}++ctx := context.Background()+client.Sessions.Start(ctx, "my-session")+res, err := client.Messages.SendText(ctx, "my-session", openwa.SendTextRequest{+ ChatID: "[email protected]",+ Text: "Hello from the OpenWA Go SDK!",+})+fmt.Println(res.MessageID)+```++Requires Go 1.22+. Stdlib-only, context-first. Errors are typed — match with+`errors.Is(err, openwa.ErrConflict)` or unwrap `*openwa.APIError` with+`errors.As`. Inject an `http.RoundTripper` with `openwa.WithTransport(...)` for+testing, retry, tracing, or metrics. See [`go/README.md`](go/README.md).+## Reliability & security- **Use HTTPS in production.** The API key is sent as `X-API-Key` on every@@ -186,6 +218,8 @@ cd sdk/python && python -m pytest -qcd sdk/php && composer install && ./vendor/bin/phpunit# Javacd sdk/java && mvn -B verify+# Go+cd sdk/go && go test -race ./... && go vet ./...```Each test suite mocks the HTTP layer and asserts on the exact path, so thediff --git a/sdk/go/README.md b/sdk/go/README.mdnew file mode 100644index 000000000..932291dba--- /dev/null+++ b/sdk/go/README.md@@ -0,0 +1,174 @@+# OpenWA Go SDK++Idiomatic Go client for the [OpenWA](https://github.com/rmyndharis/OpenWA) WhatsApp+API Gateway. Stdlib-only (no dependencies), context-first, with typed errors and+an injectable transport pipeline.++```bash+go get github.com/rmyndharis/OpenWA/sdk/go+```++Requires Go 1.22+.++## Quick start++```go+package main++import (+ "context"+ "log"++ openwa "github.com/rmyndharis/OpenWA/sdk/go"+)++func main() {+ client, err := openwa.New("http://localhost:2785", "owa_k1_…")+ if err != nil {+ log.Fatal(err)+ }++ ctx := context.Background()+ if _, err := client.Sessions.Start(ctx, "my-session"); err != nil {+ log.Fatal(err)+ }++ res, err := client.Messages.SendText(ctx, "my-session", openwa.SendTextRequest{+ ChatID: "[email protected]",+ Text: "Hello from the OpenWA Go SDK!",+ })+ if err != nil {+ log.Fatal(err)+ }+ log.Println(res.MessageID)+}+```++## Design++- **Client entry point** — `openwa.New(baseURL, apiKey, opts...)` returns a+ `*Client`. Required credentials are positional; everything else is a functional+ Option. The client is safe for concurrent use.+- **Services by domain** — the API is grouped onto exported fields:+ `client.Sessions`, `client.Messages`, `client.Contacts`, `client.Groups`,+ `client.Webhooks`, `client.Chats`, `client.Status`, `client.Labels`,+ `client.Channels`, `client.Catalog`, `client.Templates`, `client.Health`,+ `client.Search`, `client.Auth`.+- **Context-first** — every network method takes `ctx context.Context` as its+ first argument; the context bounds the request (and any retries).+- **Functional options + DI** — inject dependencies instead of relying on+ globals: `WithHTTPClient`, `WithTransport`, `WithLogger`, `WithRetry`,+ `WithMiddleware`, `WithTimeout`, `WithUserAgent`, `WithHeader`.+- **Typed errors** — match with `errors.Is` against the sentinels, or unwrap the+ concrete `*APIError` with `errors.As`.++## Configuration++| Option | Purpose |+| ------ | ------- |+| `WithTimeout(d)` | Per-request timeout (default 30s). |+| `WithHTTPClient(hc)` | Inject a preconfigured `*http.Client` (pool, jar, timeout). |+| `WithTransport(rt)` | Inject the base `http.RoundTripper` (proxy, TLS, test double). |+| `WithLogger(l)` | Inject a `Logger` (default: no-op). |+| `WithRetry(p)` | Enable automatic retries (off by default). |+| `WithMiddleware(mw...)` | Add transport middleware (tracing, metrics, auth). |+| `WithUserAgent(ua)` | Override the `User-Agent`. |+| `WithHeader(k, v)` | Add a default header on every request. |+| `WithInsecureHTTP()` | Suppress the plaintext-`http://` warning. |++## Typed errors++```go+res, err := client.Messages.SendText(ctx, "my-session", req)+switch {+case errors.Is(err, openwa.ErrConflict):+ // 409 — engine not ready; retry once the session is "ready".+case errors.Is(err, openwa.ErrNotFound):+ // 404 — unknown session/resource.+case err != nil:+ var apiErr *openwa.APIError+ if errors.As(err, &apiErr) {+ log.Printf("API %d: %s (body: %v)", apiErr.StatusCode, apiErr.Message, apiErr.Body)+ }+}+```++Sentinels: `ErrUnauthorized` (401), `ErrForbidden` (403), `ErrNotFound` (404),+`ErrConflict` (409), `ErrRateLimited` (429), `ErrNotImplemented` (501). A timeout+surfaces as `*openwa.TimeoutError`.++## Retries++Off by default. Opt in with a policy; only network errors and retryable statuses+(429/5xx) are retried, with exponential backoff and `Retry-After` support.+Request bodies are safely rewound on each attempt.++```go+client, _ := openwa.New(baseURL, apiKey,+ openwa.WithRetry(openwa.DefaultRetryPolicy()),+)+```++## Middleware / transport pipeline++Inject cross-cutting concerns (tracing, metrics, custom auth) as `Middleware`.+The first middleware is the outermost layer. The SDK's own auth, logging, and+retry layers sit inside yours, so every attempt is authenticated and observable.++```go+tracing := func(next http.RoundTripper) http.RoundTripper {+ return openwa.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {+ // start span, inject headers…+ return next.RoundTrip(req)+ })+}+client, _ := openwa.New(baseURL, apiKey, openwa.WithMiddleware(tracing))+```++## Dependency injection & testing++Inject a mock `http.RoundTripper` — no network, no global state:++```go+type mockRT struct{}+func (mockRT) RoundTrip(r *http.Request) (*http.Response, error) {+ return &http.Response{+ StatusCode: 200,+ Body: io.NopCloser(strings.NewReader(`{"messageId":"m1","timestamp":1}`)),+ Header: http.Header{},+ }, nil+}++client, _ := openwa.New("https://api.test", "key", openwa.WithTransport(mockRT{}))+```++## Escape hatch++For endpoints the typed services don't cover, use `client.Do`:++```go+var out map[string]any+err := client.Do(ctx, "GET", "/api/some/new/path", nil, nil, &out)+```++## Security & reliability++- **Use HTTPS in production.** The API key is sent as `X-API-Key` on every+ request and is bearer-equivalent. Over plaintext `http://` to a non-localhost+ host the SDK logs a warning (silence it with `WithInsecureHTTP`).+- **Redirects are never followed** — a `3xx` surfaces as an `*APIError` rather+ than re-sending the API key to the redirect target.+- Path segments (chat/message ids) are percent-encoded; a base-URL path prefix+ (e.g. behind a proxy at `/v1`) is preserved.++## Development++```bash+cd sdk/go+go test -race -cover ./...+go vet ./...+```++The `TestRouting` table asserts the exact method and path of every service call,+so a wrong path (the historical `/messages/text` vs `/messages/send-text`) fails+at test time.diff --git a/sdk/go/auth.go b/sdk/go/auth.gonew file mode 100644index 000000000..3da3027fe--- /dev/null+++ b/sdk/go/auth.go@@ -0,0 +1,17 @@+package openwa++import "context"++// AuthService validates the configured API key.+// Backed by src/modules/auth/auth.controller.ts.+type AuthService struct{ client *Client }++// Validate confirms the API key is valid and returns its role.+func (s *AuthService) Validate(ctx context.Context) (*AuthValidateResponse, error) {+ var out AuthValidateResponse+ err := s.client.do(ctx, "POST", "/api/auth/validate", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/sdk/go/catalog.go b/sdk/go/catalog.gonew file mode 100644index 000000000..e8aeeaf7e--- /dev/null+++ b/sdk/go/catalog.go@@ -0,0 +1,63 @@+package openwa++import "context"++// CatalogService reads the WhatsApp Business catalog and sends product/catalog+// messages. Catalog reads live under /catalog; product/catalog SENDS share the+// messages namespace (/messages/send-product, /messages/send-catalog).+// Backed by src/modules/catalog/catalog.controller.ts.+type CatalogService struct{ client *Client }++func (s *CatalogService) sessionBase(sessionID string) string {+ return "/api/sessions/" + pathEscape(sessionID)+}++// Info returns catalog metadata.+func (s *CatalogService) Info(ctx context.Context, sessionID string) (*CatalogInfo, error) {+ var out CatalogInfo+ err := s.client.do(ctx, "GET", s.sessionBase(sessionID)+"/catalog", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Products returns paginated catalog products.+func (s *CatalogService) Products(ctx context.Context, sessionID string, query *CatalogProductsQuery) (*PaginatedProducts, error) {+ var out PaginatedProducts+ err := s.client.do(ctx, "GET", s.sessionBase(sessionID)+"/catalog/products", valuesOf(query), nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Product returns a single catalog product.+func (s *CatalogService) Product(ctx context.Context, sessionID, productID string) (*CatalogProduct, error) {+ var out CatalogProduct+ err := s.client.do(ctx, "GET", s.sessionBase(sessionID)+"/catalog/products/"+pathEscape(productID), nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// SendProduct sends a product message. Requires an OPERATOR-level key.+func (s *CatalogService) SendProduct(ctx context.Context, sessionID string, body SendProductRequest) (*MessageResponse, error) {+ var out MessageResponse+ err := s.client.do(ctx, "POST", s.sessionBase(sessionID)+"/messages/send-product", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// SendCatalog sends a catalog link message. Requires an OPERATOR-level key.+func (s *CatalogService) SendCatalog(ctx context.Context, sessionID string, body SendCatalogRequest) (*MessageResponse, error) {+ var out MessageResponse+ err := s.client.do(ctx, "POST", s.sessionBase(sessionID)+"/messages/send-catalog", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/sdk/go/channels.go b/sdk/go/channels.gonew file mode 100644index 000000000..7d730751f--- /dev/null+++ b/sdk/go/channels.go@@ -0,0 +1,55 @@+package openwa++import "context"++// ChannelsService manages WhatsApp Channels / Newsletters.+// Backed by src/modules/channel/channel.controller.ts.+type ChannelsService struct{ client *Client }++func (s *ChannelsService) base(sessionID string) string {+ return "/api/sessions/" + pathEscape(sessionID) + "/channels"+}++// List returns channels for a session.+func (s *ChannelsService) List(ctx context.Context, sessionID string) ([]ChannelRecord, error) {+ var out []ChannelRecord+ err := s.client.do(ctx, "GET", s.base(sessionID), nil, nil, &out)+ return out, err+}++// Get returns a single channel.+func (s *ChannelsService) Get(ctx context.Context, sessionID, channelID string) (*ChannelRecord, error) {+ var out ChannelRecord+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(channelID), nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Messages returns recent messages from a channel.+func (s *ChannelsService) Messages(ctx context.Context, sessionID, channelID string, query *ChannelMessageQuery) ([]MessageRecord, error) {+ var out []MessageRecord+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(channelID)+"/messages", valuesOf(query), nil, &out)+ return out, err+}++// Subscribe subscribes to a channel by invite code. Requires an OPERATOR-level key.+func (s *ChannelsService) Subscribe(ctx context.Context, sessionID string, body SubscribeChannelRequest) (*ChannelRecord, error) {+ var out ChannelRecord+ err := s.client.do(ctx, "POST", s.base(sessionID)+"/subscribe", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Unsubscribe unsubscribes from a channel. Requires an OPERATOR-level key.+func (s *ChannelsService) Unsubscribe(ctx context.Context, sessionID, channelID string) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "DELETE", s.base(sessionID)+"/"+pathEscape(channelID), nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/sdk/go/chats.go b/sdk/go/chats.gonew file mode 100644index 000000000..08b438aa8--- /dev/null+++ b/sdk/go/chats.go@@ -0,0 +1,47 @@+package openwa++import "context"++// ChatsService operates on the chat list (read/unread/delete/typing state).+// These endpoints live under the session controller (/api/sessions/:id/chats/*).+type ChatsService struct{ client *Client }++func (s *ChatsService) base(sessionID string) string {+ return "/api/sessions/" + pathEscape(sessionID) + "/chats"+}++// List returns chats for a session.+func (s *ChatsService) List(ctx context.Context, sessionID string, query *ListChatsQuery) ([]ChatSummary, error) {+ var out []ChatSummary+ err := s.client.do(ctx, "GET", s.base(sessionID), valuesOf(query), nil, &out)+ return out, err+}++// MarkRead marks a chat as read.+func (s *ChatsService) MarkRead(ctx context.Context, sessionID string, body MarkChatRequest) (*SuccessResult, error) {+ return s.post(ctx, sessionID, "/read", body)+}++// MarkUnread marks a chat as unread.+func (s *ChatsService) MarkUnread(ctx context.Context, sessionID string, body MarkChatRequest) (*SuccessResult, error) {+ return s.post(ctx, sessionID, "/unread", body)+}++// Delete deletes a chat.+func (s *ChatsService) Delete(ctx context.Context, sessionID string, body DeleteChatRequest) (*SuccessResult, error) {+ return s.post(ctx, sessionID, "/delete", body)+}++// SendState sends a typing/recording/paused state.+func (s *ChatsService) SendState(ctx context.Context, sessionID string, body SendChatStateRequest) (*SuccessResult, error) {+ return s.post(ctx, sessionID, "/typing", body)+}++func (s *ChatsService) post(ctx context.Context, sessionID, suffix string, body any) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "POST", s.base(sessionID)+suffix, nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/sdk/go/client.go b/sdk/go/client.gonew file mode 100644index 000000000..c14a8ca38--- /dev/null+++ b/sdk/go/client.go@@ -0,0 +1,300 @@+// Package openwa is the official Go client for the OpenWA WhatsApp API Gateway.+//+// The single entry point is New, which returns a *Client whose exported fields+// are the domain services:+//+// client, err := openwa.New("http://localhost:2785", "owa_k1_…")+// if err != nil {+// log.Fatal(err)+// }+//+// ctx := context.Background()+// if _, err := client.Sessions.Start(ctx, "my-session"); err != nil {+// log.Fatal(err)+// }+// res, err := client.Messages.SendText(ctx, "my-session", openwa.SendTextRequest{+// ChatID: "[email protected]",+// Text: "Hello from the OpenWA Go SDK!",+// })+//+// Every network method is context-first. Configuration and dependency injection+// go through functional Options (WithHTTPClient, WithTransport, WithLogger,+// WithRetry, WithMiddleware). Errors are typed — match them with errors.Is+// against the sentinels (ErrNotFound, ErrConflict, …) or errors.As against+// *APIError.+//+// Use HTTPS in production: the API key is sent as X-API-Key on every request+// and is bearer-equivalent. Redirects are never followed, so the key is never+// re-sent to a redirect target.+package openwa++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "reflect"+ "strconv"+ "strings"+ "time"+)++// Client is the entry point to the OpenWA API. Construct it with New. It is safe+// for concurrent use by multiple goroutines. The exported service fields group+// the API by domain.+type Client struct {+ baseURL string+ httpClient *http.Client+ timeout time.Duration++ // Services.+ Sessions *SessionsService+ Messages *MessagesService+ Contacts *ContactsService+ Groups *GroupsService+ Webhooks *WebhooksService+ Chats *ChatsService+ Status *StatusService+ Labels *LabelsService+ Channels *ChannelsService+ Catalog *CatalogService+ Templates *TemplatesService+ Health *HealthService+ Search *SearchService+ Auth *AuthService+}++var localhostHosts = map[string]bool{"localhost": true, "127.0.0.1": true, "::1": true}++// New constructs a Client for the API at baseURL, authenticating with apiKey.+// Both are required. Everything else is configured through Options.+func New(baseURL, apiKey string, opts ...Option) (*Client, error) {+ if strings.TrimSpace(baseURL) == "" {+ return nil, errors.New("openwa: baseURL is required")+ }+ if strings.TrimSpace(apiKey) == "" {+ return nil, errors.New("openwa: apiKey is required")+ }++ cfg := &config{+ baseURL: strings.TrimRight(baseURL, "/"),+ apiKey: apiKey,+ timeout: DefaultTimeout,+ logger: nopLogger{},+ userAgent: DefaultUserAgent,+ }+ for _, opt := range opts {+ opt(cfg)+ }+ // A zero (or negative) timeout means "use the default" per WithTimeout's+ // documentation — never an infinite timeout, which would silently pin+ // goroutines waiting for a dead peer.+ if cfg.timeout <= 0 {+ cfg.timeout = DefaultTimeout+ }++ warnIfInsecure(cfg)++ base := cfg.baseTransport+ if base == nil {+ if cfg.httpClient != nil && cfg.httpClient.Transport != nil {+ base = cfg.httpClient.Transport+ } else {+ base = http.DefaultTransport+ }+ }+ pipeline := buildTransport(cfg, base)++ hc := &http.Client{+ Transport: pipeline,+ // Never auto-follow redirects: doing so would re-send X-API-Key to the+ // redirect target. ErrUseLastResponse surfaces the 3xx to do(), which+ // then treats it as an error.+ CheckRedirect: func(*http.Request, []*http.Request) error {+ return http.ErrUseLastResponse+ },+ Timeout: cfg.timeout,+ }+ if cfg.httpClient != nil {+ hc.Jar = cfg.httpClient.Jar+ if cfg.httpClient.Timeout > 0 {+ hc.Timeout = cfg.httpClient.Timeout+ }+ }+ // An explicit WithTimeout always wins.+ if cfg.timeout > 0 {+ hc.Timeout = cfg.timeout+ }++ c := &Client{+ baseURL: cfg.baseURL,+ httpClient: hc,+ timeout: hc.Timeout,+ }+ c.Sessions = &SessionsService{client: c}+ c.Messages = &MessagesService{client: c}+ c.Contacts = &ContactsService{client: c}+ c.Groups = &GroupsService{client: c}+ c.Webhooks = &WebhooksService{client: c}+ c.Chats = &ChatsService{client: c}+ c.Status = &StatusService{client: c}+ c.Labels = &LabelsService{client: c}+ c.Channels = &ChannelsService{client: c}+ c.Catalog = &CatalogService{client: c}+ c.Templates = &TemplatesService{client: c}+ c.Health = &HealthService{client: c}+ c.Search = &SearchService{client: c}+ c.Auth = &AuthService{client: c}+ return c, nil+}++func warnIfInsecure(cfg *config) {+ if cfg.allowInsecure {+ return+ }+ u, err := url.Parse(cfg.baseURL)+ if err != nil {+ 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)+ }+}++// Do issues a raw request against the API and decodes the JSON response into+// out (pass nil to ignore the body). It is the escape hatch for endpoints the+// typed services do not cover. path must begin with "/".+func (c *Client) Do(ctx context.Context, method, path string, query url.Values, body, out any) error {+ return c.do(ctx, method, path, query, body, out)+}++func (c *Client) do(ctx context.Context, method, path string, query url.Values, body, out any) error {+ var bodyBytes []byte+ var reader io.Reader+ if body != nil {+ b, err := json.Marshal(body)+ if err != nil {+ return fmt.Errorf("openwa: encoding request body: %w", err)+ }+ bodyBytes = b+ reader = bytes.NewReader(b)+ }++ rawURL := c.baseURL + path+ if len(query) > 0 {+ rawURL += "?" + query.Encode()+ }++ req, err := http.NewRequestWithContext(ctx, method, rawURL, reader)+ if err != nil {+ return fmt.Errorf("openwa: building request: %w", err)+ }+ if body != nil {+ req.Header.Set("Content-Type", "application/json")+ req.ContentLength = int64(len(bodyBytes))+ // GetBody lets the retry middleware rewind the body on each attempt.+ req.GetBody = func() (io.ReadCloser, error) {+ return io.NopCloser(bytes.NewReader(bodyBytes)), nil+ }+ }++ resp, err := c.httpClient.Do(req)+ if err != nil {+ if isTimeout(err) {+ return &TimeoutError{Timeout: c.timeout, Err: err}+ }+ return fmt.Errorf("openwa: %s %s: %w", method, path, err)+ }+ defer resp.Body.Close()++ data, err := io.ReadAll(resp.Body)+ if err != nil {+ return fmt.Errorf("openwa: reading response body: %w", err)+ }++ // Any non-2xx (including an unfollowed 3xx) is an error.+ if resp.StatusCode >= 300 {+ return parseAPIError(resp.StatusCode, data, method+" "+path)+ }+ if out == nil || resp.StatusCode == http.StatusNoContent || len(data) == 0 {+ return nil+ }+ if err := json.Unmarshal(data, out); err != nil {+ return fmt.Errorf("openwa: decoding response: %w", err)+ }+ return nil+}++func isTimeout(err error) bool {+ if errors.Is(err, context.DeadlineExceeded) {+ return true+ }+ var timeouter interface{ Timeout() bool }+ if errors.As(err, &timeouter) {+ return timeouter.Timeout()+ }+ return false+}++// pathEscape percent-encodes a single path segment so a value containing "/",+// "#", or "?" can't break out of its path position. WhatsApp-JID characters+// that are already path-safe ("@", ":", "+") are kept readable.+func pathEscape(segment string) string {+ escaped := url.PathEscape(segment)+ return jidRestorer.Replace(escaped)+}++var jidRestorer = strings.NewReplacer("%40", "@", "%3A", ":", "%2B", "+")++// query helpers used by the typed *Query structs.++func setStr(v url.Values, key string, p *string) {+ if p != nil {+ v.Set(key, *p)+ }+}++func setInt(v url.Values, key string, p *int) {+ if p != nil {+ v.Set(key, strconv.Itoa(*p))+ }+}++func setBool(v url.Values, key string, p *bool) {+ if p != nil {+ if *p {+ v.Set(key, "true")+ } else {+ v.Set(key, "false")+ }+ }+}++func setInt64(v url.Values, key string, p *int64) {+ if p != nil {+ v.Set(key, strconv.FormatInt(*p, 10))+ }+}++// queryValuer is implemented by the typed *Query structs.+type queryValuer interface{ values() url.Values }++// valuesOf encodes a query, treating a nil (including a typed-nil pointer) as+// "no query params".+func valuesOf(q queryValuer) url.Values {+ if q == nil {+ return nil+ }+ rv := reflect.ValueOf(q)+ if rv.Kind() == reflect.Ptr && rv.IsNil() {+ return nil+ }+ return q.values()+}diff --git a/sdk/go/client_test.go b/sdk/go/client_test.gonew file mode 100644index 000000000..5727ac951--- /dev/null+++ b/sdk/go/client_test.go@@ -0,0 +1,517 @@+package openwa++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++// recordTransport is a mock http.RoundTripper that records the last request and+// replies with a canned response. It is injected via WithTransport — no network,+// no global state.+type recordTransport struct {+ status int+ body string+ header http.Header+ lastReq *http.Request+ lastRaw []byte+}++func (t *recordTransport) RoundTrip(req *http.Request) (*http.Response, error) {+ if err := req.Context().Err(); err != nil {+ return nil, err+ }+ t.lastReq = req+ if req.Body != nil {+ t.lastRaw, _ = io.ReadAll(req.Body)+ }+ h := t.header+ if h == nil {+ h = http.Header{}+ }+ return &http.Response{+ StatusCode: t.status,+ Body: io.NopCloser(strings.NewReader(t.body)),+ Header: h,+ Request: req,+ }, nil+}++func newTestClient(t *testing.T, rt http.RoundTripper, opts ...Option) *Client {+ t.Helper()+ all := append([]Option{WithTransport(rt)}, opts...)+ c, err := New("https://api.example.com", "owa_k1_test", all...)+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ return c+}++func TestNewValidation(t *testing.T) {+ if _, err := New("", "key"); err == nil {+ t.Fatal("expected error for empty baseURL")+ }+ if _, err := New("https://x", ""); err == nil {+ t.Fatal("expected error for empty apiKey")+ }+}++func TestSendTextHitsCorrectPath(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{"messageId":"m1","timestamp":123}`}+ c := newTestClient(t, rt)++ res, err := c.Messages.SendText(context.Background(), "s1", SendTextRequest{+ ChatID: "[email protected]",+ Text: "hi",+ })+ if err != nil {+ t.Fatalf("SendText: %v", err)+ }+ if res.MessageID != "m1" || res.Timestamp != 123 {+ t.Fatalf("unexpected response: %+v", res)+ }++ // The historically-broken path was /messages/text; the real one is send-text.+ wantPath := "/api/sessions/s1/messages/send-text"+ if got := rt.lastReq.URL.Path; got != wantPath {+ t.Fatalf("path = %q, want %q", got, wantPath)+ }+ if rt.lastReq.Method != "POST" {+ t.Fatalf("method = %q, want POST", rt.lastReq.Method)+ }+ if got := rt.lastReq.Header.Get("X-API-Key"); got != "owa_k1_test" {+ t.Fatalf("X-API-Key = %q", got)+ }++ var sent SendTextRequest+ if err := json.Unmarshal(rt.lastRaw, &sent); err != nil {+ t.Fatalf("body not JSON: %v", err)+ }+ if sent.ChatID != "[email protected]" || sent.Text != "hi" {+ t.Fatalf("sent body = %+v", sent)+ }+}++func TestJIDPathIsReadable(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{}`}+ c := newTestClient(t, rt)++ _, _ = c.Contacts.Check(context.Background(), "s1", "[email protected]")+ // @ stays readable, not percent-encoded.+ want := "/api/sessions/s1/contacts/check/[email protected]"+ if got := rt.lastReq.URL.EscapedPath(); got != want {+ t.Fatalf("escaped path = %q, want %q", got, want)+ }+}++func TestQueryEncoding(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{"messages":[],"total":0}`}+ c := newTestClient(t, rt)++ _, err := c.Messages.List(context.Background(), "s1", &ListMessagesQuery{+ ChatID: Ptr("[email protected]"),+ Limit: Ptr(10),+ })+ if err != nil {+ t.Fatalf("List: %v", err)+ }+ q := rt.lastReq.URL.Query()+ if q.Get("chatId") != "[email protected]" || q.Get("limit") != "10" {+ t.Fatalf("query = %v", rt.lastReq.URL.RawQuery)+ }+ if _, ok := q["offset"]; ok {+ t.Fatal("nil offset should not appear in query")+ }+}++func TestNilQueryOmitted(t *testing.T) {+ rt := &recordTransport{status: 200, body: `[]`}+ c := newTestClient(t, rt)++ // Typed-nil pointer must not panic and must send no query string.+ var q *ListContactsQuery+ if _, err := c.Contacts.List(context.Background(), "s1", q); err != nil {+ t.Fatalf("List: %v", err)+ }+ if rt.lastReq.URL.RawQuery != "" {+ t.Fatalf("expected empty query, got %q", rt.lastReq.URL.RawQuery)+ }+}++func TestTypedErrors(t *testing.T) {+ rt := &recordTransport{+ status: 409,+ body: `{"statusCode":409,"message":"engine not ready","error":"Conflict"}`,+ }+ c := newTestClient(t, rt)++ _, err := c.Messages.SendText(context.Background(), "s1", SendTextRequest{ChatID: "x", Text: "y"})+ if err == nil {+ t.Fatal("expected error")+ }+ if !errors.Is(err, ErrConflict) {+ t.Fatalf("errors.Is ErrConflict = false for %v", err)+ }+ var apiErr *APIError+ if !errors.As(err, &apiErr) {+ t.Fatalf("errors.As *APIError failed for %v", err)+ }+ if apiErr.StatusCode != 409 || apiErr.Kind != "Conflict" || apiErr.Message != "engine not ready" {+ t.Fatalf("APIError = %+v", apiErr)+ }+}++func TestArrayMessageError(t *testing.T) {+ rt := &recordTransport{+ status: 400,+ body: `{"statusCode":400,"message":["chatId must be a string","text should not be empty"],"error":"Bad Request"}`,+ }+ c := newTestClient(t, rt)++ _, err := c.Messages.SendText(context.Background(), "s1", SendTextRequest{})+ var apiErr *APIError+ if !errors.As(err, &apiErr) {+ t.Fatalf("expected APIError, got %v", err)+ }+ if !strings.Contains(apiErr.Message, "chatId must be a string, text should not be empty") {+ t.Fatalf("message = %q", apiErr.Message)+ }+}++func TestRedirectNotFollowed(t *testing.T) {+ rt := &recordTransport{status: 302, body: "", header: http.Header{"Location": {"https://evil.example"}}}+ c := newTestClient(t, rt)+ _, err := c.Sessions.List(context.Background(), nil)+ var apiErr *APIError+ if !errors.As(err, &apiErr) || apiErr.StatusCode != 302 {+ t.Fatalf("expected 302 APIError, got %v", err)+ }+}++func TestDeleteReturnsNoBody(t *testing.T) {+ rt := &recordTransport{status: 204, body: ""}+ c := newTestClient(t, rt)+ if err := c.Sessions.Delete(context.Background(), "s1"); err != nil {+ t.Fatalf("Delete: %v", err)+ }+ if rt.lastReq.Method != "DELETE" {+ t.Fatalf("method = %q", rt.lastReq.Method)+ }+}++// retryTransport fails the first N calls with a 503, then succeeds. It rewinds+// and asserts the body is present on every attempt.+type retryTransport struct {+ failuresLeft int32+ calls int32+ gotBodies []string+}++func (t *retryTransport) RoundTrip(req *http.Request) (*http.Response, error) {+ atomic.AddInt32(&t.calls, 1)+ var b []byte+ if req.Body != nil {+ b, _ = io.ReadAll(req.Body)+ }+ t.gotBodies = append(t.gotBodies, string(b))+ if atomic.AddInt32(&t.failuresLeft, -1) >= 0 {+ return &http.Response{StatusCode: 503, Body: io.NopCloser(bytes.NewReader(nil)), Header: http.Header{}, Request: req}, nil+ }+ return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"messageId":"ok","timestamp":1}`)), Header: http.Header{}, Request: req}, nil+}++func TestRetryPolicy(t *testing.T) {+ rt := &retryTransport{failuresLeft: 2}+ c := newTestClient(t, rt, WithRetry(RetryPolicy{+ MaxRetries: 3,+ BaseDelay: time.Millisecond,+ MaxDelay: 5 * time.Millisecond,+ }))++ res, err := c.Messages.SendText(context.Background(), "s1", SendTextRequest{ChatID: "x", Text: "y"})+ if err != nil {+ t.Fatalf("SendText with retry: %v", err)+ }+ if res.MessageID != "ok" {+ t.Fatalf("res = %+v", res)+ }+ if rt.calls != 3 {+ t.Fatalf("expected 3 attempts, got %d", rt.calls)+ }+ // Body must be re-sent (rewound) on every attempt.+ for i, b := range rt.gotBodies {+ if !strings.Contains(b, `"chatId":"x"`) {+ t.Fatalf("attempt %d had empty/rewound-broken body: %q", i, b)+ }+ }+}++func TestMiddlewarePipeline(t *testing.T) {+ rt := &recordTransport{status: 200, body: `[]`}+ var hits int32+ mw := func(next http.RoundTripper) http.RoundTripper {+ return RoundTripperFunc(func(req *http.Request) (*http.Response, error) {+ atomic.AddInt32(&hits, 1)+ req.Header.Set("X-Trace", "on")+ return next.RoundTrip(req)+ })+ }+ c := newTestClient(t, rt, WithMiddleware(mw))+ if _, err := c.Sessions.List(context.Background(), nil); err != nil {+ t.Fatalf("List: %v", err)+ }+ if hits != 1 {+ t.Fatalf("middleware hits = %d, want 1", hits)+ }+ if rt.lastReq.Header.Get("X-Trace") != "on" {+ t.Fatal("middleware header not propagated")+ }+}++// retryAfterTransport replies once with 429 + Retry-After, then success. It+// records the delay between the two calls so a test can assert Retry-After was+// honored.+type retryAfterTransport struct {+ calls int32+ stamps []time.Time+ header string+}++func (t *retryAfterTransport) RoundTrip(req *http.Request) (*http.Response, error) {+ atomic.AddInt32(&t.calls, 1)+ t.stamps = append(t.stamps, time.Now())+ if req.Body != nil {+ _, _ = io.ReadAll(req.Body)+ }+ if t.calls == 1 {+ return &http.Response{+ StatusCode: 429,+ Body: io.NopCloser(strings.NewReader("")),+ Header: http.Header{"Retry-After": {t.header}},+ Request: req,+ }, nil+ }+ return &http.Response{+ StatusCode: 200,+ Body: io.NopCloser(strings.NewReader(`{"messageId":"ok","timestamp":1}`)),+ Header: http.Header{},+ Request: req,+ }, nil+}++func TestRetryHonorsRetryAfter(t *testing.T) {+ rt := &retryAfterTransport{header: "1"}+ c := newTestClient(t, rt, WithRetry(RetryPolicy{+ MaxRetries: 2,+ BaseDelay: time.Millisecond, // computed backoff = 1ms; Retry-After = 1s dominates+ MaxDelay: 10 * time.Millisecond,+ RetryableStatuses: []int{429},+ RespectRetryAfter: true,+ }))++ if _, err := c.Messages.SendText(context.Background(), "s1", SendTextRequest{ChatID: "x", Text: "y"}); err != nil {+ t.Fatalf("SendText: %v", err)+ }+ if rt.calls != 2 {+ t.Fatalf("expected 2 attempts, got %d", rt.calls)+ }+ waited := rt.stamps[1].Sub(rt.stamps[0])+ if waited < 900*time.Millisecond {+ t.Fatalf("expected to wait ~1s for Retry-After, waited %s", waited)+ }+}++func TestParseRetryAfterHTTPDate(t *testing.T) {+ resp := &http.Response{Header: http.Header{"Retry-After": {time.Now().Add(2 * time.Second).UTC().Format(http.TimeFormat)}}}+ d, ok := parseRetryAfter(resp)+ if !ok {+ t.Fatal("expected HTTP-date Retry-After to parse")+ }+ if d < time.Second || d > 3*time.Second {+ t.Fatalf("unexpected duration: %s", d)+ }+}++// networkErrTransport always returns a network error, so it exercises the+// "retry on network error" branch instead of the "retry on status code" branch.+type networkErrTransport struct{ calls int32 }++func (t *networkErrTransport) RoundTrip(req *http.Request) (*http.Response, error) {+ atomic.AddInt32(&t.calls, 1)+ return nil, errors.New("simulated network failure")+}++func TestRetrySkipsNonIdempotentOnNetworkError(t *testing.T) {+ rt := &networkErrTransport{}+ c := newTestClient(t, rt, WithRetry(RetryPolicy{+ MaxRetries: 3,+ BaseDelay: time.Millisecond,+ MaxDelay: time.Millisecond,+ }))++ // POST is not idempotent: a network error must NOT retry, or a message+ // could be double-sent.+ _, err := c.Messages.SendText(context.Background(), "s1", SendTextRequest{ChatID: "x", Text: "y"})+ if err == nil {+ t.Fatal("expected error")+ }+ if rt.calls != 1 {+ t.Fatalf("expected 1 attempt for POST on network error, got %d", rt.calls)+ }+}++func TestRetryIdempotentOnNetworkError(t *testing.T) {+ rt := &networkErrTransport{}+ c := newTestClient(t, rt, WithRetry(RetryPolicy{+ MaxRetries: 2,+ BaseDelay: time.Millisecond,+ MaxDelay: time.Millisecond,+ }))++ // GET is idempotent: a network error is safe to retry.+ _, err := c.Sessions.List(context.Background(), nil)+ if err == nil {+ t.Fatal("expected error")+ }+ if rt.calls != 3 {+ t.Fatalf("expected 3 attempts (1 + 2 retries) for GET on network error, got %d", rt.calls)+ }+}++func TestBadRequestSentinel(t *testing.T) {+ rt := &recordTransport{+ status: 400,+ body: `{"statusCode":400,"message":"invalid","error":"Bad Request"}`,+ }+ c := newTestClient(t, rt)+ _, err := c.Messages.SendText(context.Background(), "s1", SendTextRequest{})+ if err == nil {+ t.Fatal("expected error")+ }+ if !errors.Is(err, ErrBadRequest) {+ t.Fatalf("errors.Is ErrBadRequest = false for %v", err)+ }+}++func TestStatusListEnvelope(t *testing.T) {+ rt := &recordTransport{+ status: 200,+ body: `{"statuses":[{"id":"s","contact":{"id":"[email protected]","name":"Cat"},"type":"text","mediaUrl":"","caption":"hi"}]}`,+ }+ c := newTestClient(t, rt)++ got, err := c.Status.List(context.Background(), "s1")+ if err != nil {+ t.Fatalf("Status.List: %v", err)+ }+ if len(got) != 1 || got[0].ID != "s" || got[0].Contact.Name != "Cat" {+ t.Fatalf("unexpected decode: %+v", got)+ }+}++func TestHealthReadyDependencyDecode(t *testing.T) {+ rt := &recordTransport{+ status: 200,+ body: `{"status":"ok","details":{"mainDatabase":{"status":"up"},"dataDatabase":{"status":"up"}}}`,+ }+ c := newTestClient(t, rt)++ res, err := c.Health.Ready(context.Background())+ if err != nil {+ t.Fatalf("Health.Ready: %v", err)+ }+ if res.Details["mainDatabase"].Status != "up" || res.Details["dataDatabase"].Status != "up" {+ t.Fatalf("unexpected details: %+v", res.Details)+ }+}++func TestWithHeaderMultiValue(t *testing.T) {+ rt := &recordTransport{status: 200, body: `[]`}+ c := newTestClient(t, rt,+ WithHeader("X-Trace", "a"),+ WithHeader("X-Trace", "b"),+ )+ if _, err := c.Sessions.List(context.Background(), nil); err != nil {+ t.Fatalf("List: %v", err)+ }+ got := rt.lastReq.Header.Values("X-Trace")+ if len(got) != 2 || got[0] != "a" || got[1] != "b" {+ t.Fatalf("X-Trace values = %v, want [a b]", got)+ }+}++func TestWithTimeoutZeroUsesDefault(t *testing.T) {+ rt := &recordTransport{status: 200, body: `[]`}+ c := newTestClient(t, rt, WithTimeout(0))+ if c.timeout != DefaultTimeout {+ t.Fatalf("timeout = %s, want %s", c.timeout, DefaultTimeout)+ }+}++func TestBulkMediaContentOmitsChatID(t *testing.T) {+ // The bulk media block must not emit a chatId key — the outer item carries+ // it, and BulkMediaDto rejects a stray empty one via forbidNonWhitelisted.+ body := SendBulkRequest{+ Messages: []BulkMessageItem{{+ ChatID: "[email protected]",+ Type: "image",+ Content: BulkMessageContent{+ Image: &BulkMediaContent{URL: "https://x/y.png"},+ },+ }},+ }+ raw, err := json.Marshal(body)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ if strings.Contains(string(raw), `"chatId":""`) {+ t.Fatalf("bulk media block must not emit empty chatId; got: %s", raw)+ }+}++func TestBulkAudioSerializesPTT(t *testing.T) {+ // Bulk audio with PTT must emit "ptt":true so the server sends it as a voice+ // note; the media block must not emit a "caption" key (not whitelisted by+ // BulkMediaDto — caption lives at the content level).+ body := SendBulkRequest{+ Messages: []BulkMessageItem{{+ ChatID: "[email protected]",+ Type: "audio",+ Content: BulkMessageContent{+ Audio: &BulkMediaContent{URL: "https://x/v.ogg", PTT: true},+ Caption: "voicenote",+ },+ }},+ }+ raw, err := json.Marshal(body)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ if !strings.Contains(string(raw), `"ptt":true`) {+ t.Fatalf("bulk audio must emit ptt:true; got: %s", raw)+ }+ audioBlock := string(raw)+ if i := strings.Index(audioBlock, `"audio":{`); i >= 0 {+ if j := strings.Index(audioBlock[i:], "}"); j >= 0 && strings.Contains(audioBlock[i:i+j], `"caption"`) {+ t.Fatalf("bulk media block must not emit caption; got: %s", raw)+ }+ }+}++func TestContextCancel(t *testing.T) {+ rt := &recordTransport{status: 200, body: `[]`}+ c := newTestClient(t, rt)+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ _, err := c.Sessions.List(ctx, nil)+ if err == nil {+ t.Fatal("expected context cancellation error")+ }+}diff --git a/sdk/go/contacts.go b/sdk/go/contacts.gonew file mode 100644index 000000000..24891b769--- /dev/null+++ b/sdk/go/contacts.go@@ -0,0 +1,78 @@+package openwa++import "context"++// ContactsService looks up and manages contacts.+// Backed by src/modules/contact/contact.controller.ts.+type ContactsService struct{ client *Client }++func (s *ContactsService) base(sessionID string) string {+ return "/api/sessions/" + pathEscape(sessionID) + "/contacts"+}++// List returns contacts for a session.+func (s *ContactsService) List(ctx context.Context, sessionID string, query *ListContactsQuery) ([]ContactRecord, error) {+ var out []ContactRecord+ err := s.client.do(ctx, "GET", s.base(sessionID), valuesOf(query), nil, &out)+ return out, err+}++// Get returns a single contact.+func (s *ContactsService) Get(ctx context.Context, sessionID, contactID string) (*ContactRecord, error) {+ var out ContactRecord+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(contactID), nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Check reports whether a number is on WhatsApp.+func (s *ContactsService) Check(ctx context.Context, sessionID, number string) (*CheckNumberResponse, error) {+ var out CheckNumberResponse+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/check/"+pathEscape(number), nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// ProfilePicture returns a contact's profile picture URL.+func (s *ContactsService) ProfilePicture(ctx context.Context, sessionID, contactID string) (*ProfilePictureResponse, error) {+ var out ProfilePictureResponse+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(contactID)+"/profile-picture", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Phone resolves a contact's phone number.+func (s *ContactsService) Phone(ctx context.Context, sessionID, contactID string) (*ContactPhoneResponse, error) {+ var out ContactPhoneResponse+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(contactID)+"/phone", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Block blocks a contact.+func (s *ContactsService) Block(ctx context.Context, sessionID, contactID string) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "POST", s.base(sessionID)+"/"+pathEscape(contactID)+"/block", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Unblock unblocks a contact.+func (s *ContactsService) Unblock(ctx context.Context, sessionID, contactID string) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "DELETE", s.base(sessionID)+"/"+pathEscape(contactID)+"/block", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/sdk/go/errors.go b/sdk/go/errors.gonew file mode 100644index 000000000..930ded586--- /dev/null+++ b/sdk/go/errors.go@@ -0,0 +1,166 @@+package openwa++import (+ "encoding/json"+ "errors"+ "fmt"+ "time"+)++// Sentinel errors for the common failure modes. Match them with errors.Is:+//+// if errors.Is(err, openwa.ErrNotFound) { ... }+//+// They are matched against an *APIError by its HTTP status code, so you never+// need to inspect the status yourself for the common cases. For everything else+// (or to read the response body), unwrap the concrete type with errors.As:+//+// var apiErr *openwa.APIError+// if errors.As(err, &apiErr) { log.Println(apiErr.StatusCode, apiErr.Body) }+var (+ // ErrBadRequest is returned for a 400 (invalid request payload).+ ErrBadRequest = errors.New("openwa: bad request")+ // ErrUnauthorized is returned for a 401 (missing or invalid API key).+ ErrUnauthorized = errors.New("openwa: unauthorized")+ // ErrForbidden is returned for a 403 (insufficient role).+ ErrForbidden = errors.New("openwa: forbidden")+ // ErrNotFound is returned for a 404.+ ErrNotFound = errors.New("openwa: not found")+ // ErrConflict is returned for a 409 (typically an engine-not-ready condition).+ ErrConflict = errors.New("openwa: conflict")+ // ErrRateLimited is returned for a 429 (too many requests).+ ErrRateLimited = errors.New("openwa: rate limited")+ // ErrNotImplemented is returned for a 501 (the active engine does not+ // support this operation).+ ErrNotImplemented = errors.New("openwa: not implemented")+)++// APIError is returned when the API responds with a non-2xx status. A 3xx also+// surfaces as an APIError: redirects are deliberately never followed, so the+// API key is never re-sent to a redirect target.+type APIError struct {+ // StatusCode is the HTTP status code of the response.+ StatusCode int+ // Message is a human-readable description derived from the NestJS error+ // envelope (or the raw body when the response is not the standard shape).+ Message string+ // Kind is the value of the NestJS envelope's "error" field (e.g.+ // "Not Found", "Conflict"), when present.+ Kind string+ // Body is the parsed JSON body, or the raw string when the body is not+ // valid JSON.+ Body any+ // Context is the "METHOD /path" that produced the error.+ Context string+}++func (e *APIError) Error() string {+ return fmt.Sprintf("openwa: API %d — %s: %s", e.StatusCode, e.Context, e.Message)+}++// Is bridges the concrete APIError to the sentinel errors above so callers can+// use errors.Is(err, ErrNotFound) without matching on the status code directly.+func (e *APIError) Is(target error) bool {+ switch e.StatusCode {+ case 400:+ return target == ErrBadRequest+ case 401:+ return target == ErrUnauthorized+ case 403:+ return target == ErrForbidden+ case 404:+ return target == ErrNotFound+ case 409:+ return target == ErrConflict+ case 429:+ return target == ErrRateLimited+ case 501:+ return target == ErrNotImplemented+ }+ return false+}++// TimeoutError is returned when a request exceeds the configured timeout (or the+// caller's context deadline).+type TimeoutError struct {+ Timeout time.Duration+ // Err is the underlying cause (context.DeadlineExceeded or a net timeout).+ Err error+}++func (e *TimeoutError) Error() string {+ if e.Timeout > 0 {+ return fmt.Sprintf("openwa: request timed out after %s", e.Timeout)+ }+ return "openwa: request timed out"+}++func (e *TimeoutError) Unwrap() error { return e.Err }++// nestEnvelope is the standard NestJS error shape:+// {"statusCode": int, "message": string|[]string, "error": string}.+type nestEnvelope struct {+ StatusCode int `json:"statusCode"`+ Message json.RawMessage `json:"message"`+ Error string `json:"error"`+}++// parseAPIError builds an *APIError from a raw response body, extracting a+// readable message from the NestJS envelope when the body matches that shape.+func parseAPIError(status int, raw []byte, context string) *APIError {+ var body any+ var envelope *nestEnvelope++ if len(raw) > 0 {+ if err := json.Unmarshal(raw, &body); err != nil {+ body = string(raw)+ }+ var env nestEnvelope+ if err := json.Unmarshal(raw, &env); err == nil && env.StatusCode != 0 {+ envelope = &env+ }+ }++ message := messageFromEnvelope(envelope, body)+ kind := ""+ if envelope != nil {+ kind = envelope.Error+ }++ return &APIError{+ StatusCode: status,+ Message: message,+ Kind: kind,+ Body: body,+ Context: context,+ }+}++func messageFromEnvelope(envelope *nestEnvelope, body any) string {+ if envelope != nil && len(envelope.Message) > 0 {+ // message may be a string or an array of strings.+ var single string+ if err := json.Unmarshal(envelope.Message, &single); err == nil {+ return single+ }+ var many []string+ if err := json.Unmarshal(envelope.Message, &many); err == nil {+ return joinComma(many)+ }+ }+ if s, ok := body.(string); ok && s != "" {+ return s+ }+ return "request failed"+}++func joinComma(parts []string) string {+ out := ""+ for i, p := range parts {+ if i > 0 {+ out += ", "+ }+ out += p+ }+ return out+}diff --git a/sdk/go/example_test.go b/sdk/go/example_test.gonew file mode 100644index 000000000..e5761720d--- /dev/null+++ b/sdk/go/example_test.go@@ -0,0 +1,62 @@+package openwa_test++import (+ "context"+ "errors"+ "fmt"+ "log"+ "time"++ openwa "github.com/rmyndharis/OpenWA/sdk/go"+)++func ExampleNew() {+ client, err := openwa.New("http://localhost:2785", "owa_k1_…")+ if err != nil {+ log.Fatal(err)+ }++ ctx := context.Background()+ if _, err := client.Sessions.Start(ctx, "my-session"); err != nil {+ log.Fatal(err)+ }++ res, err := client.Messages.SendText(ctx, "my-session", openwa.SendTextRequest{+ ChatID: "[email protected]",+ Text: "Hello from the OpenWA Go SDK!",+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Println(res.MessageID)+}++func ExampleClient_typedErrors() {+ client, _ := openwa.New("http://localhost:2785", "owa_k1_…")++ _, err := client.Messages.SendText(context.Background(), "my-session", openwa.SendTextRequest{+ ChatID: "[email protected]",+ Text: "hi",+ })+ switch {+ case errors.Is(err, openwa.ErrConflict):+ // Engine not ready (409) — retry after the session reaches "ready".+ case errors.Is(err, openwa.ErrNotFound):+ // Unknown session (404).+ case err != nil:+ var apiErr *openwa.APIError+ if errors.As(err, &apiErr) {+ log.Printf("API %d: %s", apiErr.StatusCode, apiErr.Message)+ }+ }+}++func ExampleWithRetry() {+ // Opt into automatic retries with exponential backoff, and inject a custom+ // per-request timeout — dependencies flow through functional options.+ client, _ := openwa.New("http://localhost:2785", "owa_k1_…",+ openwa.WithRetry(openwa.DefaultRetryPolicy()),+ openwa.WithTimeout(15*time.Second),+ )+ _ = client+}diff --git a/sdk/go/go.mod b/sdk/go/go.modnew file mode 100644index 000000000..cad41b507--- /dev/null+++ b/sdk/go/go.mod@@ -0,0 +1,3 @@+module github.com/rmyndharis/OpenWA/sdk/go++go 1.22diff --git a/sdk/go/groups.go b/sdk/go/groups.gonew file mode 100644index 000000000..d804ef5d6--- /dev/null+++ b/sdk/go/groups.go@@ -0,0 +1,120 @@+package openwa++import "context"++// GroupsService manages WhatsApp groups.+// Backed by src/modules/group/group.controller.ts.+type GroupsService struct{ client *Client }++func (s *GroupsService) base(sessionID string) string {+ return "/api/sessions/" + pathEscape(sessionID) + "/groups"+}++// List returns groups for a session.+func (s *GroupsService) List(ctx context.Context, sessionID string, query *ListGroupsQuery) ([]GroupSummary, error) {+ var out []GroupSummary+ err := s.client.do(ctx, "GET", s.base(sessionID), valuesOf(query), nil, &out)+ return out, err+}++// Get returns full group detail.+func (s *GroupsService) Get(ctx context.Context, sessionID, groupID string) (*GroupInfo, error) {+ var out GroupInfo+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(groupID), nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Create creates a group.+func (s *GroupsService) Create(ctx context.Context, sessionID string, body CreateGroupRequest) (*GroupInfo, error) {+ var out GroupInfo+ err := s.client.do(ctx, "POST", s.base(sessionID), nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// AddParticipants adds members to a group.+func (s *GroupsService) AddParticipants(ctx context.Context, sessionID, groupID string, participants []string) (*SuccessResult, error) {+ return s.participants(ctx, "POST", sessionID, groupID, "/participants", participants)+}++// RemoveParticipants removes members from a group.+func (s *GroupsService) RemoveParticipants(ctx context.Context, sessionID, groupID string, participants []string) (*SuccessResult, error) {+ return s.participants(ctx, "DELETE", sessionID, groupID, "/participants", participants)+}++// PromoteParticipants promotes members to admin.+func (s *GroupsService) PromoteParticipants(ctx context.Context, sessionID, groupID string, participants []string) (*SuccessResult, error) {+ return s.participants(ctx, "POST", sessionID, groupID, "/participants/promote", participants)+}++// DemoteParticipants demotes admins to member.+func (s *GroupsService) DemoteParticipants(ctx context.Context, sessionID, groupID string, participants []string) (*SuccessResult, error) {+ return s.participants(ctx, "POST", sessionID, groupID, "/participants/demote", participants)+}++func (s *GroupsService) participants(ctx context.Context, method, sessionID, groupID, suffix string, participants []string) (*SuccessResult, error) {+ var out SuccessResult+ body := map[string][]string{"participants": participants}+ err := s.client.do(ctx, method, s.base(sessionID)+"/"+pathEscape(groupID)+suffix, nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// SetSubject updates the group subject (name).+func (s *GroupsService) SetSubject(ctx context.Context, sessionID, groupID, subject string) (*SuccessResult, error) {+ var out SuccessResult+ body := map[string]string{"subject": subject}+ err := s.client.do(ctx, "PUT", s.base(sessionID)+"/"+pathEscape(groupID)+"/subject", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// SetDescription updates the group description.+func (s *GroupsService) SetDescription(ctx context.Context, sessionID, groupID, description string) (*SuccessResult, error) {+ var out SuccessResult+ body := map[string]string{"description": description}+ err := s.client.do(ctx, "PUT", s.base(sessionID)+"/"+pathEscape(groupID)+"/description", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Leave leaves a group.+func (s *GroupsService) Leave(ctx context.Context, sessionID, groupID string) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "POST", s.base(sessionID)+"/"+pathEscape(groupID)+"/leave", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// InviteCode returns the group invite code/link.+func (s *GroupsService) InviteCode(ctx context.Context, sessionID, groupID string) (*InviteCodeResponse, error) {+ var out InviteCodeResponse+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(groupID)+"/invite-code", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// RevokeInviteCode rotates the group invite code.+func (s *GroupsService) RevokeInviteCode(ctx context.Context, sessionID, groupID string) (*InviteCodeResponse, error) {+ var out InviteCodeResponse+ err := s.client.do(ctx, "POST", s.base(sessionID)+"/"+pathEscape(groupID)+"/invite-code/revoke", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/sdk/go/health.go b/sdk/go/health.gonew file mode 100644index 000000000..0ff2d0696--- /dev/null+++ b/sdk/go/health.go@@ -0,0 +1,34 @@+package openwa++import "context"++// HealthService exposes connectivity and readiness probes.+// Backed by src/modules/health/health.controller.ts.+type HealthService struct{ client *Client }++// Check returns the overall health payload.+func (s *HealthService) Check(ctx context.Context) (*HealthResponse, error) {+ var out HealthResponse+ err := s.client.do(ctx, "GET", "/api/health", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Live is the liveness probe.+func (s *HealthService) Live(ctx context.Context) (map[string]string, error) {+ var out map[string]string+ err := s.client.do(ctx, "GET", "/api/health/live", nil, nil, &out)+ return out, err+}++// Ready is the readiness probe.+func (s *HealthService) Ready(ctx context.Context) (*HealthReadyResponse, error) {+ var out HealthReadyResponse+ err := s.client.do(ctx, "GET", "/api/health/ready", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/sdk/go/labels.go b/sdk/go/labels.gonew file mode 100644index 000000000..3c0a82e06--- /dev/null+++ b/sdk/go/labels.go@@ -0,0 +1,55 @@+package openwa++import "context"++// LabelsService manages WhatsApp Business chat labels. The session must be a+// business account. Backed by src/modules/label/label.controller.ts.+type LabelsService struct{ client *Client }++func (s *LabelsService) base(sessionID string) string {+ return "/api/sessions/" + pathEscape(sessionID) + "/labels"+}++// List returns all labels.+func (s *LabelsService) List(ctx context.Context, sessionID string) ([]LabelRecord, error) {+ var out []LabelRecord+ err := s.client.do(ctx, "GET", s.base(sessionID), nil, nil, &out)+ return out, err+}++// Get returns a single label.+func (s *LabelsService) Get(ctx context.Context, sessionID, labelID string) (*LabelRecord, error) {+ var out LabelRecord+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(labelID), nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// ForChat returns the labels applied to a chat.+func (s *LabelsService) ForChat(ctx context.Context, sessionID, chatID string) ([]LabelRecord, error) {+ var out []LabelRecord+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/chat/"+pathEscape(chatID), nil, nil, &out)+ return out, err+}++// AddToChat applies a label to a chat. Requires an OPERATOR-level key.+func (s *LabelsService) AddToChat(ctx context.Context, sessionID, chatID string, body AddLabelRequest) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "POST", s.base(sessionID)+"/chat/"+pathEscape(chatID), nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// RemoveFromChat removes a label from a chat. Requires an OPERATOR-level key.+func (s *LabelsService) RemoveFromChat(ctx context.Context, sessionID, chatID, labelID string) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "DELETE", s.base(sessionID)+"/chat/"+pathEscape(chatID)+"/"+pathEscape(labelID), nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/sdk/go/logger.go b/sdk/go/logger.gonew file mode 100644index 000000000..c010e5481--- /dev/null+++ b/sdk/go/logger.go@@ -0,0 +1,31 @@+package openwa++import "context"++// Log levels passed to Logger.Log by the SDK's built-in middleware.+const (+ LevelDebug = "debug"+ LevelInfo = "info"+ LevelWarn = "warn"+ LevelError = "error"+)++// Logger is the minimal logging surface the SDK depends on. Inject your own+// implementation with WithLogger to bridge to slog, zap, logrus, or any other+// logger. kv is a flat list of alternating key/value pairs (like slog).+//+// A slog bridge is a few lines:+//+// type slogLogger struct{ l *slog.Logger }+// func (s slogLogger) Log(ctx context.Context, level, msg string, kv ...any) {+// s.l.Log(ctx, slog.LevelInfo, msg, kv...)+// }+type Logger interface {+ Log(ctx context.Context, level string, msg string, kv ...any)+}++// nopLogger discards all log records. It is the default when no logger is+// injected, so the SDK never writes anywhere the caller did not ask for.+type nopLogger struct{}++func (nopLogger) Log(context.Context, string, string, ...any) {}diff --git a/sdk/go/messages.go b/sdk/go/messages.gonew file mode 100644index 000000000..04eabee0f--- /dev/null+++ b/sdk/go/messages.go@@ -0,0 +1,154 @@+package openwa++import "context"++// MessagesService sends and queries messages.+// Backed by src/modules/message/message.controller.ts. NOTE: send paths use the+// "send-" prefix (e.g. /messages/send-text).+type MessagesService struct{ client *Client }++func (s *MessagesService) base(sessionID string) string {+ return "/api/sessions/" + pathEscape(sessionID) + "/messages"+}++// List returns persisted messages for a session.+func (s *MessagesService) List(ctx context.Context, sessionID string, query *ListMessagesQuery) (*MessageListResponse, error) {+ var out MessageListResponse+ err := s.client.do(ctx, "GET", s.base(sessionID), valuesOf(query), nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// SendText sends a plain text message.+func (s *MessagesService) SendText(ctx context.Context, sessionID string, body SendTextRequest) (*MessageResponse, error) {+ return s.send(ctx, sessionID, "send-text", body)+}++// SendImage sends an image.+func (s *MessagesService) SendImage(ctx context.Context, sessionID string, body SendMediaRequest) (*MessageResponse, error) {+ return s.send(ctx, sessionID, "send-image", body)+}++// SendVideo sends a video.+func (s *MessagesService) SendVideo(ctx context.Context, sessionID string, body SendMediaRequest) (*MessageResponse, error) {+ return s.send(ctx, sessionID, "send-video", body)+}++// SendAudio sends audio (set PTT for a voice note).+func (s *MessagesService) SendAudio(ctx context.Context, sessionID string, body SendAudioRequest) (*MessageResponse, error) {+ return s.send(ctx, sessionID, "send-audio", body)+}++// SendDocument sends a document.+func (s *MessagesService) SendDocument(ctx context.Context, sessionID string, body SendMediaRequest) (*MessageResponse, error) {+ return s.send(ctx, sessionID, "send-document", body)+}++// SendSticker sends a sticker.+func (s *MessagesService) SendSticker(ctx context.Context, sessionID string, body SendMediaRequest) (*MessageResponse, error) {+ return s.send(ctx, sessionID, "send-sticker", body)+}++// SendLocation sends a location pin.+func (s *MessagesService) SendLocation(ctx context.Context, sessionID string, body SendLocationRequest) (*MessageResponse, error) {+ return s.send(ctx, sessionID, "send-location", body)+}++// SendContact sends a contact card.+func (s *MessagesService) SendContact(ctx context.Context, sessionID string, body SendContactRequest) (*MessageResponse, error) {+ return s.send(ctx, sessionID, "send-contact", body)+}++// SendTemplate sends a stored template.+func (s *MessagesService) SendTemplate(ctx context.Context, sessionID string, body SendTemplateRequest) (*MessageResponse, error) {+ return s.send(ctx, sessionID, "send-template", body)+}++func (s *MessagesService) send(ctx context.Context, sessionID, segment string, body any) (*MessageResponse, error) {+ var out MessageResponse+ err := s.client.do(ctx, "POST", s.base(sessionID)+"/"+segment, nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Reply replies to a quoted message.+func (s *MessagesService) Reply(ctx context.Context, sessionID string, body ReplyMessageRequest) (*MessageResponse, error) {+ return s.send(ctx, sessionID, "reply", body)+}++// Forward forwards a message between chats.+func (s *MessagesService) Forward(ctx context.Context, sessionID string, body ForwardMessageRequest) (*MessageResponse, error) {+ return s.send(ctx, sessionID, "forward", body)+}++// React adds (or, with an empty emoji, removes) a reaction.+func (s *MessagesService) React(ctx context.Context, sessionID string, body ReactMessageRequest) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "POST", s.base(sessionID)+"/react", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Delete deletes a message.+func (s *MessagesService) Delete(ctx context.Context, sessionID string, body DeleteMessageRequest) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "POST", s.base(sessionID)+"/delete", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// History reads live chat history from WhatsApp.+func (s *MessagesService) History(ctx context.Context, sessionID, chatID string, query *MessageHistoryQuery) ([]ChatHistoryMessage, error) {+ var out []ChatHistoryMessage+ path := s.base(sessionID) + "/" + pathEscape(chatID) + "/history"+ err := s.client.do(ctx, "GET", path, valuesOf(query), nil, &out)+ return out, err+}++// Reactions returns the reactions on a message.+func (s *MessagesService) Reactions(ctx context.Context, sessionID, chatID, messageID string) ([]ReactionRecord, error) {+ var out []ReactionRecord+ path := s.base(sessionID) + "/" + pathEscape(chatID) + "/" + pathEscape(messageID) + "/reactions"+ err := s.client.do(ctx, "GET", path, nil, nil, &out)+ return out, err+}++// SendBulk queues a batch of messages.+func (s *MessagesService) SendBulk(ctx context.Context, sessionID string, body SendBulkRequest) (*BulkMessageResponse, error) {+ var out BulkMessageResponse+ err := s.client.do(ctx, "POST", s.base(sessionID)+"/send-bulk", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// BatchStatus returns the status of a bulk batch.+func (s *MessagesService) BatchStatus(ctx context.Context, sessionID, batchID string) (*BatchStatusResponse, error) {+ var out BatchStatusResponse+ path := s.base(sessionID) + "/batch/" + pathEscape(batchID)+ err := s.client.do(ctx, "GET", path, nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// CancelBatch cancels a running batch. Requires an OPERATOR-level key.+func (s *MessagesService) CancelBatch(ctx context.Context, sessionID, batchID string) (*BatchStatusResponse, error) {+ var out BatchStatusResponse+ path := s.base(sessionID) + "/batch/" + pathEscape(batchID) + "/cancel"+ err := s.client.do(ctx, "POST", path, nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/sdk/go/options.go b/sdk/go/options.gonew file mode 100644index 000000000..da4383600--- /dev/null+++ b/sdk/go/options.go@@ -0,0 +1,104 @@+package openwa++import (+ "net/http"+ "time"+)++// DefaultTimeout is the per-request timeout applied when none is configured.+const DefaultTimeout = 30 * time.Second++// DefaultUserAgent is sent on every request unless overridden with+// WithUserAgent or a caller-supplied User-Agent header.+const DefaultUserAgent = "openwa-go/0.1.0"++// config is the resolved, internal configuration assembled from the options.+type config struct {+ baseURL string+ apiKey string+ timeout time.Duration+ httpClient *http.Client+ baseTransport http.RoundTripper+ logger Logger+ retry *RetryPolicy+ middlewares []Middleware+ userAgent string+ headers http.Header+ allowInsecure bool+}++// Option configures the client. Options are the single, uniform way to inject+// dependencies (HTTP client, transport, logger, retry, middleware) and tune+// behavior — no globals, no singletons.+type Option func(*config)++// WithTimeout sets the per-request timeout. Zero uses DefaultTimeout. The+// timeout also bounds retries, since it is enforced via the request context.+func WithTimeout(d time.Duration) Option {+ return func(c *config) { c.timeout = d }+}++// WithHTTPClient injects a fully-configured *http.Client (connection pool,+// timeout, cookie jar). The SDK wraps its Transport with the middleware+// pipeline and forces a non-following redirect policy for safety; it never+// mutates the client you pass. If both WithHTTPClient and WithTransport are+// given, WithTransport wins as the base transport.+func WithHTTPClient(hc *http.Client) Option {+ return func(c *config) { c.httpClient = hc }+}++// WithTransport injects the base http.RoundTripper the pipeline is built on top+// of. Use this to plug in a custom transport (proxy, TLS config, a recording+// transport in tests) without supplying a whole *http.Client.+func WithTransport(rt http.RoundTripper) Option {+ return func(c *config) { c.baseTransport = rt }+}++// WithLogger injects a Logger. The default is a no-op, so the SDK stays silent+// unless you opt in.+func WithLogger(l Logger) Option {+ return func(c *config) {+ if l != nil {+ c.logger = l+ }+ }+}++// WithRetry enables automatic retries with the given policy. Retries are off by+// default. Use openwa.DefaultRetryPolicy() for sensible defaults:+//+// openwa.WithRetry(openwa.DefaultRetryPolicy())+func WithRetry(p RetryPolicy) Option {+ return func(c *config) { c.retry = &p }+}++// WithMiddleware appends one or more middlewares to the transport pipeline. The+// first argument is the outermost layer. Use it for tracing, metrics, or custom+// auth without touching the SDK internals.+func WithMiddleware(mw ...Middleware) Option {+ return func(c *config) { c.middlewares = append(c.middlewares, mw...) }+}++// WithUserAgent overrides the User-Agent header sent on every request.+func WithUserAgent(ua string) Option {+ return func(c *config) { c.userAgent = ua }+}++// WithHeader adds a default header sent on every request. Auth and content+// headers set by the SDK always take precedence and cannot be overridden.+// Repeated calls accumulate.+func WithHeader(key, value string) Option {+ return func(c *config) {+ if c.headers == nil {+ c.headers = http.Header{}+ }+ c.headers.Add(key, value)+ }+}++// WithInsecureHTTP suppresses the warning logged when base URL uses plaintext+// http:// against a non-localhost host. The API key is bearer-equivalent — only+// use this when TLS is terminated by a trusted proxy in front of the API.+func WithInsecureHTTP() Option {+ return func(c *config) { c.allowInsecure = true }+}diff --git a/sdk/go/retry.go b/sdk/go/retry.gonew file mode 100644index 000000000..106ccd2d6--- /dev/null+++ b/sdk/go/retry.go@@ -0,0 +1,184 @@+package openwa++import (+ "context"+ "errors"+ "io"+ "net/http"+ "strconv"+ "time"+)++// idempotentMethods is the set of HTTP methods that are safe to retry after a+// network error — the request has RFC-defined idempotent semantics, so+// re-issuing it will not cause a duplicate side effect.+var idempotentMethods = map[string]bool{+ http.MethodGet: true,+ http.MethodHead: true,+ http.MethodOptions: true,+ http.MethodPut: true,+ http.MethodDelete: true,+}++// isIdempotent reports whether it is safe to retry a request that failed with a+// network error (as opposed to a retryable HTTP status the server explicitly+// sent). POST is treated as non-idempotent because we cannot tell whether the+// server processed the request before the connection dropped — replaying it+// could double-send a WhatsApp message.+func isIdempotent(method string) bool { return idempotentMethods[method] }++// 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.+//+// Because every request the SDK issues sets req.GetBody, request bodies are+// safely rewound on each attempt.+type RetryPolicy struct {+ // MaxRetries is the number of retries AFTER the first attempt. 3 means up+ // to 4 total attempts.+ MaxRetries int+ // BaseDelay is the delay before the first retry. Each subsequent retry+ // doubles it (exponential backoff), capped at MaxDelay.+ BaseDelay time.Duration+ // MaxDelay caps the per-retry backoff delay.+ MaxDelay time.Duration+ // RetryableStatuses is the set of HTTP statuses that trigger a retry.+ // Defaults (via DefaultRetryPolicy) to 429, 500, 502, 503, 504.+ RetryableStatuses []int+ // RespectRetryAfter honors a Retry-After header on a 429/503 response,+ // using it as the delay when it is longer than the computed backoff.+ RespectRetryAfter bool+}++// DefaultRetryPolicy returns a sensible retry policy: 3 retries, 200ms base+// delay with exponential backoff capped at 5s, retrying 429/500/502/503/504 and+// honoring Retry-After.+func DefaultRetryPolicy() RetryPolicy {+ return RetryPolicy{+ MaxRetries: 3,+ BaseDelay: 200 * time.Millisecond,+ MaxDelay: 5 * time.Second,+ RetryableStatuses: []int{429, 500, 502, 503, 504},+ RespectRetryAfter: true,+ }+}++func (p RetryPolicy) retryableStatus(status int) bool {+ statuses := p.RetryableStatuses+ if statuses == nil {+ statuses = []int{429, 500, 502, 503, 504}+ }+ for _, s := range statuses {+ if s == status {+ return true+ }+ }+ return false+}++// backoff returns the delay before the retry that follows attempt (0-indexed):+// BaseDelay * 2^attempt, capped at MaxDelay.+func (p RetryPolicy) backoff(attempt int) time.Duration {+ base := p.BaseDelay+ if base <= 0 {+ base = 200 * time.Millisecond+ }+ d := base+ for i := 0; i < attempt; i++ {+ d *= 2+ if p.MaxDelay > 0 && d >= p.MaxDelay {+ return p.MaxDelay+ }+ }+ if p.MaxDelay > 0 && d > p.MaxDelay {+ return p.MaxDelay+ }+ return d+}++func parseRetryAfter(resp *http.Response) (time.Duration, bool) {+ if resp == nil {+ return 0, false+ }+ v := resp.Header.Get("Retry-After")+ if v == "" {+ return 0, false+ }+ if secs, err := strconv.Atoi(v); err == nil {+ return time.Duration(secs) * time.Second, true+ }+ if t, err := http.ParseTime(v); err == nil {+ if d := time.Until(t); d > 0 {+ return d, true+ }+ }+ return 0, false+}++// retryMiddleware retries network errors and retryable statuses per policy,+// rewinding the body via req.GetBody and respecting context cancellation.+func retryMiddleware(p RetryPolicy, log Logger) Middleware {+ return func(next http.RoundTripper) http.RoundTripper {+ return RoundTripperFunc(func(req *http.Request) (*http.Response, error) {+ for attempt := 0; ; attempt++ {+ r := req.Clone(req.Context())+ if req.GetBody != nil {+ body, err := req.GetBody()+ if err != nil {+ return nil, err+ }+ r.Body = body+ }++ resp, err := next.RoundTrip(r)++ retryable := false+ switch {+ case err != nil:+ // Never retry a context cancellation/deadline — the+ // caller has already stopped waiting.+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {+ return resp, err+ }+ // Network error: only retry idempotent methods, since we+ // can't tell whether the server processed the request+ // before the connection dropped.+ 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+ }+ if !retryable || attempt >= p.MaxRetries {+ return resp, err+ }++ // Drain and close the response body so the connection can be+ // reused before the next attempt.+ delay := p.backoff(attempt)+ if resp != nil {+ if p.RespectRetryAfter {+ if ra, ok := parseRetryAfter(resp); ok && ra > delay {+ delay = ra+ }+ }+ _, _ = io.Copy(io.Discard, resp.Body)+ _ = resp.Body.Close()+ }++ log.Log(req.Context(), LevelWarn, "openwa retrying request",+ "method", req.Method, "url", req.URL.String(),+ "attempt", attempt+1, "delay_ms", delay.Milliseconds())++ timer := time.NewTimer(delay)+ select {+ case <-timer.C:+ case <-req.Context().Done():+ timer.Stop()+ return nil, req.Context().Err()+ }+ }+ })+ }+}diff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.gonew file mode 100644index 000000000..a5f857c46--- /dev/null+++ b/sdk/go/routing_test.go@@ -0,0 +1,143 @@+package openwa++import (+ "context"+ "testing"+)++// TestRouting exercises every service method and asserts the exact HTTP method+// and path it produces. This is the drift gate: a wrong path (like the+// historical /messages/text vs /messages/send-text) fails here immediately.+func TestRouting(t *testing.T) {+ ctx := context.Background()++ cases := []struct {+ name string+ call func(c *Client)+ wantMethod string+ wantPath string+ }{+ {"Sessions.List", func(c *Client) { c.Sessions.List(ctx, nil) }, "GET", "/api/sessions"},+ {"Sessions.Get", func(c *Client) { c.Sessions.Get(ctx, "s1") }, "GET", "/api/sessions/s1"},+ {"Sessions.Create", func(c *Client) { c.Sessions.Create(ctx, CreateSessionRequest{}) }, "POST", "/api/sessions"},+ {"Sessions.Delete", func(c *Client) { c.Sessions.Delete(ctx, "s1") }, "DELETE", "/api/sessions/s1"},+ {"Sessions.Start", func(c *Client) { c.Sessions.Start(ctx, "s1") }, "POST", "/api/sessions/s1/start"},+ {"Sessions.Stop", func(c *Client) { c.Sessions.Stop(ctx, "s1") }, "POST", "/api/sessions/s1/stop"},+ {"Sessions.ForceKill", func(c *Client) { c.Sessions.ForceKill(ctx, "s1") }, "POST", "/api/sessions/s1/force-kill"},+ {"Sessions.QRCode", func(c *Client) { c.Sessions.QRCode(ctx, "s1") }, "GET", "/api/sessions/s1/qr"},+ {"Sessions.RequestPairingCode", func(c *Client) { c.Sessions.RequestPairingCode(ctx, "s1", RequestPairingCodeRequest{}) }, "POST", "/api/sessions/s1/pairing-code"},+ {"Sessions.Stats", func(c *Client) { c.Sessions.Stats(ctx) }, "GET", "/api/sessions/stats/overview"},++ {"Messages.List", func(c *Client) { c.Messages.List(ctx, "s1", nil) }, "GET", "/api/sessions/s1/messages"},+ {"Messages.SendText", func(c *Client) { c.Messages.SendText(ctx, "s1", SendTextRequest{}) }, "POST", "/api/sessions/s1/messages/send-text"},+ {"Messages.SendImage", func(c *Client) { c.Messages.SendImage(ctx, "s1", SendMediaRequest{}) }, "POST", "/api/sessions/s1/messages/send-image"},+ {"Messages.SendVideo", func(c *Client) { c.Messages.SendVideo(ctx, "s1", SendMediaRequest{}) }, "POST", "/api/sessions/s1/messages/send-video"},+ {"Messages.SendAudio", func(c *Client) { c.Messages.SendAudio(ctx, "s1", SendAudioRequest{}) }, "POST", "/api/sessions/s1/messages/send-audio"},+ {"Messages.SendDocument", func(c *Client) { c.Messages.SendDocument(ctx, "s1", SendMediaRequest{}) }, "POST", "/api/sessions/s1/messages/send-document"},+ {"Messages.SendSticker", func(c *Client) { c.Messages.SendSticker(ctx, "s1", SendMediaRequest{}) }, "POST", "/api/sessions/s1/messages/send-sticker"},+ {"Messages.SendLocation", func(c *Client) { c.Messages.SendLocation(ctx, "s1", SendLocationRequest{}) }, "POST", "/api/sessions/s1/messages/send-location"},+ {"Messages.SendContact", func(c *Client) { c.Messages.SendContact(ctx, "s1", SendContactRequest{}) }, "POST", "/api/sessions/s1/messages/send-contact"},+ {"Messages.SendTemplate", func(c *Client) { c.Messages.SendTemplate(ctx, "s1", SendTemplateRequest{}) }, "POST", "/api/sessions/s1/messages/send-template"},+ {"Messages.Reply", func(c *Client) { c.Messages.Reply(ctx, "s1", ReplyMessageRequest{}) }, "POST", "/api/sessions/s1/messages/reply"},+ {"Messages.Forward", func(c *Client) { c.Messages.Forward(ctx, "s1", ForwardMessageRequest{}) }, "POST", "/api/sessions/s1/messages/forward"},+ {"Messages.React", func(c *Client) { c.Messages.React(ctx, "s1", ReactMessageRequest{}) }, "POST", "/api/sessions/s1/messages/react"},+ {"Messages.Delete", func(c *Client) { c.Messages.Delete(ctx, "s1", DeleteMessageRequest{}) }, "POST", "/api/sessions/s1/messages/delete"},+ {"Messages.History", func(c *Client) { c.Messages.History(ctx, "s1", "c1", nil) }, "GET", "/api/sessions/s1/messages/c1/history"},+ {"Messages.Reactions", func(c *Client) { c.Messages.Reactions(ctx, "s1", "c1", "m1") }, "GET", "/api/sessions/s1/messages/c1/m1/reactions"},+ {"Messages.SendBulk", func(c *Client) { c.Messages.SendBulk(ctx, "s1", SendBulkRequest{}) }, "POST", "/api/sessions/s1/messages/send-bulk"},+ {"Messages.BatchStatus", func(c *Client) { c.Messages.BatchStatus(ctx, "s1", "b1") }, "GET", "/api/sessions/s1/messages/batch/b1"},+ {"Messages.CancelBatch", func(c *Client) { c.Messages.CancelBatch(ctx, "s1", "b1") }, "POST", "/api/sessions/s1/messages/batch/b1/cancel"},++ {"Contacts.List", func(c *Client) { c.Contacts.List(ctx, "s1", nil) }, "GET", "/api/sessions/s1/contacts"},+ {"Contacts.Get", func(c *Client) { c.Contacts.Get(ctx, "s1", "u1") }, "GET", "/api/sessions/s1/contacts/u1"},+ {"Contacts.Check", func(c *Client) { c.Contacts.Check(ctx, "s1", "628") }, "GET", "/api/sessions/s1/contacts/check/628"},+ {"Contacts.ProfilePicture", func(c *Client) { c.Contacts.ProfilePicture(ctx, "s1", "u1") }, "GET", "/api/sessions/s1/contacts/u1/profile-picture"},+ {"Contacts.Phone", func(c *Client) { c.Contacts.Phone(ctx, "s1", "u1") }, "GET", "/api/sessions/s1/contacts/u1/phone"},+ {"Contacts.Block", func(c *Client) { c.Contacts.Block(ctx, "s1", "u1") }, "POST", "/api/sessions/s1/contacts/u1/block"},+ {"Contacts.Unblock", func(c *Client) { c.Contacts.Unblock(ctx, "s1", "u1") }, "DELETE", "/api/sessions/s1/contacts/u1/block"},++ {"Groups.List", func(c *Client) { c.Groups.List(ctx, "s1", nil) }, "GET", "/api/sessions/s1/groups"},+ {"Groups.Get", func(c *Client) { c.Groups.Get(ctx, "s1", "g1") }, "GET", "/api/sessions/s1/groups/g1"},+ {"Groups.Create", func(c *Client) { c.Groups.Create(ctx, "s1", CreateGroupRequest{}) }, "POST", "/api/sessions/s1/groups"},+ {"Groups.AddParticipants", func(c *Client) { c.Groups.AddParticipants(ctx, "s1", "g1", nil) }, "POST", "/api/sessions/s1/groups/g1/participants"},+ {"Groups.RemoveParticipants", func(c *Client) { c.Groups.RemoveParticipants(ctx, "s1", "g1", nil) }, "DELETE", "/api/sessions/s1/groups/g1/participants"},+ {"Groups.PromoteParticipants", func(c *Client) { c.Groups.PromoteParticipants(ctx, "s1", "g1", nil) }, "POST", "/api/sessions/s1/groups/g1/participants/promote"},+ {"Groups.DemoteParticipants", func(c *Client) { c.Groups.DemoteParticipants(ctx, "s1", "g1", nil) }, "POST", "/api/sessions/s1/groups/g1/participants/demote"},+ {"Groups.SetSubject", func(c *Client) { c.Groups.SetSubject(ctx, "s1", "g1", "x") }, "PUT", "/api/sessions/s1/groups/g1/subject"},+ {"Groups.SetDescription", func(c *Client) { c.Groups.SetDescription(ctx, "s1", "g1", "x") }, "PUT", "/api/sessions/s1/groups/g1/description"},+ {"Groups.Leave", func(c *Client) { c.Groups.Leave(ctx, "s1", "g1") }, "POST", "/api/sessions/s1/groups/g1/leave"},+ {"Groups.InviteCode", func(c *Client) { c.Groups.InviteCode(ctx, "s1", "g1") }, "GET", "/api/sessions/s1/groups/g1/invite-code"},+ {"Groups.RevokeInviteCode", func(c *Client) { c.Groups.RevokeInviteCode(ctx, "s1", "g1") }, "POST", "/api/sessions/s1/groups/g1/invite-code/revoke"},++ {"Webhooks.List", func(c *Client) { c.Webhooks.List(ctx, "s1") }, "GET", "/api/sessions/s1/webhooks"},+ {"Webhooks.Get", func(c *Client) { c.Webhooks.Get(ctx, "s1", "w1") }, "GET", "/api/sessions/s1/webhooks/w1"},+ {"Webhooks.Create", func(c *Client) { c.Webhooks.Create(ctx, "s1", CreateWebhookRequest{}) }, "POST", "/api/sessions/s1/webhooks"},+ {"Webhooks.Update", func(c *Client) { c.Webhooks.Update(ctx, "s1", "w1", UpdateWebhookRequest{}) }, "PUT", "/api/sessions/s1/webhooks/w1"},+ {"Webhooks.Delete", func(c *Client) { c.Webhooks.Delete(ctx, "s1", "w1") }, "DELETE", "/api/sessions/s1/webhooks/w1"},+ {"Webhooks.Test", func(c *Client) { c.Webhooks.Test(ctx, "s1", "w1") }, "POST", "/api/sessions/s1/webhooks/w1/test"},++ {"Chats.List", func(c *Client) { c.Chats.List(ctx, "s1", nil) }, "GET", "/api/sessions/s1/chats"},+ {"Chats.MarkRead", func(c *Client) { c.Chats.MarkRead(ctx, "s1", MarkChatRequest{}) }, "POST", "/api/sessions/s1/chats/read"},+ {"Chats.MarkUnread", func(c *Client) { c.Chats.MarkUnread(ctx, "s1", MarkChatRequest{}) }, "POST", "/api/sessions/s1/chats/unread"},+ {"Chats.Delete", func(c *Client) { c.Chats.Delete(ctx, "s1", DeleteChatRequest{}) }, "POST", "/api/sessions/s1/chats/delete"},+ {"Chats.SendState", func(c *Client) { c.Chats.SendState(ctx, "s1", SendChatStateRequest{}) }, "POST", "/api/sessions/s1/chats/typing"},++ {"Status.List", func(c *Client) { c.Status.List(ctx, "s1") }, "GET", "/api/sessions/s1/status"},+ {"Status.FromContact", func(c *Client) { c.Status.FromContact(ctx, "s1", "u1") }, "GET", "/api/sessions/s1/status/u1"},+ {"Status.SendText", func(c *Client) { c.Status.SendText(ctx, "s1", SendTextStatusRequest{}) }, "POST", "/api/sessions/s1/status/send-text"},+ {"Status.SendImage", func(c *Client) { c.Status.SendImage(ctx, "s1", SendImageStatusRequest{}) }, "POST", "/api/sessions/s1/status/send-image"},+ {"Status.SendVideo", func(c *Client) { c.Status.SendVideo(ctx, "s1", SendVideoStatusRequest{}) }, "POST", "/api/sessions/s1/status/send-video"},+ {"Status.Delete", func(c *Client) { c.Status.Delete(ctx, "s1", "st1") }, "DELETE", "/api/sessions/s1/status/st1"},++ {"Labels.List", func(c *Client) { c.Labels.List(ctx, "s1") }, "GET", "/api/sessions/s1/labels"},+ {"Labels.Get", func(c *Client) { c.Labels.Get(ctx, "s1", "l1") }, "GET", "/api/sessions/s1/labels/l1"},+ {"Labels.ForChat", func(c *Client) { c.Labels.ForChat(ctx, "s1", "c1") }, "GET", "/api/sessions/s1/labels/chat/c1"},+ {"Labels.AddToChat", func(c *Client) { c.Labels.AddToChat(ctx, "s1", "c1", AddLabelRequest{}) }, "POST", "/api/sessions/s1/labels/chat/c1"},+ {"Labels.RemoveFromChat", func(c *Client) { c.Labels.RemoveFromChat(ctx, "s1", "c1", "l1") }, "DELETE", "/api/sessions/s1/labels/chat/c1/l1"},++ {"Channels.List", func(c *Client) { c.Channels.List(ctx, "s1") }, "GET", "/api/sessions/s1/channels"},+ {"Channels.Get", func(c *Client) { c.Channels.Get(ctx, "s1", "ch1") }, "GET", "/api/sessions/s1/channels/ch1"},+ {"Channels.Messages", func(c *Client) { c.Channels.Messages(ctx, "s1", "ch1", nil) }, "GET", "/api/sessions/s1/channels/ch1/messages"},+ {"Channels.Subscribe", func(c *Client) { c.Channels.Subscribe(ctx, "s1", SubscribeChannelRequest{}) }, "POST", "/api/sessions/s1/channels/subscribe"},+ {"Channels.Unsubscribe", func(c *Client) { c.Channels.Unsubscribe(ctx, "s1", "ch1") }, "DELETE", "/api/sessions/s1/channels/ch1"},++ {"Catalog.Info", func(c *Client) { c.Catalog.Info(ctx, "s1") }, "GET", "/api/sessions/s1/catalog"},+ {"Catalog.Products", func(c *Client) { c.Catalog.Products(ctx, "s1", nil) }, "GET", "/api/sessions/s1/catalog/products"},+ {"Catalog.Product", func(c *Client) { c.Catalog.Product(ctx, "s1", "p1") }, "GET", "/api/sessions/s1/catalog/products/p1"},+ {"Catalog.SendProduct", func(c *Client) { c.Catalog.SendProduct(ctx, "s1", SendProductRequest{}) }, "POST", "/api/sessions/s1/messages/send-product"},+ {"Catalog.SendCatalog", func(c *Client) { c.Catalog.SendCatalog(ctx, "s1", SendCatalogRequest{}) }, "POST", "/api/sessions/s1/messages/send-catalog"},++ {"Templates.List", func(c *Client) { c.Templates.List(ctx, "s1") }, "GET", "/api/sessions/s1/templates"},+ {"Templates.Get", func(c *Client) { c.Templates.Get(ctx, "s1", "t1") }, "GET", "/api/sessions/s1/templates/t1"},+ {"Templates.Create", func(c *Client) { c.Templates.Create(ctx, "s1", CreateTemplateRequest{}) }, "POST", "/api/sessions/s1/templates"},+ {"Templates.Update", func(c *Client) { c.Templates.Update(ctx, "s1", "t1", UpdateTemplateRequest{}) }, "PUT", "/api/sessions/s1/templates/t1"},+ {"Templates.Delete", func(c *Client) { c.Templates.Delete(ctx, "s1", "t1") }, "DELETE", "/api/sessions/s1/templates/t1"},++ {"Health.Check", func(c *Client) { c.Health.Check(ctx) }, "GET", "/api/health"},+ {"Health.Live", func(c *Client) { c.Health.Live(ctx) }, "GET", "/api/health/live"},+ {"Health.Ready", func(c *Client) { c.Health.Ready(ctx) }, "GET", "/api/health/ready"},++ {"Search.Search", func(c *Client) { c.Search.Search(ctx, SearchQuery{Q: "hi"}) }, "GET", "/api/search"},+ {"Auth.Validate", func(c *Client) { c.Auth.Validate(ctx) }, "POST", "/api/auth/validate"},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{}`}+ c := newTestClient(t, rt)+ tc.call(c)+ if rt.lastReq == nil {+ t.Fatalf("no request issued")+ }+ if rt.lastReq.Method != tc.wantMethod {+ t.Errorf("method = %q, want %q", rt.lastReq.Method, tc.wantMethod)+ }+ if got := rt.lastReq.URL.EscapedPath(); got != tc.wantPath {+ t.Errorf("path = %q, want %q", got, tc.wantPath)+ }+ if h := rt.lastReq.Header.Get("X-API-Key"); h == "" {+ t.Error("missing X-API-Key header")+ }+ })+ }+}diff --git a/sdk/go/search.go b/sdk/go/search.gonew file mode 100644index 000000000..5b6ee9345--- /dev/null+++ b/sdk/go/search.go@@ -0,0 +1,18 @@+package openwa++import "context"++// SearchService runs full-text message search across sessions. If no search+// provider is configured the server returns 501 (ErrNotImplemented).+// Backed by src/modules/search/search.controller.ts.+type SearchService struct{ client *Client }++// Search searches messages across sessions. Query.Q is required.+func (s *SearchService) Search(ctx context.Context, query SearchQuery) (*SearchResults, error) {+ var out SearchResults+ err := s.client.do(ctx, "GET", "/api/search", query.values(), nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/sdk/go/sessions.go b/sdk/go/sessions.gonew file mode 100644index 000000000..47add084c--- /dev/null+++ b/sdk/go/sessions.go@@ -0,0 +1,99 @@+package openwa++import "context"++// SessionsService manages the lifecycle of WhatsApp sessions.+// Backed by src/modules/session/session.controller.ts.+type SessionsService struct{ client *Client }++// List returns sessions. Pass nil for the default (server-side) limit/offset.+func (s *SessionsService) List(ctx context.Context, query *ListSessionsQuery) ([]SessionResponse, error) {+ var out []SessionResponse+ err := s.client.do(ctx, "GET", "/api/sessions", valuesOf(query), nil, &out)+ return out, err+}++// Get returns a single session.+func (s *SessionsService) Get(ctx context.Context, sessionID string) (*SessionResponse, error) {+ var out SessionResponse+ err := s.client.do(ctx, "GET", "/api/sessions/"+pathEscape(sessionID), nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Create provisions a new session.+func (s *SessionsService) Create(ctx context.Context, body CreateSessionRequest) (*SessionResponse, error) {+ var out SessionResponse+ err := s.client.do(ctx, "POST", "/api/sessions", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Delete removes a session.+func (s *SessionsService) Delete(ctx context.Context, sessionID string) error {+ return s.client.do(ctx, "DELETE", "/api/sessions/"+pathEscape(sessionID), nil, nil, nil)+}++// Start connects a session (triggers QR / pairing).+func (s *SessionsService) Start(ctx context.Context, sessionID string) (*SessionResponse, error) {+ var out SessionResponse+ err := s.client.do(ctx, "POST", "/api/sessions/"+pathEscape(sessionID)+"/start", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Stop disconnects a session gracefully.+func (s *SessionsService) Stop(ctx context.Context, sessionID string) (*SessionResponse, error) {+ var out SessionResponse+ err := s.client.do(ctx, "POST", "/api/sessions/"+pathEscape(sessionID)+"/stop", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// ForceKill terminates a stuck session immediately.+func (s *SessionsService) ForceKill(ctx context.Context, sessionID string) (*SessionResponse, error) {+ var out SessionResponse+ err := s.client.do(ctx, "POST", "/api/sessions/"+pathEscape(sessionID)+"/force-kill", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// QRCode returns the current QR code for a session awaiting scan.+func (s *SessionsService) QRCode(ctx context.Context, sessionID string) (*QrCodeResponse, error) {+ var out QrCodeResponse+ err := s.client.do(ctx, "GET", "/api/sessions/"+pathEscape(sessionID)+"/qr", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// RequestPairingCode requests a phone-pairing code.+func (s *SessionsService) RequestPairingCode(ctx context.Context, sessionID string, body RequestPairingCodeRequest) (*PairingCodeResponse, error) {+ var out PairingCodeResponse+ err := s.client.do(ctx, "POST", "/api/sessions/"+pathEscape(sessionID)+"/pairing-code", nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Stats returns the aggregate session stats overview.+func (s *SessionsService) Stats(ctx context.Context) (*SessionStatsOverview, error) {+ var out SessionStatsOverview+ err := s.client.do(ctx, "GET", "/api/sessions/stats/overview", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}diff --git a/sdk/go/status.go b/sdk/go/status.gonew file mode 100644index 000000000..66d174d23--- /dev/null+++ b/sdk/go/status.go@@ -0,0 +1,57 @@+package openwa++import "context"++// StatusService posts and reads WhatsApp Status (Stories). This is distinct from+// session lifecycle status. Backed by src/modules/status/status.controller.ts.+type StatusService struct{ client *Client }++func (s *StatusService) base(sessionID string) string {+ return "/api/sessions/" + pathEscape(sessionID) + "/status"+}++// List returns all status/stories visible to the session. The server returns+// {"statuses":[...]} — the envelope is unwrapped and only the slice is+// returned.+func (s *StatusService) List(ctx context.Context, sessionID string) ([]StatusRecord, error) {+ var out StatusListResponse+ err := s.client.do(ctx, "GET", s.base(sessionID), nil, nil, &out)+ return out.Statuses, err+}++// FromContact returns the status/stories from a specific contact. Same+// {"statuses":[...]} envelope as List.+func (s *StatusService) FromContact(ctx context.Context, sessionID, contactID string) ([]StatusRecord, error) {+ var out StatusListResponse+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(contactID), nil, nil, &out)+ return out.Statuses, err+}++// SendText posts a text status.+func (s *StatusService) SendText(ctx context.Context, sessionID string, body SendTextStatusRequest) (*StatusResult, error) {+ return s.send(ctx, sessionID, "/send-text", body)+}++// SendImage posts an image status.+func (s *StatusService) SendImage(ctx context.Context, sessionID string, body SendImageStatusRequest) (*StatusResult, error) {+ return s.send(ctx, sessionID, "/send-image", body)+}++// SendVideo posts a video status.+func (s *StatusService) SendVideo(ctx context.Context, sessionID string, body SendVideoStatusRequest) (*StatusResult, error) {+ return s.send(ctx, sessionID, "/send-video", body)+}++func (s *StatusService) send(ctx context.Context, sessionID, suffix string, body any) (*StatusResult, error) {+ var out StatusResult+ err := s.client.do(ctx, "POST", s.base(sessionID)+suffix, nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Delete removes a status post.+func (s *StatusService) Delete(ctx context.Context, sessionID, statusID string) error {+ return s.client.do(ctx, "DELETE", s.base(sessionID)+"/"+pathEscape(statusID), nil, nil, nil)+}diff --git a/sdk/go/templates.go b/sdk/go/templates.gonew file mode 100644index 000000000..0eb08bf82--- /dev/null+++ b/sdk/go/templates.go@@ -0,0 +1,53 @@+package openwa++import "context"++// TemplatesService manages stored message templates with {{variable}}+// placeholders. Backed by src/modules/template/template.controller.ts.+type TemplatesService struct{ client *Client }++func (s *TemplatesService) base(sessionID string) string {+ return "/api/sessions/" + pathEscape(sessionID) + "/templates"+}++// List returns templates for a session.+func (s *TemplatesService) List(ctx context.Context, sessionID string) ([]TemplateRecord, error) {+ var out []TemplateRecord+ err := s.client.do(ctx, "GET", s.base(sessionID), nil, nil, &out)+ return out, err+}++// Get returns a single template.+func (s *TemplatesService) Get(ctx context.Context, sessionID, templateID string) (*TemplateRecord, error) {+ var out TemplateRecord+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(templateID), nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Create creates a template.+func (s *TemplatesService) Create(ctx context.Context, sessionID string, body CreateTemplateRequest) (*TemplateRecord, error) {+ var out TemplateRecord+ err := s.client.do(ctx, "POST", s.base(sessionID), nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Update modifies a template.+func (s *TemplatesService) Update(ctx context.Context, sessionID, templateID string, body UpdateTemplateRequest) (*TemplateRecord, error) {+ var out TemplateRecord+ err := s.client.do(ctx, "PUT", s.base(sessionID)+"/"+pathEscape(templateID), nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Delete removes a template.+func (s *TemplatesService) Delete(ctx context.Context, sessionID, templateID string) error {+ return s.client.do(ctx, "DELETE", s.base(sessionID)+"/"+pathEscape(templateID), nil, nil, nil)+}diff --git a/sdk/go/transport.go b/sdk/go/transport.gonew file mode 100644index 000000000..3588d7444--- /dev/null+++ b/sdk/go/transport.go@@ -0,0 +1,96 @@+package openwa++import (+ "net/http"+ "time"+)++// RoundTripperFunc adapts a function to an http.RoundTripper, so a middleware+// can be written as a closure instead of a named type.+type RoundTripperFunc func(*http.Request) (*http.Response, error)++// RoundTrip implements http.RoundTripper.+func (f RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {+ return f(req)+}++// Middleware wraps an http.RoundTripper to add behavior (retry, logging,+// metrics, tracing, custom auth). Middlewares compose into a pipeline: the+// first one passed to WithMiddleware is the outermost (runs first on the way+// out, last on the way back). Inject cross-cutting concerns like this instead+// of subclassing the client.+//+// client, _ := openwa.New(baseURL, apiKey,+// openwa.WithMiddleware(tracingMiddleware, metricsMiddleware),+// )+type Middleware func(next http.RoundTripper) http.RoundTripper++// buildTransport composes the request pipeline from the base transport outward:+//+// base -> auth -> logging -> retry -> user middlewares (index 0 outermost)+//+// Auth sits innermost so every attempt — including retries — carries the API+// key. Retry wraps logging+auth so each attempt is logged and re-authenticated.+func buildTransport(cfg *config, base http.RoundTripper) http.RoundTripper {+ rt := base+ rt = authMiddleware(cfg)(rt)+ rt = loggingMiddleware(cfg.logger)(rt)+ if cfg.retry != nil {+ rt = retryMiddleware(*cfg.retry, cfg.logger)(rt)+ }+ for i := len(cfg.middlewares) - 1; i >= 0; i-- {+ rt = cfg.middlewares[i](rt)+ }+ return rt+}++// authMiddleware injects the API key and default headers on every outbound+// request. Caller-supplied default headers are applied first so the auth and+// content headers below always win and can never be clobbered.+func authMiddleware(cfg *config) Middleware {+ return func(next http.RoundTripper) http.RoundTripper {+ return RoundTripperFunc(func(req *http.Request) (*http.Response, error) {+ // Clone so we never mutate the caller's request headers.+ r := req.Clone(req.Context())+ for k, vs := range cfg.headers {+ // Only apply defaults for a header the caller has not already+ // set. The check runs once per key so all default values are+ // added (not just the first, which the earlier per-value check+ // silently dropped).+ if r.Header.Get(k) != "" {+ continue+ }+ for _, v := range vs {+ r.Header.Add(k, v)+ }+ }+ r.Header.Set("X-API-Key", cfg.apiKey)+ if cfg.userAgent != "" && r.Header.Get("User-Agent") == "" {+ r.Header.Set("User-Agent", cfg.userAgent)+ }+ return next.RoundTrip(r)+ })+ }+}++// loggingMiddleware logs one record per attempt at debug level, and errors at+// error level. It is a no-op in practice when the injected logger is nopLogger.+func loggingMiddleware(log Logger) Middleware {+ return func(next http.RoundTripper) http.RoundTripper {+ return RoundTripperFunc(func(req *http.Request) (*http.Response, error) {+ start := time.Now()+ resp, err := next.RoundTrip(req)+ dur := time.Since(start)+ if err != nil {+ log.Log(req.Context(), LevelError, "openwa request failed",+ "method", req.Method, "url", req.URL.String(),+ "duration_ms", dur.Milliseconds(), "error", err.Error())+ return resp, err+ }+ log.Log(req.Context(), LevelDebug, "openwa request",+ "method", req.Method, "url", req.URL.String(),+ "status", resp.StatusCode, "duration_ms", dur.Milliseconds())+ return resp, nil+ })+ }+}diff --git a/sdk/go/types.go b/sdk/go/types.gonew file mode 100644index 000000000..7b72c9eb5--- /dev/null+++ b/sdk/go/types.go@@ -0,0 +1,22 @@+package openwa++// Wire types for the OpenWA API, split by domain into types_*.go files. Field+// names / JSON tags mirror the backend DTOs exactly (camelCase). Optional+// request fields use `omitempty` (and pointers where the zero value is+// meaningful); nullable response fields use pointers so absent and empty are+// distinguishable.+//+// The types_*.go files are the single source of truth for wire shapes and are+// structured so they can later be regenerated from openapi.json without+// touching the hand-written service methods (paths + DX live elsewhere).++// Ptr returns a pointer to v — handy for optional pointer fields:+//+// openwa.DeleteMessageRequest{ChatID: id, MessageID: mid, ForEveryone: openwa.Ptr(false)}+func Ptr[T any](v T) *T { return &v }++// SuccessResult is the generic {success, message} acknowledgement.+type SuccessResult struct {+ Success bool `json:"success"`+ Message string `json:"message,omitempty"`+}diff --git a/sdk/go/types_catalog.go b/sdk/go/types_catalog.gonew file mode 100644index 000000000..34587b837--- /dev/null+++ b/sdk/go/types_catalog.go@@ -0,0 +1,66 @@+package openwa++import "net/url"++// CatalogInfo describes a business catalog.+type CatalogInfo struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Description *string `json:"description,omitempty"`+ ProductCount int `json:"productCount,omitempty"`+ URL string `json:"url,omitempty"`+}++// CatalogProductsQuery paginates the catalog products list.+type CatalogProductsQuery struct {+ Page *int+ Limit *int+}++func (q *CatalogProductsQuery) values() url.Values {+ v := url.Values{}+ setInt(v, "page", q.Page)+ setInt(v, "limit", q.Limit)+ return v+}++// CatalogProduct is a catalog product.+type CatalogProduct struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Description *string `json:"description,omitempty"`+ Price float64 `json:"price,omitempty"`+ Currency string `json:"currency,omitempty"`+ PriceFormatted string `json:"priceFormatted,omitempty"`+ ImageURL *string `json:"imageUrl,omitempty"`+ URL string `json:"url,omitempty"`+ IsAvailable bool `json:"isAvailable,omitempty"`+ RetailerID string `json:"retailerId,omitempty"`+}++// ProductPagination is the pagination block for catalog products.+type ProductPagination struct {+ Page int `json:"page"`+ Limit int `json:"limit"`+ Total int `json:"total"`+ TotalPages int `json:"totalPages"`+}++// PaginatedProducts is the paginated catalog products payload.+type PaginatedProducts struct {+ Products []CatalogProduct `json:"products"`+ Pagination ProductPagination `json:"pagination"`+}++// SendProductRequest sends a product message.+type SendProductRequest struct {+ ChatID string `json:"chatId"`+ ProductID string `json:"productId"`+ Body string `json:"body,omitempty"`+}++// SendCatalogRequest sends a catalog link message.+type SendCatalogRequest struct {+ ChatID string `json:"chatId"`+ Body string `json:"body,omitempty"`+}diff --git a/sdk/go/types_channel.go b/sdk/go/types_channel.gonew file mode 100644index 000000000..75e9caab1--- /dev/null+++ b/sdk/go/types_channel.go@@ -0,0 +1,29 @@+package openwa++import "net/url"++// ChannelRecord is a WhatsApp Channel / Newsletter.+type ChannelRecord struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Description *string `json:"description,omitempty"`+ SubscriberCount int `json:"subscriberCount,omitempty"`+ PictureURL *string `json:"pictureUrl,omitempty"`+ Role string `json:"role,omitempty"`+}++// ChannelMessageQuery limits the channel message read (default 50).+type ChannelMessageQuery struct {+ Limit *int+}++func (q *ChannelMessageQuery) values() url.Values {+ v := url.Values{}+ setInt(v, "limit", q.Limit)+ return v+}++// SubscribeChannelRequest subscribes to a channel by invite code.+type SubscribeChannelRequest struct {+ InviteCode string `json:"inviteCode"`+}diff --git a/sdk/go/types_chat.go b/sdk/go/types_chat.gonew file mode 100644index 000000000..08a8095c3--- /dev/null+++ b/sdk/go/types_chat.go@@ -0,0 +1,42 @@+package openwa++import "net/url"++// ChatSummary is a chat-list entry.+type ChatSummary struct {+ ID string `json:"id"`+ Name *string `json:"name,omitempty"`+ IsGroup bool `json:"isGroup"`+ UnreadCount int `json:"unreadCount"`+ LastMessage string `json:"lastMessage,omitempty"`+ Timestamp any `json:"timestamp,omitempty"`+}++// MarkChatRequest marks a chat read/unread.+type MarkChatRequest struct {+ ChatID string `json:"chatId"`+}++// SendChatStateRequest sets typing state. State is one of: typing, recording, paused.+type SendChatStateRequest struct {+ ChatID string `json:"chatId"`+ State string `json:"state"`+}++// DeleteChatRequest deletes a chat.+type DeleteChatRequest struct {+ ChatID string `json:"chatId"`+}++// ListChatsQuery paginates the chat list.+type ListChatsQuery struct {+ Limit *int+ Offset *int+}++func (q *ListChatsQuery) values() url.Values {+ v := url.Values{}+ setInt(v, "limit", q.Limit)+ setInt(v, "offset", q.Offset)+ return v+}diff --git a/sdk/go/types_contact.go b/sdk/go/types_contact.gonew file mode 100644index 000000000..86b8cdb1c--- /dev/null+++ b/sdk/go/types_contact.go@@ -0,0 +1,44 @@+package openwa++import "net/url"++// ContactRecord is a contact.+type ContactRecord struct {+ ID string `json:"id"`+ Name *string `json:"name,omitempty"`+ Number *string `json:"number,omitempty"`+ Pushname *string `json:"pushname,omitempty"`+ IsBusiness bool `json:"isBusiness,omitempty"`+ IsMyContact bool `json:"isMyContact,omitempty"`+}++// CheckNumberResponse reports whether a number is on WhatsApp.+type CheckNumberResponse struct {+ Number string `json:"number"`+ Exists bool `json:"exists"`+ WhatsappID *string `json:"whatsappId,omitempty"`+}++// ProfilePictureResponse carries a contact's profile picture URL.+type ProfilePictureResponse struct {+ URL *string `json:"url,omitempty"`+}++// ContactPhoneResponse resolves a contact's phone number.+type ContactPhoneResponse struct {+ ContactID string `json:"contactId"`+ Phone *string `json:"phone,omitempty"`+}++// ListContactsQuery paginates the contact list.+type ListContactsQuery struct {+ Limit *int+ Offset *int+}++func (q *ListContactsQuery) values() url.Values {+ v := url.Values{}+ setInt(v, "limit", q.Limit)+ setInt(v, "offset", q.Offset)+ return v+}diff --git a/sdk/go/types_group.go b/sdk/go/types_group.gonew file mode 100644index 000000000..cbe747451--- /dev/null+++ b/sdk/go/types_group.go@@ -0,0 +1,65 @@+package openwa++import "net/url"++// GroupParticipant is a group member.+type GroupParticipant struct {+ ID string `json:"id"`+ Number string `json:"number,omitempty"`+ Name string `json:"name,omitempty"`+ IsAdmin bool `json:"isAdmin,omitempty"`+ IsSuperAdmin bool `json:"isSuperAdmin,omitempty"`+}++// GroupSummary is the slim group shape from the list endpoint. Note that+// ParticipantsCount and IsAdmin are stripped by the LIST endpoint on the+// current engine and will normally be absent from the payload — use Groups.Get+// (which returns GroupInfo) when you need them. They are pointers so a missing+// field decodes as nil rather than being confused with a zero-valued present+// field.+type GroupSummary struct {+ ID string `json:"id"`+ Name string `json:"name"`+ ParticipantsCount *int `json:"participantsCount,omitempty"`+ IsAdmin *bool `json:"isAdmin,omitempty"`+ LinkedParentJID *string `json:"linkedParentJID,omitempty"`+}++// GroupInfo is the full group detail.+type GroupInfo struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Description *string `json:"description,omitempty"`+ Owner *string `json:"owner,omitempty"`+ CreatedAt int64 `json:"createdAt,omitempty"`+ Participants []GroupParticipant `json:"participants,omitempty"`+ IsReadOnly bool `json:"isReadOnly,omitempty"`+ IsAnnounce bool `json:"isAnnounce,omitempty"`+ LinkedParentJID *string `json:"linkedParentJID,omitempty"`+}++// CreateGroupRequest creates a group with initial participants.+type CreateGroupRequest struct {+ Name string `json:"name"`+ Participants []string `json:"participants"`+}++// InviteCodeResponse carries a group invite code/link.+type InviteCodeResponse struct {+ InviteCode string `json:"inviteCode,omitempty"`+ InviteLink string `json:"inviteLink,omitempty"`+ Message string `json:"message,omitempty"`+}++// ListGroupsQuery paginates the group list.+type ListGroupsQuery struct {+ Limit *int+ Offset *int+}++func (q *ListGroupsQuery) values() url.Values {+ v := url.Values{}+ setInt(v, "limit", q.Limit)+ setInt(v, "offset", q.Offset)+ return v+}diff --git a/sdk/go/types_message.go b/sdk/go/types_message.gonew file mode 100644index 000000000..6260f8133--- /dev/null+++ b/sdk/go/types_message.go@@ -0,0 +1,297 @@+package openwa++import "net/url"++// MessageResponse is the acknowledgement for a sent message.+type MessageResponse struct {+ MessageID string `json:"messageId"`+ Timestamp int64 `json:"timestamp"`+}++// SendTextRequest sends a plain text message.+type SendTextRequest struct {+ ChatID string `json:"chatId"`+ Text string `json:"text"`+}++// SendMediaRequest sends image/video/document/sticker media. Provide exactly+// one of URL or Base64. For audio use SendAudioRequest (PTT lives there).+type SendMediaRequest struct {+ ChatID string `json:"chatId"`+ URL string `json:"url,omitempty"`+ Base64 string `json:"base64,omitempty"`+ Mimetype string `json:"mimetype,omitempty"`+ Filename string `json:"filename,omitempty"`+ Caption string `json:"caption,omitempty"`+}++// SendAudioRequest sends audio. PTT sends as a voice note. Server only accepts+// PTT on /send-audio, so it is kept off the shared media struct to avoid a 400.+type SendAudioRequest struct {+ ChatID string `json:"chatId"`+ URL string `json:"url,omitempty"`+ Base64 string `json:"base64,omitempty"`+ Mimetype string `json:"mimetype,omitempty"`+ Filename string `json:"filename,omitempty"`+ Caption string `json:"caption,omitempty"`+ PTT *bool `json:"ptt,omitempty"`+}++// SendLocationRequest sends a location pin. ChatID/Latitude/Longitude required.+type SendLocationRequest struct {+ ChatID string `json:"chatId"`+ Latitude float64 `json:"latitude"`+ Longitude float64 `json:"longitude"`+ Description string `json:"description,omitempty"`+ Address string `json:"address,omitempty"`+}++// SendContactRequest sends a contact card.+type SendContactRequest struct {+ ChatID string `json:"chatId"`+ ContactName string `json:"contactName"`+ ContactNumber string `json:"contactNumber"`+}++// SendTemplateRequest sends a stored template. Provide exactly one of+// TemplateID or TemplateName.+type SendTemplateRequest struct {+ ChatID string `json:"chatId"`+ TemplateID string `json:"templateId,omitempty"`+ TemplateName string `json:"templateName,omitempty"`+ Vars map[string]string `json:"vars,omitempty"`+}++// ReplyMessageRequest replies to a quoted message.+type ReplyMessageRequest struct {+ ChatID string `json:"chatId"`+ QuotedMessageID string `json:"quotedMessageId"`+ Text string `json:"text"`+}++// ForwardMessageRequest forwards a message between chats.+type ForwardMessageRequest struct {+ FromChatID string `json:"fromChatId"`+ ToChatID string `json:"toChatId"`+ MessageID string `json:"messageId"`+}++// ReactMessageRequest adds an emoji reaction. Send an empty Emoji to remove.+type ReactMessageRequest struct {+ ChatID string `json:"chatId"`+ MessageID string `json:"messageId"`+ Emoji string `json:"emoji"`+}++// DeleteMessageRequest deletes a message. ForEveryone defaults to true server-side.+type DeleteMessageRequest struct {+ ChatID string `json:"chatId"`+ MessageID string `json:"messageId"`+ ForEveryone *bool `json:"forEveryone,omitempty"`+}++// ListMessagesQuery filters GET /sessions/:id/messages.+type ListMessagesQuery struct {+ ChatID *string+ From *string+ Limit *int+ Offset *int+}++func (q *ListMessagesQuery) values() url.Values {+ v := url.Values{}+ setStr(v, "chatId", q.ChatID)+ setStr(v, "from", q.From)+ setInt(v, "limit", q.Limit)+ setInt(v, "offset", q.Offset)+ return v+}++// MessageHistoryQuery filters the live chat history read.+type MessageHistoryQuery struct {+ Limit *int+ IncludeMedia *bool+ Deep *bool+}++func (q *MessageHistoryQuery) values() url.Values {+ v := url.Values{}+ setInt(v, "limit", q.Limit)+ setBool(v, "includeMedia", q.IncludeMedia)+ setBool(v, "deep", q.Deep)+ return v+}++// MessageRecord is a persisted message row.+type MessageRecord struct {+ ID string `json:"id"`+ SessionID string `json:"sessionId"`+ WaMessageID *string `json:"waMessageId,omitempty"`+ ChatID string `json:"chatId"`+ From string `json:"from"`+ To string `json:"to"`+ Body *string `json:"body,omitempty"`+ Type string `json:"type"`+ Direction string `json:"direction"`+ Timestamp *int64 `json:"timestamp,omitempty"`+ Metadata map[string]any `json:"metadata,omitempty"`+ Status string `json:"status"`+ CreatedAt string `json:"createdAt"`+}++// MessageListResponse is the paginated message list payload.+type MessageListResponse struct {+ Messages []MessageRecord `json:"messages"`+ Total int `json:"total"`+}++// ChatHistoryMedia is the media block on a live history message.+type ChatHistoryMedia struct {+ Mimetype string `json:"mimetype,omitempty"`+ Filename string `json:"filename,omitempty"`+ Data string `json:"data,omitempty"`+ Omitted bool `json:"omitted,omitempty"`+ SizeBytes int64 `json:"sizeBytes,omitempty"`+}++// QuotedMessage is the quoted-message block on a live history message.+type QuotedMessage struct {+ ID string `json:"id,omitempty"`+ Body string `json:"body,omitempty"`+}++// MessageLocation is the location block on a live history message.+type MessageLocation struct {+ Latitude float64 `json:"latitude,omitempty"`+ Longitude float64 `json:"longitude,omitempty"`+ Description string `json:"description,omitempty"`+ Address string `json:"address,omitempty"`+ URL string `json:"url,omitempty"`+}++// ChatHistoryMessage is a message read live from WhatsApp by Messages.History —+// the richer engine payload, differently shaped from MessageRecord.+type ChatHistoryMessage struct {+ ID string `json:"id"`+ From string `json:"from"`+ To string `json:"to"`+ ChatID string `json:"chatId"`+ Body string `json:"body,omitempty"`+ Type string `json:"type"`+ Timestamp int64 `json:"timestamp"`+ FromMe bool `json:"fromMe"`+ IsGroup bool `json:"isGroup"`+ IsStatusBroadcast bool `json:"isStatusBroadcast"`+ Author string `json:"author,omitempty"`+ MentionedIDs []string `json:"mentionedIds,omitempty"`+ IsLidSender bool `json:"isLidSender,omitempty"`+ SenderPhone *string `json:"senderPhone,omitempty"`+ Media *ChatHistoryMedia `json:"media,omitempty"`+ QuotedMessage *QuotedMessage `json:"quotedMessage,omitempty"`+ Location *MessageLocation `json:"location,omitempty"`+}++// ReactionSender is one sender within a ReactionRecord.+type ReactionSender struct {+ SenderID string `json:"senderId"`+ Emoji string `json:"emoji"`+ Timestamp int64 `json:"timestamp"`+}++// ReactionRecord groups everyone who reacted with a given emoji.+type ReactionRecord struct {+ Emoji string `json:"emoji"`+ Senders []ReactionSender `json:"senders"`+}++// BulkMediaContent is a per-item media block for a bulk send. It mirrors the+// server's BulkMediaDto whitelist (url/base64/mimetype/filename/ptt) exactly. It+// deliberately omits chatId (the parent BulkMessageItem carries it) and caption+// (which lives at the BulkMessageContent level, not on the media object) so the+// server's forbidNonWhitelisted validator does not reject a stray field.+//+// PTT applies to audio only: set it true to send the audio as a WhatsApp voice+// note. It is ignored for image/video/document.+type BulkMediaContent struct {+ URL string `json:"url,omitempty"`+ Base64 string `json:"base64,omitempty"`+ Mimetype string `json:"mimetype,omitempty"`+ Filename string `json:"filename,omitempty"`+ PTT bool `json:"ptt,omitempty"`+}++// BulkMessageContent is the per-item content of a bulk send.+type BulkMessageContent struct {+ Text string `json:"text,omitempty"`+ Image *BulkMediaContent `json:"image,omitempty"`+ Video *BulkMediaContent `json:"video,omitempty"`+ Audio *BulkMediaContent `json:"audio,omitempty"`+ Document *BulkMediaContent `json:"document,omitempty"`+ Caption string `json:"caption,omitempty"`+}++// BulkMessageItem is one message in a bulk send. Type is one of: text, image,+// video, audio, document.+type BulkMessageItem struct {+ ChatID string `json:"chatId"`+ Type string `json:"type"`+ Content BulkMessageContent `json:"content"`+ Variables map[string]string `json:"variables,omitempty"`+}++// BulkOptions tunes bulk delivery pacing and error behavior.+type BulkOptions struct {+ DelayBetweenMessages *int `json:"delayBetweenMessages,omitempty"`+ RandomizeDelay *bool `json:"randomizeDelay,omitempty"`+ StopOnError *bool `json:"stopOnError,omitempty"`+}++// SendBulkRequest queues a batch of messages.+type SendBulkRequest struct {+ Messages []BulkMessageItem `json:"messages"`+ Options *BulkOptions `json:"options,omitempty"`+ BatchID string `json:"batchId,omitempty"`+}++// BulkMessageResponse is the send-bulk acknowledgement.+type BulkMessageResponse struct {+ BatchID string `json:"batchId"`+ Status string `json:"status"`+ TotalMessages int `json:"totalMessages"`+ EstimatedCompletionTime string `json:"estimatedCompletionTime"`+ StatusURL string `json:"statusUrl"`+}++// BatchError is a per-message failure in a batch result.+type BatchError struct {+ Code string `json:"code,omitempty"`+ Message string `json:"message,omitempty"`+}++// BatchMessageResult is one message's outcome within a batch.+type BatchMessageResult struct {+ ChatID string `json:"chatId"`+ Status string `json:"status"`+ MessageID string `json:"messageId,omitempty"`+ SentAt string `json:"sentAt,omitempty"`+ Error *BatchError `json:"error,omitempty"`+}++// BatchProgress is the aggregate progress of a batch.+type BatchProgress struct {+ Total int `json:"total"`+ Sent int `json:"sent"`+ Failed int `json:"failed"`+ Pending int `json:"pending"`+ Cancelled int `json:"cancelled"`+}++// BatchStatusResponse is the response from the batch status / cancel endpoints.+type BatchStatusResponse struct {+ BatchID string `json:"batchId"`+ Status string `json:"status"`+ Progress BatchProgress `json:"progress"`+ Results []BatchMessageResult `json:"results,omitempty"`+ StartedAt string `json:"startedAt,omitempty"`+ CompletedAt string `json:"completedAt,omitempty"`+}diff --git a/sdk/go/types_misc.go b/sdk/go/types_misc.gonew file mode 100644index 000000000..b23900a3b--- /dev/null+++ b/sdk/go/types_misc.go@@ -0,0 +1,75 @@+package openwa++// ── Health ──────────────────────────────────────────────++// HealthResponse is the /health payload.+type HealthResponse struct {+ Status string `json:"status"`+ Timestamp string `json:"timestamp,omitempty"`+ Version string `json:"version,omitempty"`+}++// DependencyStatus is one dependency's health snapshot inside a readiness+// payload (e.g. {"mainDatabase":{"status":"up"}}).+type DependencyStatus struct {+ Status string `json:"status"`+}++// HealthReadyResponse is the /health/ready payload. Details maps a dependency+// name (e.g. "mainDatabase", "dataDatabase") to its DependencyStatus.+type HealthReadyResponse struct {+ Status string `json:"status"`+ Details map[string]DependencyStatus `json:"details,omitempty"`+}++// ── Auth ─────────────────────────────────────────────────++// AuthValidateResponse reports whether the API key is valid and its role.+type AuthValidateResponse struct {+ Valid bool `json:"valid"`+ Role string `json:"role,omitempty"`+}++// ── Template ───────────────────────────────────────────++// TemplateRecord is a stored message template with {{variable}} placeholders.+type TemplateRecord struct {+ ID string `json:"id"`+ SessionID string `json:"sessionId"`+ Name string `json:"name"`+ Body string `json:"body"`+ Header *string `json:"header,omitempty"`+ Footer *string `json:"footer,omitempty"`+ CreatedAt string `json:"createdAt"`+ UpdatedAt string `json:"updatedAt"`+}++// CreateTemplateRequest creates a template. Name and Body required.+type CreateTemplateRequest struct {+ Name string `json:"name"`+ Body string `json:"body"`+ Header string `json:"header,omitempty"`+ Footer string `json:"footer,omitempty"`+}++// UpdateTemplateRequest updates a template; all fields optional.+type UpdateTemplateRequest struct {+ Name string `json:"name,omitempty"`+ Body string `json:"body,omitempty"`+ Header string `json:"header,omitempty"`+ Footer string `json:"footer,omitempty"`+}++// ── Label (WhatsApp Business) ────────────────────────────────++// LabelRecord is a WhatsApp Business chat label.+type LabelRecord struct {+ ID string `json:"id"`+ Name string `json:"name"`+ HexColor string `json:"hexColor,omitempty"`+}++// AddLabelRequest applies a label to a chat.+type AddLabelRequest struct {+ LabelID string `json:"labelId"`+}diff --git a/sdk/go/types_search.go b/sdk/go/types_search.gonew file mode 100644index 000000000..496f48eb1--- /dev/null+++ b/sdk/go/types_search.go@@ -0,0 +1,56 @@+package openwa++import "net/url"++// SearchQuery is the query for GET /search. Q is required; all else optional.+// DateFrom/DateTo are epoch-ms.+type SearchQuery struct {+ Q string+ SessionID *string+ ChatID *string+ Direction *string+ Type *string+ From *string+ DateFrom *int64+ DateTo *int64+ Limit *int+ Offset *int+}++func (q *SearchQuery) values() url.Values {+ v := url.Values{}+ v.Set("q", q.Q)+ setStr(v, "sessionId", q.SessionID)+ setStr(v, "chatId", q.ChatID)+ setStr(v, "direction", q.Direction)+ setStr(v, "type", q.Type)+ setStr(v, "from", q.From)+ setInt64(v, "dateFrom", q.DateFrom)+ setInt64(v, "dateTo", q.DateTo)+ setInt(v, "limit", q.Limit)+ setInt(v, "offset", q.Offset)+ return v+}++// SearchHit is one search result.+type SearchHit struct {+ MessageID string `json:"messageId"`+ WaMessageID string `json:"waMessageId"`+ SessionID string `json:"sessionId"`+ ChatID string `json:"chatId"`+ Body string `json:"body"`+ Snippet string `json:"snippet"`+ Timestamp int64 `json:"timestamp"`+ Type string `json:"type"`+ Direction string `json:"direction"`+ From string `json:"from"`+ Score float64 `json:"score,omitempty"`+}++// SearchResults is the GET /search payload.+type SearchResults struct {+ Hits []SearchHit `json:"hits"`+ Total int `json:"total"`+ TookMs int `json:"tookMs"`+ Provider string `json:"provider"`+}diff --git a/sdk/go/types_session.go b/sdk/go/types_session.gonew file mode 100644index 000000000..14fd0b5c8--- /dev/null+++ b/sdk/go/types_session.go@@ -0,0 +1,74 @@+package openwa++import "net/url"++// ListSessionsQuery paginates GET /sessions. Both fields optional.+type ListSessionsQuery struct {+ Limit *int+ Offset *int+}++func (q *ListSessionsQuery) values() url.Values {+ v := url.Values{}+ setInt(v, "limit", q.Limit)+ setInt(v, "offset", q.Offset)+ return v+}++// SessionResponse describes a WhatsApp session. Status is one of: created,+// initializing, qr_ready, authenticating, ready, disconnected, failed.+type SessionResponse struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Status string `json:"status"`+ Phone *string `json:"phone,omitempty"`+ PushName *string `json:"pushName,omitempty"`+ ConnectedAt *string `json:"connectedAt,omitempty"`+ LastActive *string `json:"lastActive,omitempty"`+ CreatedAt string `json:"createdAt,omitempty"`+ UpdatedAt string `json:"updatedAt,omitempty"`+ LastError *string `json:"lastError,omitempty"`+}++// CreateSessionRequest is the body for creating a session. ProxyType is one of:+// http, https, socks4, socks5.+type CreateSessionRequest struct {+ Name string `json:"name"`+ Config map[string]any `json:"config,omitempty"`+ ProxyURL string `json:"proxyUrl,omitempty"`+ ProxyType string `json:"proxyType,omitempty"`+}++// QrCodeResponse carries the current QR code for a session awaiting scan.+type QrCodeResponse struct {+ QrCode string `json:"qrCode"`+ Status string `json:"status"`+}++// PairingCodeResponse carries a phone-pairing code.+type PairingCodeResponse struct {+ PairingCode string `json:"pairingCode"`+ Status string `json:"status"`+}++// RequestPairingCodeRequest requests a pairing code for a phone number.+type RequestPairingCodeRequest struct {+ PhoneNumber string `json:"phoneNumber"`+}++// MemoryUsage is the process memory snapshot in the stats overview.+type MemoryUsage struct {+ HeapUsed int64 `json:"heapUsed"`+ HeapTotal int64 `json:"heapTotal"`+ RSS int64 `json:"rss"`+}++// SessionStatsOverview is the aggregate session stats payload.+type SessionStatsOverview struct {+ Total int `json:"total"`+ Active int `json:"active"`+ Ready int `json:"ready"`+ Disconnected int `json:"disconnected"`+ ByStatus map[string]int `json:"byStatus,omitempty"`+ MemoryUsage MemoryUsage `json:"memoryUsage"`+}diff --git a/sdk/go/types_status.go b/sdk/go/types_status.gonew file mode 100644index 000000000..d06df5096--- /dev/null+++ b/sdk/go/types_status.go@@ -0,0 +1,65 @@+package openwa++// StatusContact is the poster of a status entry (from a GET list).+type StatusContact struct {+ ID string `json:"id"`+ Name string `json:"name,omitempty"`+ PushName string `json:"pushName,omitempty"`+}++// StatusRecord is a status/story entry as returned by GET endpoints.+type StatusRecord struct {+ ID string `json:"id"`+ Contact StatusContact `json:"contact"`+ Type string `json:"type,omitempty"`+ Caption string `json:"caption,omitempty"`+ 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"`+}++// StatusListResponse is the {"statuses": [...]} envelope returned by GET+// /sessions/:id/status and GET /sessions/:id/status/:contactId.+type StatusListResponse struct {+ Statuses []StatusRecord `json:"statuses"`+}++// StatusResult is the acknowledgement returned by Send{Text,Image,Video}Status.+// 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"`+}++// SendTextStatusRequest posts a text status. Recipients is required.+type SendTextStatusRequest struct {+ Text string `json:"text"`+ Recipients []string `json:"recipients"`+ BackgroundColor string `json:"backgroundColor,omitempty"`+ Font *int `json:"font,omitempty"`+}++// StatusMediaInput is a status media payload: provide URL or Base64.+type StatusMediaInput struct {+ URL string `json:"url,omitempty"`+ Base64 string `json:"base64,omitempty"`+ Mimetype string `json:"mimetype,omitempty"`+}++// SendImageStatusRequest posts an image status (nested {image:{...}} body).+type SendImageStatusRequest struct {+ Image StatusMediaInput `json:"image"`+ Recipients []string `json:"recipients"`+ Caption string `json:"caption,omitempty"`+}++// SendVideoStatusRequest posts a video status (nested {video:{...}} body).+type SendVideoStatusRequest struct {+ Video StatusMediaInput `json:"video"`+ Recipients []string `json:"recipients"`+ Caption string `json:"caption,omitempty"`+}diff --git a/sdk/go/types_webhook.go b/sdk/go/types_webhook.gonew file mode 100644index 000000000..8059da4ce--- /dev/null+++ b/sdk/go/types_webhook.go@@ -0,0 +1,60 @@+package openwa++// WebhookFilterCondition is one condition in a webhook filter. Value is+// polymorphic per field kind — the server accepts a string (text fields), a+// []string (id/idArray/enum fields), or a bool (boolean fields). Passing a+// []string for a text/boolean field triggers a 400. Use any so all shapes+// round-trip cleanly for both create and read-back.+type WebhookFilterCondition struct {+ Field string `json:"field"`+ Operator string `json:"operator"`+ Value any `json:"value"`+ CaseSensitive *bool `json:"caseSensitive,omitempty"`+}++// WebhookFilters groups filter conditions.+type WebhookFilters struct {+ Conditions []WebhookFilterCondition `json:"conditions"`+}++// CreateWebhookRequest registers a webhook. RetryCount is 0–5 (default 3).+type CreateWebhookRequest struct {+ URL string `json:"url"`+ Events []string `json:"events"`+ Secret string `json:"secret,omitempty"`+ Headers map[string]string `json:"headers,omitempty"`+ Filters *WebhookFilters `json:"filters,omitempty"`+ RetryCount *int `json:"retryCount,omitempty"`+}++// UpdateWebhookRequest updates a webhook; all fields optional.+type UpdateWebhookRequest struct {+ URL string `json:"url,omitempty"`+ Events []string `json:"events,omitempty"`+ Secret string `json:"secret,omitempty"`+ Headers map[string]string `json:"headers,omitempty"`+ Filters *WebhookFilters `json:"filters,omitempty"`+ RetryCount *int `json:"retryCount,omitempty"`+ Active *bool `json:"active,omitempty"`+}++// WebhookResponse is a stored webhook (secret/headers are omitted on reads).+type WebhookResponse struct {+ ID string `json:"id"`+ SessionID string `json:"sessionId"`+ URL string `json:"url"`+ Events []string `json:"events"`+ Active bool `json:"active"`+ Filters *WebhookFilters `json:"filters,omitempty"`+ RetryCount int `json:"retryCount,omitempty"`+ LastTriggeredAt *string `json:"lastTriggeredAt,omitempty"`+ CreatedAt string `json:"createdAt"`+ UpdatedAt string `json:"updatedAt"`+}++// WebhookTestResult is the outcome of a webhook test delivery.+type WebhookTestResult struct {+ Success bool `json:"success"`+ StatusCode int `json:"statusCode,omitempty"`+ Error string `json:"error,omitempty"`+}diff --git a/sdk/go/webhooks.go b/sdk/go/webhooks.gonew file mode 100644index 000000000..4a2a3f700--- /dev/null+++ b/sdk/go/webhooks.go@@ -0,0 +1,63 @@+package openwa++import "context"++// WebhooksService configures event delivery to external HTTP endpoints.+// Backed by src/modules/webhook/webhook.controller.ts.+type WebhooksService struct{ client *Client }++func (s *WebhooksService) base(sessionID string) string {+ return "/api/sessions/" + pathEscape(sessionID) + "/webhooks"+}++// List returns webhooks for a session.+func (s *WebhooksService) List(ctx context.Context, sessionID string) ([]WebhookResponse, error) {+ var out []WebhookResponse+ err := s.client.do(ctx, "GET", s.base(sessionID), nil, nil, &out)+ return out, err+}++// Get returns a single webhook.+func (s *WebhooksService) Get(ctx context.Context, sessionID, webhookID string) (*WebhookResponse, error) {+ var out WebhookResponse+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(webhookID), nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Create registers a webhook.+func (s *WebhooksService) Create(ctx context.Context, sessionID string, body CreateWebhookRequest) (*WebhookResponse, error) {+ var out WebhookResponse+ err := s.client.do(ctx, "POST", s.base(sessionID), nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Update modifies a webhook.+func (s *WebhooksService) Update(ctx context.Context, sessionID, webhookID string, body UpdateWebhookRequest) (*WebhookResponse, error) {+ var out WebhookResponse+ err := s.client.do(ctx, "PUT", s.base(sessionID)+"/"+pathEscape(webhookID), nil, body, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}++// Delete removes a webhook.+func (s *WebhooksService) Delete(ctx context.Context, sessionID, webhookID string) error {+ return s.client.do(ctx, "DELETE", s.base(sessionID)+"/"+pathEscape(webhookID), nil, nil, nil)+}++// Test triggers a test delivery.+func (s *WebhooksService) Test(ctx context.Context, sessionID, webhookID string) (*WebhookTestResult, error) {+ var out WebhookTestResult+ err := s.client.do(ctx, "POST", s.base(sessionID)+"/"+pathEscape(webhookID)+"/test", nil, nil, &out)+ if err != nil {+ return nil, err+ }+ return &out, nil+}