Hey there, fellow Go enthusiast! Ready to add some SMS magic to your Go application? You're in the right place. We're going to walk through integrating the TextMagic SMS API using the textmagic-rest-go-v2
package. It's easier than you might think, and by the end of this guide, you'll be sending SMS messages like a pro.
Before we dive in, make sure you've got:
Let's get our hands dirty:
mkdir textmagic-sms-project cd textmagic-sms-project go mod init textmagic-sms-project
go get github.com/textmagic/textmagic-rest-go-v2/v2
Now, let's write some Go code:
package main import ( "context" "fmt" "github.com/textmagic/textmagic-rest-go-v2/v2" ) func main() { client := textmagic.NewAPIClient(textmagic.NewConfiguration()) auth := context.WithValue(context.Background(), textmagic.ContextAPIKey, textmagic.APIKey{ Key: "YOUR_API_KEY", }) // We'll use this client and auth context for our API calls }
Replace "YOUR_API_KEY"
with your actual TextMagic API key. Keep it secret, keep it safe!
Let's send our first SMS:
func main() { // ... (previous client and auth setup) message := *textmagic.NewSendMessageInputObject() message.Text = "Hello from Go!" message.Phones = []string{"+1234567890"} result, _, err := client.TextMagicApi.SendMessage(auth).SendMessageInputObject(message).Execute() if err != nil { fmt.Printf("Error when calling TextMagicApi.SendMessage: %v\n", err) return } fmt.Printf("Message sent successfully! ID: %v\n", result.Id) }
Boom! You've just sent your first SMS. How cool is that?
Want to send to multiple recipients? Easy peasy:
message.Phones = []string{"+1234567890", "+9876543210"}
Sending messages in the future? We've got you covered:
message.SendingTime = 1640995200 // Unix timestamp for future date
Curious about your message's journey?
status, _, err := client.TextMagicApi.GetMessageStatus(auth, 1234).Execute() // Replace 1234 with actual message ID if err != nil { fmt.Printf("Error when calling TextMagicApi.GetMessageStatus: %v\n", err) return } fmt.Printf("Message status: %v\n", status.Status)
Always check for errors after API calls. The TextMagic API has rate limits, so consider implementing retries with exponential backoff for production use.
if err != nil { // Log the error // Implement retry logic if appropriate return }
Here's a quick unit test example:
func TestSendSMS(t *testing.T) { // Mock the TextMagic client // Test your SendSMS function // Assert expected outcomes }
For integration testing, consider using a sandbox environment if TextMagic provides one.
And there you have it! You're now equipped to integrate SMS functionality into your Go applications using the TextMagic API. Remember to check out the official TextMagic documentation for more advanced features and best practices.
Now go forth and send those messages! Your Go app just got a whole lot more communicative. Happy coding!