# Go client: net/http, context and a shared limiter

> A small package on the standard library only. Every call takes a context, refusals are typed so errors.As works, and cleanup runs through defer with a context that survives the deadline that caused the failure.

Source: https://otpwatch.com/go
Updated: 2026-11-24
API key: https://otpwatch.com/agent/key

## The package

Go 1.22 or newer (for `math/rand/v2`; on 1.21 swap it for `math/rand`).

```go title="otp/otp.go"
// handler_api reference: https://otpwatch.com/go
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner

// Package otp is a minimal handler_api.php client using only the standard library.
package otp

import (
	"context"
	"errors"
	"fmt"
	"io"
	"math/rand/v2"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"
)

const DefaultBaseURL = "https://sim-aggregator.org/stubs/handler_api.php"

// APIError is a refusal from the API, such as NO_NUMBERS or WRONG_MAX_PRICE:1.5.
type APIError struct{ Reply, Code string }

func (e *APIError) Error() string { return "sms api: " + e.Reply }

func refusal(reply string) *APIError {
	code, _, _ := strings.Cut(reply, ":")
	return &APIError{Reply: reply, Code: code}
}

type Client struct {
	BaseURL string
	APIKey  string
	HTTP    *http.Client
}

// New reads the base URL from SMS_API_BASE_URL and falls back to DefaultBaseURL.
func New(apiKey string) *Client {
	base := os.Getenv("SMS_API_BASE_URL")
	if base == "" {
		base = DefaultBaseURL
	}
	return &Client{BaseURL: base, APIKey: apiKey, HTTP: &http.Client{Timeout: 30 * time.Second}}
}

func sleep(ctx context.Context, d time.Duration) error {
	t := time.NewTimer(d)
	defer t.Stop()
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-t.C:
		return nil
	}
}

// Call sends one action and returns the trimmed body. REQUEST_LIMIT is retried with backoff.
func (c *Client) Call(ctx context.Context, action string, params url.Values) (string, error) {
	q := url.Values{}
	for k, v := range params {
		q[k] = v
	}
	q.Set("action", action)
	q.Set("api_key", c.APIKey)
	for attempt := 0; attempt < 6; attempt++ {
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"?"+q.Encode(), nil)
		if err != nil {
			return "", err
		}
		resp, err := c.HTTP.Do(req)
		if err != nil {
			return "", err
		}
		body, err := io.ReadAll(resp.Body)
		resp.Body.Close()
		if err != nil {
			return "", err
		}
		if resp.StatusCode >= 400 {
			return "", fmt.Errorf("sms api: HTTP %d on %s", resp.StatusCode, action)
		}
		text := strings.TrimSpace(string(body))
		if text != "REQUEST_LIMIT" {
			return text, nil
		}
		backoff := time.Duration(min(1<<attempt, 30))*time.Second + time.Duration(rand.IntN(500))*time.Millisecond
		if err := sleep(ctx, backoff); err != nil {
			return "", err
		}
	}
	return "", refusal("REQUEST_LIMIT")
}

func (c *Client) Balance(ctx context.Context) (float64, error) {
	reply, err := c.Call(ctx, "getBalance", nil)
	if err != nil {
		return 0, err
	}
	amount, ok := strings.CutPrefix(reply, "ACCESS_BALANCE:")
	if !ok {
		return 0, refusal(reply)
	}
	return strconv.ParseFloat(amount, 64)
}

type Order struct {
	Service  string
	Country  int
	MaxPrice float64 // 0 means no cap
	Duration string  // "", "d1", "d3" or "d7"
}

type Activation struct {
	ID    string
	Phone string // without '+'
	Code  string
	c     *Client
}

func (a *Activation) E164() string { return "+" + a.Phone }

func (c *Client) Order(ctx context.Context, o Order) (*Activation, error) {
	p := url.Values{"service": {o.Service}, "country": {strconv.Itoa(o.Country)}}
	if o.MaxPrice > 0 {
		p.Set("maxPrice", strconv.FormatFloat(o.MaxPrice, 'f', -1, 64))
	}
	if o.Duration != "" {
		p.Set("duration", o.Duration)
	}
	reply, err := c.Call(ctx, "getNumber", p)
	if err != nil {
		return nil, err
	}
	rest, ok := strings.CutPrefix(reply, "ACCESS_NUMBER:")
	if !ok {
		return nil, refusal(reply)
	}
	id, phone, _ := strings.Cut(rest, ":")
	return &Activation{ID: id, Phone: phone, c: c}, nil
}

// WaitCode polls getStatus every interval until a code arrives or ctx is done.
func (a *Activation) WaitCode(ctx context.Context, interval time.Duration) (string, error) {
	for {
		reply, err := a.c.Call(ctx, "getStatus", url.Values{"id": {a.ID}})
		if err != nil {
			return "", err
		}
		if code, ok := strings.CutPrefix(reply, "STATUS_OK:"); ok {
			a.Code = code
			return code, nil
		}
		if !strings.HasPrefix(reply, "STATUS_WAIT") {
			return "", refusal(reply)
		}
		if err := sleep(ctx, interval); err != nil {
			return "", err
		}
	}
}

func (a *Activation) setStatus(ctx context.Context, status int) (string, error) {
	return a.c.Call(ctx, "setStatus", url.Values{"id": {a.ID}, "status": {strconv.Itoa(status)}})
}

// AnotherCode asks for a new SMS on the same number (setStatus 3).
func (a *Activation) AnotherCode(ctx context.Context) error {
	_, err := a.setStatus(ctx, 3)
	a.Code = ""
	return err
}

// Our choice, not an API rule: the docs only say "too early to cancel, repeat the request later".
const (
	cancelTries = 9
	cancelPause = 10 * time.Second
)

// Close finishes the activation if a code was read and cancels it otherwise.
func (a *Activation) Close(ctx context.Context) error {
	if a.Code != "" {
		_, err := a.setStatus(ctx, 6)
		return err
	}
	for i := 0; i < cancelTries; i++ {
		reply, err := a.setStatus(ctx, 8)
		if err != nil {
			return err
		}
		if reply != "EARLY_CANCEL_DENIED" {
			return nil
		}
		if i == cancelTries-1 {
			break
		}
		if err := sleep(ctx, cancelPause); err != nil { // too early to cancel: repeat later
			return err
		}
	}
	return errors.New("sms api: cancel still EARLY_CANCEL_DENIED after the last try; cancel it later")
}
```

