Go SDK for message push service, supporting multiple message types including SMS, email, WeChat Work, DingTalk, and more.
- ✅ Complete API support (single send, batch send, status query)
- ✅ HMAC-SHA256 signature authentication
- ✅ Context support (timeout, cancellation)
- ✅ Comprehensive error handling
- ✅ Thread-safe
- ✅ Unit test coverage
go get github.com/mliev-sdk/push-gopackage main
import (
"context"
"fmt"
"log"
"github.com/mliev-sdk/push-go"
)
func main() {
// Create client
client := mlievpush.NewClient(
"https://your-domain.com", // Base URL
"your_app_id", // App ID
"your_app_secret", // App secret
)
// Send SMS
ctx := context.Background()
data, err := client.SendMessage(ctx, &mlievpush.SendMessageRequest{
ChannelID: 1,
SignatureName: "【Your Signature】",
Receiver: "13800138000",
TemplateParams: map[string]interface{}{
"code": "123456",
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Sent successfully, Task ID: %s\n", data.TaskID)
}// Basic creation
client := mlievpush.NewClient(baseURL, appID, appSecret)
// Using options
client := mlievpush.NewClient(
baseURL,
appID,
appSecret,
mlievpush.WithTimeout(15*time.Second), // Set timeout
mlievpush.WithHTTPClient(customHTTPClient), // Custom HTTP client
)Send a message to a single recipient.
req := &mlievpush.SendMessageRequest{
ChannelID: 1, // Channel ID (required)
SignatureName: "【Your Signature】", // Signature name (required)
Receiver: "13800138000", // Recipient (required)
TemplateParams: map[string]interface{}{ // Template parameters (optional)
"code": "123456",
"expire_time": "5",
},
ScheduledAt: "2025-11-26T10:00:00Z", // Scheduled sending (optional)
}
data, err := client.SendMessage(ctx, req)
if err != nil {
// Handle error
}
fmt.Printf("Task ID: %s\n", data.TaskID)
fmt.Printf("Status: %s\n", data.Status)Send messages to multiple recipients (using the same template parameters).
req := &mlievpush.SendBatchRequest{
ChannelID: 1,
SignatureName: "【Your Signature】",
Receivers: []string{
"13800138000",
"13800138001",
"13800138002",
},
TemplateParams: map[string]interface{}{
"content": "System maintenance notification",
"duration": "2 hours",
},
}
data, err := client.SendBatch(ctx, req)
if err != nil {
// Handle error
}
fmt.Printf("Batch ID: %s\n", data.BatchID)
fmt.Printf("Success: %d, Failed: %d\n", data.SuccessCount, data.FailedCount)Query sending status by task ID.
taskID := "550e8400-e29b-41d4-a716-446655440000"
data, err := client.QueryTask(ctx, taskID)
if err != nil {
// Handle error
}
fmt.Printf("Status: %s\n", data.Status)
fmt.Printf("Message Type: %s\n", data.MessageType)
fmt.Printf("Recipient: %s\n", data.Receiver)
fmt.Printf("Content: %s\n", data.Content)The SDK provides comprehensive error handling mechanisms.
data, err := client.SendMessage(ctx, req)
if err != nil {
if mlievpush.IsAPIError(err) {
// API business error
apiErr := err.(*mlievpush.APIError)
fmt.Printf("Error Code: %d\n", apiErr.Code)
fmt.Printf("Error Message: %s\n", apiErr.Message)
} else {
// Network error or other errors
fmt.Printf("Request failed: %v\n", err)
}
}if mlievpush.IsAPIError(err) {
apiErr := err.(*mlievpush.APIError)
switch apiErr.Code {
case mlievpush.ErrCodeInvalidSignature:
// Signature verification failed
fmt.Println("Please check if app_secret is correct")
case mlievpush.ErrCodeChannelNotFound:
// Channel not found
fmt.Println("Please check if channel_id is correct")
case mlievpush.ErrCodeRateLimitExceeded:
// Rate limit exceeded
fmt.Println("Please reduce request frequency")
default:
// Other errors
fmt.Printf("%s\n", mlievpush.GetErrorMessage(apiErr.Code))
}
}| Error Code | Constant | Description |
|---|---|---|
| 20003 | ErrCodeInvalidSignature |
Signature verification failed |
| 20004 | ErrCodeInvalidTimestamp |
Invalid timestamp |
| 30001 | ErrCodeRateLimitExceeded |
Rate limit exceeded |
| 30003 | ErrCodeChannelNotFound |
Channel not found |
| 30007 | ErrCodeTaskNotFound |
Task not found |
For a complete list of error codes, please refer to API Documentation.
All API methods support Context for timeout control and request cancellation.
// Create a context with 5-second timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req := &mlievpush.SendMessageRequest{
ChannelID: 1,
SignatureName: "【Your Signature】",
Receiver: "13800138000",
}
data, err := client.SendMessage(ctx, req)
if err != nil {
if ctx.Err() == context.DeadlineExceeded {
fmt.Println("Request timeout")
}
}ctx, cancel := context.WithCancel(context.Background())
// Can cancel request in another goroutine
go func() {
time.Sleep(1 * time.Second)
cancel()
}()
req := &mlievpush.SendMessageRequest{
ChannelID: 1,
SignatureName: "【Your Signature】",
Receiver: "13800138000",
}
data, err := client.SendMessage(ctx, req)
if err != nil {
if ctx.Err() == context.Canceled {
fmt.Println("Request canceled")
}
}mlievpush.TaskStatusPending // "pending" - Pending
mlievpush.TaskStatusProcessing // "processing" - Processing
mlievpush.TaskStatusSuccess // "success" - Success
mlievpush.TaskStatusFailed // "failed" - Failedmlievpush.MessageTypeSMS // "sms" - SMS
mlievpush.MessageTypeEmail // "email" - Email
mlievpush.MessageTypeWechatWork // "wechat_work" - WeChat Work
mlievpush.MessageTypeDingtalk // "dingtalk" - DingTalk
mlievpush.MessageTypeWebhook // "webhook" - Webhook
mlievpush.MessageTypePush // "push" - Push notificationmlievpush.CallbackStatusDelivered // "delivered" - Delivered
mlievpush.CallbackStatusFailed // "failed" - Failed
mlievpush.CallbackStatusRejected // "rejected" - RejectedCheck examples/main.go for more usage examples:
- Send single message
- Send batch messages
- Query task status
- Error handling
- Context timeout control
Run the examples:
cd examples
go run main.goRun unit tests:
go test -vRun tests with coverage:
go test -v -cover- Reuse client instance:
Clientis thread-safe and can be shared across multiple goroutines - Use Context: Set reasonable timeout for each request to avoid long blocking
- Error handling: Differentiate between API errors and network errors for targeted handling
- Logging: Save returned
task_idfor easier troubleshooting - Batch limits: Recommend not exceeding 500 items per batch send
- Go 1.21+
- github.com/google/uuid v1.5.0
MIT License
For questions or suggestions, please submit an Issue.