Send SMS with Go

To send an SMS from Go, POST JSON to the curl-sms API with the standard library's net/http. No third-party module needed.

Example

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

type SMS struct {
	ID     string `json:"id"`
	Status string `json:"status"`
}

func sendSMS(receiver, body string) (*SMS, error) {
	payload, err := json.Marshal(map[string]string{"receiver": receiver, "body": body})
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest(http.MethodPost, "https://curl-sms.com/api/sms/send", bytes.NewReader(payload))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("CURLSMS_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusAccepted {
		var e struct {
			Error struct {
				Code    string `json:"code"`
				Message string `json:"message"`
			} `json:"error"`
		}
		_ = json.NewDecoder(resp.Body).Decode(&e)
		return nil, fmt.Errorf("%s: %s", e.Error.Code, e.Error.Message)
	}
	var sms SMS
	return &sms, json.NewDecoder(resp.Body).Decode(&sms)
}

func main() {
	sms, err := sendSMS("+4915123456789", "Hello from Go")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(sms.ID, sms.Status)
}

Run it with CURLSMS_KEY=cs_test_… go run .. A test key validates everything but sends nothing and costs nothing.

What you get back

202 Accepted with id, status (queued, later sent and delivered), segments, encoding and price. Errors carry a stable code such as insufficient_balance or ambiguous_receiver, listed under error codes.

Tips

  • Idempotency: set req.Header.Set("Idempotency-Key", jobID). Retrying after a timeout with the same key and body never sends twice.
  • Context: use http.NewRequestWithContext to cancel the call together with your request or job.
  • Webhooks: the docs contain a ready Verify function for the signature in Go.
  • Alerts from your services: see server and monitoring alerts by SMS.