## Use it

```env title=".env.example"
# handler_api reference: https://otpwatch.com/go
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
SMS_API_BASE_URL=https://sim-aggregator.org/stubs/handler_api.php
# Key from the SimAggregator dashboard: https://otpwatch.com/agent/key
SMS_API_KEY=
```

```go title="main.go"
// handler_api reference: https://otpwatch.com/go
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"time"

	"example.com/yourapp/internal/otp"
)

func main() {
	client := otp.New(os.Getenv("SMS_API_KEY"))
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
	defer cancel()

	act, err := client.Order(ctx, otp.Order{Service: "tg", Country: 16, MaxPrice: 2}) // Telegram, UK
	var refused *otp.APIError
	if errors.As(err, &refused) && (refused.Code == "NO_NUMBERS" || refused.Code == "WRONG_MAX_PRICE") {
		log.Fatalf("not ordered: %s", refused.Reply)
	} else if err != nil {
		log.Fatal(err)
	}
	// WithoutCancel: cleanup must still run after the 5-minute deadline has fired.
	defer act.Close(context.WithoutCancel(ctx))

	fmt.Println("number:", act.E164())
	// ... make the app under test send the SMS to act.E164() ...
	code, err := act.WaitCode(ctx, 3*time.Second)
	if err != nil {
		log.Fatal(err) // note: log.Fatal skips defers; return an error instead in real code
	}
	fmt.Println("code:", code)
}
```

`context.WithoutCancel` (Go 1.21) is the detail people miss: if `WaitCode` failed because the deadline expired, a `Close` that reused the same context would fail instantly and leave the order open.

## Many goroutines, one key

The 600-requests-per-minute limit belongs to the key, not to a goroutine. Put one ticker in front of every call:

```go title="limiter.go"
// handler_api reference: https://otpwatch.com/go
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner

// Shared by all goroutines: at most 480 calls a minute, no bursts.
type Limited struct {
	*otp.Client
	tick *time.Ticker
}

func NewLimited(c *otp.Client, perMinute int) *Limited {
	return &Limited{Client: c, tick: time.NewTicker(time.Minute / time.Duration(perMinute))}
}

func (l *Limited) Call(ctx context.Context, action string, p url.Values) (string, error) {
	select {
	case <-l.tick.C:
		return l.Client.Call(ctx, action, p)
	case <-ctx.Done():
		return "", ctx.Err()
	}
}
```

A `time.Ticker` drops ticks nobody is waiting for, so idle periods do not build up a burst. If you want the limiter inside the package instead, give `Client` a `Limit <-chan time.Time` field and wait on it at the top of `Call`.

## Tests with httptest

```go title="otp/otp_test.go"
// handler_api reference: https://otpwatch.com/go
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner

package otp

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

func scripted(t *testing.T, replies ...string) (*Client, *[]string) {
	t.Helper()
	var seen []string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		seen = append(seen, r.URL.RawQuery)
		w.Write([]byte(replies[0]))
		replies = replies[1:]
	}))
	t.Cleanup(srv.Close)
	c := New("k")
	c.BaseURL = srv.URL
	return c, &seen
}

func TestCodeKeepsLeadingZeros(t *testing.T) {
	c, seen := scripted(t, "ACCESS_NUMBER:9:447700900123", "STATUS_WAIT_CODE", "STATUS_OK:004821", "ACCESS_ACTIVATION")
	ctx := context.Background()
	act, err := c.Order(ctx, Order{Service: "tg", Country: 16})
	if err != nil {
		t.Fatal(err)
	}
	if code, err := act.WaitCode(ctx, time.Millisecond); err != nil || code != "004821" {
		t.Fatalf("code=%q err=%v", code, err)
	}
	if err := act.Close(ctx); err != nil {
		t.Fatal(err)
	}
	if last := (*seen)[len(*seen)-1]; !strings.Contains(last, "status=6") {
		t.Fatalf("last call was %s", last)
	}
}

func TestRefusalIsTyped(t *testing.T) {
	c, _ := scripted(t, "WRONG_MAX_PRICE:1.95")
	_, err := c.Order(context.Background(), Order{Service: "tg", Country: 16, MaxPrice: 1})
	var refused *APIError
	if !errors.As(err, &refused) || refused.Code != "WRONG_MAX_PRICE" {
		t.Fatalf("got %v", err)
	}
}
```

## Notes

- Prices come as decimals in USD; `float64` is fine for comparisons against a cap. If you keep a ledger, store cents as integers.
- Keep codes as `string`; `strconv.Atoi("004821")` returns 4821.
- For rentals set `Duration: "d3"` (or `d1`, `d7`); see [renting a number](https://otpwatch.com/rent-number-api.md).
