Send SMS from Go with net/http, through your own phone
Only the standard library: a typed client, delivery status with a context deadline, retries that can't double-text, a CSV list and a webhook handler that checks its signature. Every sample ran on Go 1.27.
Sparetext
8 min read · Nov 11, 2026
Go people like their dependency list short, and an SMS SDK usually brings a whole tree of packages for what is, in the end, one POST request. Then there's the paid number and the carrier registration. If your texts go to people who already know you, none of that is needed: net/http and encoding/json are enough.
Sparetext turns the Android phone you already own into an SMS gateway with a plain HTTP API. Your Go program talks to our server, and the text goes out from your phone, on your number. Every sample below ran on 11 November on Go 1.27, against a test copy of Sparetext with a simulated phone on the other end, and passes gofmt and go vet.
What you need
- A Sparetext account. Free is 1 phone and 300 texts a month.
- An Android phone with the Sparetext app, paired in the dashboard. An iPhone works too, through Sparetext for Mac (the iPhone guide).
- An API key from the API keys page:
export SPARETEXT_API_KEY=spt_live_... - Go 1.22 or later (the webhook handler uses method patterns like
"POST /hooks/sparetext", new in 1.22). Nothing togo get.
Send your first text
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
)
const api = "https://sparetext.dev/api/v1"
func main() {
payload, _ := json.Marshal(map[string]string{
"to": "+12025550166",
"text": "Your table for 2 is ready. See you soon!",
})
req, _ := http.NewRequest("POST", api+"/messages", bytes.NewReader(payload))
req.Header.Set("x-api-key", os.Getenv("SPARETEXT_API_KEY"))
req.Header.Set("content-type", "application/json")
client := &http.Client{Timeout: 15 * time.Second}
res, err := client.Do(req)
if err != nil {
log.Fatal(err) // the network failed: no answer at all
}
defer res.Body.Close()
var body struct {
BatchID string
Messages []struct{ ID, Status, DeviceName string }
Error struct{ Code, Message string }
}
if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
log.Fatal(err)
}
if res.StatusCode >= 400 {
log.Fatalf("%d %s: %s", res.StatusCode, body.Error.Code, body.Error.Message)
}
fmt.Println(body.Messages[0].ID, body.Messages[0].Status, "on", body.Messages[0].DeviceName)
}Put your own number in to, with its country code, and go run .. Ours printed msg_20261111_s4uhcd8c queued on Pixel 8 (simulated), and your phone sends the text a moment later.
Two Go details matter here. client.Do returns an error only when the network fails; a 401 or a 500 is a normal response, so you check StatusCode yourself. And http.DefaultClient has no timeout at all, which is why we make our own client with one. Also notice the struct has no JSON tags: encoding/json matches field names without caring about case, so BatchID picks up batchId.
With a bad key it stopped with 401 unauthorized: That key or token is not valid. It may have been revoked. Every error has that shape: a code to test in code, a message for people.
A small typed client
For a real program you want types and one place that turns API errors into Go errors. Save this as sparetext.go in a new folder. Each sample after it is a main.go that sits beside it (it declares api too, so it can't share a folder with the first sample):
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"time"
)
const api = "https://sparetext.dev/api/v1"
var client = &http.Client{Timeout: 15 * time.Second}
type Message struct {
ID string `json:"id"`
Contact string `json:"contact"`
Text string `json:"text"`
Status string `json:"status"`
DeviceName string `json:"deviceName"`
Error string `json:"error,omitempty"`
}
type Batch struct {
BatchID string `json:"batchId"`
Messages []Message `json:"messages"`
EstimatedCompletionAt string `json:"estimatedCompletionAt"`
}
// APIError is every error the API sends: a code to test in code, a message for people.
type APIError struct {
Status int
Code string `json:"code"`
Message string `json:"message"`
RetryAfter time.Duration
}
func (e *APIError) Error() string { return fmt.Sprintf("%d %s: %s", e.Status, e.Code, e.Message) }
// call sends one request and decodes the answer into out, or returns an *APIError.
func call(ctx context.Context, method, path string, payload, out any, headers ...string) error {
var body []byte
if payload != nil {
var err error
if body, err = json.Marshal(payload); err != nil {
return err
}
}
req, err := http.NewRequestWithContext(ctx, method, api+path, bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("x-api-key", os.Getenv("SPARETEXT_API_KEY"))
req.Header.Set("content-type", "application/json")
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode >= 400 {
var e struct{ Error APIError }
json.NewDecoder(res.Body).Decode(&e)
e.Error.Status = res.StatusCode
if s, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil {
e.Error.RetryAfter = time.Duration(s) * time.Second
}
return &e.Error
}
if out == nil {
return nil
}
return json.NewDecoder(res.Body).Decode(out)
}Wait for delivery with a context deadline
queued means the text is waiting for your phone. It then moves to dispatched (the phone has it), sent, and delivered if your carrier sends delivery reports. A text that goes wrong ends at failed, with the reason in error. A context gives the wait a hard deadline, and it cancels a request that's still in flight when time runs out:
package main
import (
"context"
"fmt"
"log"
"time"
)
func main() {
ctx := context.Background()
var sent Batch
err := call(ctx, "POST", "/messages", map[string]string{
"to": "+12025550167",
"text": "Your order #1042 is out for delivery.",
}, &sent)
if err != nil {
log.Fatal(err)
}
fmt.Println(sent.Messages[0].ID, sent.Messages[0].Status)
final, err := waitForDelivery(ctx, sent.Messages[0].ID, 2*time.Minute)
if err != nil {
log.Fatal(err)
}
fmt.Println(final.Status, final.Error)
}
func waitForDelivery(ctx context.Context, id string, timeout time.Duration) (Message, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
for {
var got struct{ Message Message }
if err := call(ctx, "GET", "/messages/"+id, nil, &got); err != nil {
return got.Message, err
}
switch got.Message.Status {
case "delivered", "failed", "canceled":
return got.Message, nil
}
select {
case <-ctx.Done():
return got.Message, nil // gave up waiting: hand back what we have
case <-time.After(3 * time.Second):
}
}
}Run it with go run main.go sparetext.go. Against the simulated phone it printed queued, then delivered about four seconds later. A real phone on a real network takes longer, and some carriers never send a delivery report at all, so a text can rest at sent. That's what the deadline is for.
Retry without texting someone twice
Here's the thing about retries and SMS. If a request times out, you don't know whether the text was queued. Retry blindly and your customer gets the same text twice. The fix is an Idempotency-Key header: any unique string. Send the same key again and Sparetext hands back the first answer instead of queuing a second text, for 24 hours.
package main
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"time"
)
// sendText retries a timeout or a 429 without ever texting someone twice.
func sendText(ctx context.Context, payload any) (Batch, error) {
b := make([]byte, 16)
rand.Read(b)
key := hex.EncodeToString(b) // the same key on every try, so a retry can't send twice
var out Batch
for attempt := 1; ; attempt++ {
err := call(ctx, "POST", "/messages", payload, &out, "Idempotency-Key", key)
if err == nil || attempt == 4 {
return out, err
}
wait := time.Duration(attempt) * time.Second // timeout or network error
var apiErr *APIError
if errors.As(err, &apiErr) {
if apiErr.Status != 429 || apiErr.RetryAfter == 0 {
return out, err // a bad number or a daily key limit won't fix itself
}
wait = apiErr.RetryAfter
}
select {
case <-ctx.Done():
return out, ctx.Err()
case <-time.After(wait):
}
}
}We checked both halves. The same key sent twice came back with the same message id, and only one text was queued. The same key with different words was refused with 422 idempotency_mismatch.
An account can make 15 send requests every 5 seconds; past that you get 429 rate_limited with Retry-After in seconds. We sent 30 texts in a row through sendText, and all 30 went through in 5.8 seconds, waiting whenever the API asked it to. One 429 has no Retry-After on purpose, key_daily_limit, and the function returns that error straight away instead of retrying until midnight.
Text a list from a CSV
package main
import (
"context"
"encoding/csv"
"fmt"
"log"
"os"
)
func main() {
f, err := os.Open("bookings.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
if err != nil {
log.Fatal(err)
}
type text struct {
To string `json:"to"`
Text string `json:"text"`
}
var messages []text
for _, r := range rows[1:] { // name,phone,time
messages = append(messages, text{r[1], fmt.Sprintf("Hi %s, see you tomorrow at %s. Reply YES to confirm.", r[0], r[2])})
}
for start := 0; start < len(messages); start += 100 {
end := min(start+100, len(messages))
batch, err := sendText(context.Background(), map[string]any{"messages": messages[start:end]})
if err != nil {
log.Fatal(err)
}
fmt.Println(batch.BatchID, len(batch.Messages), "queued, last one out about", batch.EstimatedCompletionAt)
}
}Run it with go run main.go sparetext.go safe.go. Our test file had a quoted name with a comma in it, which encoding/csv handled, and the three made-up guests answered YES a few seconds later. estimatedCompletionAt tells you when the last text of a long list should leave the phone.
Get replies with a webhook
Sparetext can post each text your phone receives to your server. Anyone who finds the URL can post to it too, so the handler checks the X-Sparetext-Signature header first: t=1793438045,v1=9c2f…, a timestamp, then an HMAC-SHA256 of the timestamp, a dot and the raw body, keyed with the webhook's secret.
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"log"
"math"
"net/http"
"os"
"regexp"
"strconv"
"time"
)
var (
secret = []byte(os.Getenv("SPARETEXT_WEBHOOK_SECRET"))
stamp = regexp.MustCompile(`(?:^|,)t=(\d+)`)
sigs = regexp.MustCompile(`v1=([0-9a-f]{64})`)
)
func fromSparetext(raw []byte, header string) bool {
m := stamp.FindStringSubmatch(header)
if m == nil {
return false
}
t, _ := strconv.ParseInt(m[1], 10, 64)
if math.Abs(float64(time.Now().Unix()-t)) > 300 {
return false // more than five minutes off: maybe a replayed request
}
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(m[1] + "."))
mac.Write(raw)
want := []byte(hex.EncodeToString(mac.Sum(nil)))
for _, s := range sigs.FindAllStringSubmatch(header, -1) {
if hmac.Equal(want, []byte(s[1])) {
return true
}
}
return false
}
func main() {
http.HandleFunc("POST /hooks/sparetext", func(w http.ResponseWriter, r *http.Request) {
raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // the bytes exactly as they arrived
if err != nil || !fromSparetext(raw, r.Header.Get("X-Sparetext-Signature")) {
w.WriteHeader(http.StatusUnauthorized)
return
}
var event struct {
Type string
Data struct {
Message struct{ Contact, Text string }
}
}
json.Unmarshal(raw, &event)
if event.Type == "message.received" {
log.Println(event.Data.Message.Contact, "said:", event.Data.Message.Text)
}
w.WriteHeader(http.StatusOK)
})
log.Fatal(http.ListenAndServe(":3000", nil))
}Read the body once, as bytes, and check those exact bytes before you decode anything. hmac.Equal compares in constant time, so nobody can guess a signature one character at a time. The loop accepts either v1= value because for a day after you rotate the secret there are two.
We added the handler on the Webhooks page with Text received ticked and texted the simulated phone. The real signed delivery was logged as +12025550173 said: YES; a POST without a signature got a 401, and a GET got a 405 from the method pattern. The webhook guide has every event and how retries work.
What this can't do
A phone is the right tool for texts to people who know you: reminders, confirmations, alerts to your team, replies to customers. For login codes there's a ready-made verify endpoint, so you don't store codes yourself.
It's the wrong tool for marketing to a list that didn't ask. Carriers filter business texts sent by software even from a personal number, and the 10DLC post explains why. An iPhone can't send silently in the background the way Android can, and only Android phones get carrier delivery reports. On plans, Free covers 300 texts a month and Pro 10,000 on up to 5 phones (pricing).
The same steps exist for Node.js, Python, PHP, Ruby and Java. For a quick alert from a server, curl in a bash script is enough.
Try it with your own number
Make a key on the API keys page, pair your phone, and go run . the first sample with your own number in to. When your pocket buzzes, move sparetext.go and sendText into your project.
gogolangsend smssms apinet/httpwebhookstutorial
Try it with the phone you have
Free for 1 phone and 300 texts a month. Pair it in about two minutes.
Responses
Sign in or create an account to respond.