Go语言以高并发与简洁著称,常用于监控采集、网关与中间件。用Go接入互亿无线预警通知接口,可在守护进程、监控agent、定时任务中发告警。本文基于标准库net/http与net/url。 Go接入的接口与参数 短信接口 https://ap…
Go语言以高并发与简洁著称,常用于监控采集、网关与中间件。用Go接入互亿无线预警通知接口,可在守护进程、监控agent、定时任务中发告警。本文基于标准库net/http与net/url。
Go接入的接口与参数
短信接口 https://api.ihuyi.com/sms/Submit.json ,语音接口 https://api.ihuyi.com/voice/vm 。表单参数account、password、mobile、content,HTTPS POST。
- account=APIID,password=APIKEY;
- mobile=接收手机号;
- content=通知内容;
- 返回JSON code=2为成功。
Go发送告警代码示例
下面的函数构造表单请求并解析响应:
package main
import (
"net/http"
"net/url"
"strings"
"time"
)
func SendSms(mobile, content string) (string, error) {
form := url.Values{}
form.Set("account", "APIID")
form.Set("password", "APIKEY")
form.Set("mobile", mobile)
form.Set("content", content)
client := &http.Client{Timeout: 8 * time.Second}
resp, err := client.Post(
"https://api.ihuyi.com/sms/Submit.json",
"application/x-www-form-urlencoded",
strings.NewReader(form.Encode()))
if err != nil {
return "", err
}
defer resp.Body.Close()
b := make([]byte, 4096)
n, _ := resp.Body.Read(b)
return string(b[:n]), nil // code=2为成功
}
form.Encode自动对中文URL编码。
Go接入注意事项
- http.Client必须设置Timeout,避免goroutine泄漏;
- resp.Body及时Close并复用Client;
- 密钥通过环境变量注入,不写进源码;
- 并发告警复用同一Client控制连接数。
带超时与错误处理的完整示例
Go的net/http标准库即可完成HTTPS POST,下面这个版本设置了超时、错误判断与返回码解析:
package main
import (
"net/http"
"net/url"
"strings"
"time"
"encoding/json"
"fmt"
)
func sendSms(mobile, content string) error {
apiID := "你的APIID"
apiKey := "你的APIKEY"
form := url.Values{}
form.Set("account", apiID)
form.Set("password", apiKey)
form.Set("mobile", mobile)
form.Set("content", content)
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.PostForm(
"https://api.ihuyi.com/sms/Submit.json",
form,
)
if err != nil {
return err
}
defer resp.Body.Close()
var result struct {
Code int `json:"code"`
Msg string `json:"msg"`
Smsid string `json:"smsid"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return err
}
fmt.Println(result.Code, result.Msg, result.Smsid)
return nil // code=2表示提交成功
}
依赖与运行说明
示例只用Go标准库,go run main.go即可运行。生产环境建议把apiID、apiKey从环境变量读取,用os.Getenv获取。
常见报错排查
- context deadline exceeded:说明超时,检查网络出口或调大Timeout;
- 返回code非2:打印result.Msg定位;
- json解析失败:确认响应体是合法JSON,不要在出错时把HTML错误页当JSON解析;
- 语音通道:把URL换成 https://api.ihuyi.com/voice/vm 。
Go服务封装告警函数即可通知。前往注册免费试用获取密钥。