Sending SMS in Go (Golang): API Library Integration
In the modern world, sending SMS messages remains a popular feature for user verification, notifications, and marketing campaigns. In Go (Golang), this is implemented easily and efficiently thanks to built-in tools for working with HTTP and JSON. In this article, we will look at how to write your own library for sending SMS via a REST API using Go. The example will be built on an abstract provider, but the code can be easily adapted to any service (Twilio, SMS.ru, Vonage, etc.).
Library Architecture
Our library will consist of the following components:
- An HTTP request client with support for timeouts and retries
- Structures for the request (number, text, sender) and response (status, message ID, error)
- An initialization function with an API key and base URL
- A
SendSMSmethod for sending a single message
Installation and Preparation
To work, you only need the Go standard library (net/http, encoding/json). No external dependencies are required. Create a file sms.go and import the package:
package smsclient
import ( "bytes" "encoding/json" "fmt" "net/http" "time")Data Structures
Let's define the types for the request and response:
// SMSRequest represents the request body to the APItype SMSRequest struct { To string `json:"to"` // Recipient number in international format Text string `json:"text"` // Message text Sender string `json:"sender"` // Sender name (alpha-name)}
// SMSResponse contains the sending resulttype SMSResponse struct { Success bool `json:"success"` MessageID string `json:"message_id,omitempty"` Error string `json:"error,omitempty"`}Client for Working with the API
Let's create a client structure with configuration:
// Client manages sending SMS via the APItype Client struct { apiKey string baseURL string httpClient *http.Client}
// NewClient creates a new client instancefunc NewClient(apiKey, baseURL string) *Client { return &Client{ apiKey: apiKey, baseURL: baseURL, httpClient: &http.Client{ Timeout: 10 * time.Second, }, }}SMS Sending Method
Let's implement the main logic — sending a POST request with a JSON body:
// SendSMS sends an SMS and returns the response from the APIfunc (c *Client) SendSMS(req SMSRequest) (*SMSResponse, error) { // 1. Serialize the request to JSON body, err := json.Marshal(req) if err != nil { return nil, fmt.Errorf("error marshaling request: %w", err) }
// 2. Create an HTTP request httpReq, err := http.NewRequest("POST", c.baseURL+"/sms/send", bytes.NewBuffer(body)) if err != nil { return nil, fmt.Errorf("error creating request: %w", err) }
// 3. Set headers httpReq.Header.Set("Content-Type", "application/json") httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
// 4. Execute the request resp, err := c.httpClient.Do(httpReq) if err != nil { return nil, fmt.Errorf("error executing request: %w", err) } defer resp.Body.Close()
// 5. Decode the response var smsResp SMSResponse if err := json.NewDecoder(resp.Body).Decode(&smsResp); err != nil { return nil, fmt.Errorf("error decoding response: %w", err) }
// 6. Check the HTTP status code if resp.StatusCode != http.StatusOK { return &smsResp, fmt.Errorf("API returned code %d: %s", resp.StatusCode, smsResp.Error) }
return &smsResp, nil}Usage Example
Now let's show how to use the library in real code:
package main
impo Also in library
Lottie Android for Kotlin: Complete Guide with Examples
ShareLink Swift: Complete Guide with Examples
Database Migrations in Java: Overview of Popular Tools
Mongoose Paginate for JavaScript (Node.js): Complete Guide with Examples
Authorization and Authentication in Kotlin: Ktor, JWT, and Spring Security