OTP verification in Go: net/http, sessions and every error code
Written by Vivek SinghReviewed by the DiOTP team Published 3 December 2026Last updated 3 December 2026
11 min read
OTP verification in Go needs two HTTP handlers: one asks DiOTP to send a code and stores the returned request_id in the user's session, the other passes that request_id and the typed code to DiOTP and signs the user in on a 200. DiOTP generates, stores and checks the code, so your service never handles it. This guide writes the client with the standard library only, maps every DiOTP error code, handles 429 limits and the 30 second resend cooldown, and tests the client with httptest.
How the flow works
DiOTP exposes two endpoints. POST /v1/otp/send takes a mobile number and replies with a request_id; POST /v1/otp/verify takes that request_id and the code the user typed, and replies 200 when it matches. Codes expire after 5 minutes and allow 5 attempts. Both calls authenticate with your API key as a Bearer token.
- The client posts a phone number to POST /api/otp/send on your Go service.
- The handler validates it, calls DiOTP and stores the request_id in the session.
- The client posts the typed code to POST /api/otp/verify.
- The handler reads the request_id from the session, calls DiOTP and, on success, signs the user in.
The API key belongs in your server's environment, never in a front end or a mobile binary, where it can be extracted.
On DiOTP you can send without your own DLT registration, on DiOTP's registered header and pre-approved OTP template: see OTP without DLT. The Go code here stays the same when you later switch to your own sender ID.
Build it step by step
- Use Go 1.22 or newer, which added method and path patterns to http.ServeMux.
- Run go mod init example.com/otp, then go get github.com/alexedwards/scs/v2 golang.org/x/time/rate for sessions and the per-IP limiter.
- Sign up for DiOTP, create an API key and export it as DIOTP_API_KEY.
- Add the diotp package, then the handlers, the error map and the limiter in package main.
- Run go test ./..., then try the flow on your own number in test mode.
The DiOTP client itself uses only the standard library. scs is a widely used session manager for net/http, and x/time/rate is the Go team's token bucket. Swap either for what your project already uses; the pattern does not change. The same handlers also work inside chi, Gin or Echo, because each framework can mount a plain http.Handler, and the session middleware wraps the whole router.
A DiOTP client with the standard library
The client sets the Bearer key, a 10 second timeout and JSON headers, and turns any 4xx or 5xx reply into an *APIError carrying the HTTP status and the stable error code from DiOTP's envelope, {"error":{"code":"...","message":"..."}}. Callers use errors.As to read it.
diotp/diotp.go
// diotp/diotp.go: a DiOTP client using only the standard library.
package diotp
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"time"
)
const baseURL = "https://api-diotp.diorbit.com/v1"
// APIError is an error reply from DiOTP. Branch on Code, never on Message.
type APIError struct {
Status int
Code string
Message string
}
func (e *APIError) Error() string { return fmt.Sprintf("diotp: %d %s: %s", e.Status, e.Code, e.Message) }
type SendResult struct {
RequestID string `json:"request_id"`
Channel string `json:"channel"`
ExpiresAt string `json:"expires_at"`
}
type VerifyResult struct {
RequestID string `json:"request_id"`
Verified bool `json:"verified"`
VerifiedAt string `json:"verified_at"`
}
type Client struct {
apiKey string
base string
http *http.Client
}
// FromEnv reads DIOTP_API_KEY. Call it at start-up so a missing key fails fast.
func FromEnv() (*Client, error) {
key := os.Getenv("DIOTP_API_KEY")
if key == "" {
return nil, errors.New("DIOTP_API_KEY is not set")
}
return &Client{apiKey: key, base: baseURL, http: &http.Client{Timeout: 10 * time.Second}}, nil
}
// Send texts a code to a 10-digit Indian number. The code never reaches you.
func (c *Client) Send(ctx context.Context, phone, purpose string) (*SendResult, error) {
body := map[string]any{"to": phone, "country_code": 91, "channel": "sms", "purpose": purpose}
key := newKey() // one key per user action
var out SendResult
err := c.post(ctx, "/otp/send", body, key, &out)
var apiErr *APIError
if err != nil && (!errors.As(err, &apiErr) || apiErr.Code == "sending_unavailable") {
// Network failure or 503: retry once with the SAME key. DiOTP returns
// the first result instead of sending a second code.
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(1500 * time.Millisecond):
}
err = c.post(ctx, "/otp/send", body, key, &out)
}
if err != nil {
return nil, err
}
return &out, nil
}
// Verify checks the code the user typed against a request_id.
func (c *Client) Verify(ctx context.Context, requestID, code string) (*VerifyResult, error) {
var out VerifyResult
if err := c.post(ctx, "/otp/verify", map[string]string{"request_id": requestID, "code": code}, "", &out); err != nil {
return nil, err
}
return &out, nil
}
func (c *Client) post(ctx context.Context, path string, body any, idemKey string, out any) error {
buf, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.base+path, bytes.NewReader(buf))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.apiKey)
req.Header.Set("Content-Type", "application/json")
if idemKey != "" {
req.Header.Set("Idempotency-Key", idemKey)
}
res, err := c.http.Do(req)
if err != nil {
return err // network error or timeout
}
defer res.Body.Close()
if res.StatusCode >= 400 {
var env struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
_ = json.NewDecoder(res.Body).Decode(&env)
if env.Error.Code == "" {
env.Error.Code = "unknown"
}
return &APIError{Status: res.StatusCode, Code: env.Error.Code, Message: env.Error.Message}
}
return json.NewDecoder(res.Body).Decode(out)
}
func newKey() string {
b := make([]byte, 16)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}The send body uses to as digits only, the 10-digit number without +91, and country_code as the integer 91. Each send gets a fresh Idempotency-Key. On a network error or a 503 sending_unavailable, Send retries once with the same key, and DiOTP returns the first result rather than sending another code. The context is passed through, so a client that disconnects cancels the call. Field details are on the send OTP reference and the verify OTP reference.
The send and verify handlers
The handlers keep the request_id, the phone and the send time in the session, so the browser holds only an opaque session cookie. scs stores sessions in memory by default; in production, use one of its Redis or SQL stores so sessions survive restarts and work across instances.
main.go
// main.go (Go 1.22 or newer, for method patterns in http.ServeMux)
package main
import (
"encoding/json"
"errors"
"log"
"net/http"
"regexp"
"strconv"
"time"
"github.com/alexedwards/scs/v2"
"example.com/otp/diotp"
)
var (
sessions = scs.New()
otp *diotp.Client
mobile = regexp.MustCompile(`^[6-9][0-9]{9}$`)
digits = regexp.MustCompile(`^[0-9]{4,10}$`)
nonDigit = regexp.MustCompile(`[^0-9]`)
)
const cooldown = 30 * time.Second
func main() {
var err error
if otp, err = diotp.FromEnv(); err != nil {
log.Fatal(err)
}
sessions.Lifetime = 24 * time.Hour
sessions.Cookie.HttpOnly = true
sessions.Cookie.Secure = true
sessions.Cookie.SameSite = http.SameSiteLaxMode
mux := http.NewServeMux()
mux.Handle("POST /api/otp/send", perIP(http.HandlerFunc(sendCode)))
mux.HandleFunc("POST /api/otp/verify", verifyCode)
log.Fatal(http.ListenAndServe(":8080", sessions.LoadAndSave(mux)))
}
func sendCode(w http.ResponseWriter, r *http.Request) {
var in struct{ Phone string `json:"phone"` }
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<12)).Decode(&in); err != nil {
writeJSON(w, 400, map[string]any{"error": "bad_json"})
return
}
phone := nonDigit.ReplaceAllString(in.Phone, "")
if len(phone) == 12 && phone[:2] == "91" {
phone = phone[2:]
}
if !mobile.MatchString(phone) {
writeJSON(w, 400, map[string]any{"error": "invalid_phone", "message": "Enter a 10-digit mobile number."})
return
}
// Mirror DiOTP's 30 second cooldown: an instant 429, no API call.
ctx := r.Context()
if sessions.GetString(ctx, "otp_phone") == phone {
if since := time.Since(sessions.GetTime(ctx, "otp_sent_at")); since < cooldown {
wait := int((cooldown - since).Seconds()) + 1
w.Header().Set("Retry-After", strconv.Itoa(wait))
writeJSON(w, 429, map[string]any{"error": "resend_cooldown", "retry_after": wait})
return
}
}
res, err := otp.Send(ctx, phone, "login")
if err != nil {
writeOTPError(w, err)
return
}
sessions.Put(ctx, "otp_request_id", res.RequestID)
sessions.Put(ctx, "otp_phone", phone)
sessions.Put(ctx, "otp_sent_at", time.Now())
writeJSON(w, 200, map[string]any{"sent": true, "expires_at": res.ExpiresAt, "resend_in": 30})
}
func verifyCode(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
requestID := sessions.GetString(ctx, "otp_request_id")
if requestID == "" {
writeJSON(w, 400, map[string]any{"error": "no_pending_code", "message": "Ask for a code first."})
return
}
var in struct{ Code string `json:"code"` }
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<12)).Decode(&in); err != nil || !digits.MatchString(in.Code) {
writeJSON(w, 400, map[string]any{"error": "invalid_code", "message": "Enter the code from the SMS."})
return
}
_, err := otp.Verify(ctx, requestID, in.Code)
var apiErr *diotp.APIError
if err != nil && !(errors.As(err, &apiErr) && apiErr.Code == "already_verified") {
if apiErr != nil && finished[apiErr.Code] {
clearPending(r)
}
writeOTPError(w, err)
return
}
phone := sessions.GetString(ctx, "otp_phone")
clearPending(r)
if err := sessions.RenewToken(ctx); err != nil { // new session token at login
writeJSON(w, 500, map[string]any{"error": "session_error"})
return
}
sessions.Put(ctx, "verified_phone", phone) // sign the user in here
writeJSON(w, 200, map[string]any{"verified": true})
}
func clearPending(r *http.Request) {
for _, k := range []string{"otp_request_id", "otp_phone", "otp_sent_at"} {
sessions.Remove(r.Context(), k)
}
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}sendCode keeps its own copy of the 30 second cooldown: a second tap within 30 seconds gets an instant 429 with Retry-After and no API call. DiOTP still enforces the real limit, so another tab or device cannot get around it. verifyCode treats already_verified as success, since it usually means a double submit, and clears the pending request when it is finished. RenewToken issues a new session token at the moment of login, which prevents session fixation.
Map every error code to a reply
Decide once what each code means for the visitor. Codes they can act on go back with a plain message and, for rate limits, a Retry-After header. Everything else is a setup or account problem: log the status and code, never the key, and show a generic message.
errors.go
// errors.go: what the visitor sees for each DiOTP error code.
package main
import (
"errors"
"log/slog"
"net/http"
"strconv"
"example.com/otp/diotp"
)
type reply struct {
status int
message string
retryAfter int // seconds; 0 means no header
}
var userErrors = map[string]reply{
"resend_cooldown": {429, "Please wait 30 seconds before asking for another code.", 30},
"phone_hourly_limit": {429, "Too many codes for this number. Try again in an hour.", 3600},
"phone_daily_limit": {429, "Too many codes for this number today. Try tomorrow.", 0},
"api_key_minute_limit": {429, "We are busy right now. Please try again in a minute.", 60},
"rate_limited": {429, "We are busy right now. Please try again in a minute.", 60},
"invalid_code": {400, "That code is not right. Check the SMS and try again.", 0},
"expired": {410, "This code has expired. Ask for a new one.", 0},
"not_pending": {409, "This code is no longer valid. Ask for a new one.", 0},
"not_found": {404, "We could not find that code. Ask for a new one.", 0},
"too_many_attempts": {429, "Too many wrong tries. Ask for a new code.", 0},
"invalid_request": {400, "Enter a valid 10-digit mobile number.", 0},
}
// finished lists verify codes after which the request_id is no longer usable.
var finished = map[string]bool{"expired": true, "not_pending": true, "too_many_attempts": true, "not_found": true}
func writeOTPError(w http.ResponseWriter, err error) {
var apiErr *diotp.APIError
if errors.As(err, &apiErr) {
if r, ok := userErrors[apiErr.Code]; ok {
body := map[string]any{"error": apiErr.Code, "message": r.message}
if r.retryAfter > 0 {
w.Header().Set("Retry-After", strconv.Itoa(r.retryAfter))
body["retry_after"] = r.retryAfter
}
writeJSON(w, r.status, body)
return
}
// unauthorized, trial_restricted, trial_used_up, insufficient_balance,
// account_suspended, channel_not_enabled, test_limit, sending_unavailable ...
slog.Error("diotp error", "status", apiErr.Status, "code", apiErr.Code) // never log the key
} else {
slog.Error("diotp unreachable", "err", err)
}
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
"error": "otp_unavailable", "message": "We could not send a code right now. Please try again shortly.",
})
}| Code | Status | What the handler returns |
|---|---|---|
| resend_cooldown | 429 | Retry-After: 30. Keep the resend button disabled. |
| phone_hourly_limit | 429 | Retry-After: 3600. Come back in an hour. |
| phone_daily_limit | 429 | Try tomorrow; 10 codes per number per day. |
| api_key_minute_limit, rate_limited | 429 | Retry-After: 60. Alert yourself if it repeats. |
| invalid_code | 400 | Try again, up to 5 attempts. |
| expired | 410 | Offer a new code; codes last 5 minutes. |
| too_many_attempts | 429 | Start over with a new code. |
| unauthorized, trial_restricted, trial_used_up, insufficient_balance, test_limit | 401, 402, 403, 429 | Logged; generic reply. |
A 429 from DiOTP means nothing was sent and nothing was charged. Every code is listed on the error codes page.
Add a per-IP limit
DiOTP limits each number to one code every 30 seconds, 3 an hour and 10 a day, and each key to 30 sends a minute. A script that uses a new number each time gets past per-number limits, which is how SMS pumping drains a wallet. A per-IP limiter on the send route adds the missing layer.
ratelimit.go
// ratelimit.go: a per-IP limit on the send route.
package main
import (
"net"
"net/http"
"sync"
"time"
"golang.org/x/time/rate"
)
var (
mu sync.Mutex
visitors = map[string]*rate.Limiter{}
)
// 10 sends per IP per 15 minutes, with a burst of 3.
func limiterFor(ip string) *rate.Limiter {
mu.Lock()
defer mu.Unlock()
l, ok := visitors[ip]
if !ok {
l = rate.NewLimiter(rate.Every(90*time.Second), 3)
visitors[ip] = l
}
return l
}
func perIP(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip, _, _ := net.SplitHostPort(r.RemoteAddr) // behind a proxy, read the header YOUR proxy sets
if !limiterFor(ip).Allow() {
writeJSON(w, 429, map[string]any{"error": "too_many_requests", "message": "Too many requests. Try again later."})
return
}
next.ServeHTTP(w, r)
})
}The map grows with every new IP, so in a long-running service add a sweep that removes idle entries, or keep the counters in Redis when you run several instances. Behind a load balancer, read the client address from the header your own proxy sets, and only that one. The SMS pumping protection guide covers bot checks and monitoring too.
Test it without sending an SMS
httptest.NewServer gives the client a fake DiOTP. The tests check the headers, that to is digits and country_code is the number 91, and that a 429 comes back as an *APIError with the right code.
diotp/diotp_test.go
// diotp/diotp_test.go: the client against a fake server, no SMS sent.
package diotp
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
)
func testClient(t *testing.T, h http.HandlerFunc) *Client {
srv := httptest.NewServer(h)
t.Cleanup(srv.Close)
return &Client{apiKey: "test_key", base: srv.URL, http: srv.Client()}
}
func TestSendSendsDigitsAndIntegerCountryCode(t *testing.T) {
c := testClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer test_key" || r.Header.Get("Idempotency-Key") == "" {
t.Errorf("missing headers")
}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
if body["to"] != "9876543210" || body["country_code"] != float64(91) {
t.Errorf("bad body: %v", body)
}
w.Write([]byte(`{"request_id":"req_1","channel":"sms","expires_at":"2026-12-03T10:05:00Z"}`))
})
res, err := c.Send(context.Background(), "9876543210", "login")
if err != nil || res.RequestID != "req_1" {
t.Fatalf("got %v, %v", res, err)
}
}
func TestCooldownIsAnAPIError(t *testing.T) {
c := testClient(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(429)
w.Write([]byte(`{"error":{"code":"resend_cooldown","message":"wait"}}`))
})
_, err := c.Send(context.Background(), "9876543210", "login")
var apiErr *APIError
if !errors.As(err, &apiErr) || apiErr.Status != 429 || apiErr.Code != "resend_cooldown" {
t.Fatalf("got %v", err)
}
}Then test the live flow. A new DiOTP account has 10 free test messages, sent only to the mobile number you verified at sign-up; other numbers return 403 trial_restricted. Ask twice within 30 seconds to see resend_cooldown, and wait more than 5 minutes before verifying to see expired. Recharge your wallet from ₹100 to send to any Indian mobile number at ₹0.26 to ₹0.40 per OTP plus 18% GST.
Send OTP reference Verify OTP reference Error codes
OTP without DLT OTP integration basics OTP service system design
