1
0

first commit

This commit is contained in:
2025-01-20 19:30:00 +08:00
commit 8cb9a49f60
3 changed files with 91 additions and 0 deletions

3
go.mod Normal file
View File

@@ -0,0 +1,3 @@
module nad-plain-notifier-golang-sdk
go 1.23

81
plain/nad-notifier.go Normal file
View File

@@ -0,0 +1,81 @@
package plain
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
)
type NadNotifier struct {
Address string // http://host:port/path
SkipSSLVerify bool
AccessToken string
}
// Notify 方法将传入的 Notify 信息序列化为 JSON
// 然后通过 HTTP POST 请求发送到 NadNotifier.Address 指定的地址。
// 如果启用 SkipSSLVerify将跳过对服务端证书的校验仅在测试或内部环境使用
// 若需要授权令牌AccessToken则会在请求头中设置相应的 Bearer Token。
func (receiver NadNotifier) Notify(notify *Notify) error {
// 将 Notify 序列化为 JSON
bodyData, err := json.Marshal(notify)
if err != nil {
return fmt.Errorf("json marshal error: %v", err)
}
// 创建一个可选的自定义 Transport用于跳过 SSL 证书验证
transport := http.DefaultTransport.(*http.Transport).Clone()
if receiver.SkipSSLVerify {
// 不建议在生产环境中使用此选项
transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
}
// 使用自定义 Transport 创建 http.Client
client := &http.Client{Transport: transport}
// 构造 HTTP 请求
req, err := http.NewRequest(http.MethodPost, receiver.Address, bytes.NewReader(bodyData))
if err != nil {
return fmt.Errorf("create request error: %v", err)
}
// 设置请求头
req.Header.Set("Content-Type", "application/json")
req.Header.Set("access_token", receiver.AccessToken)
// 发送请求
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("http post error: %v", err)
}
fmt.Println("status code:", resp.StatusCode)
fmt.Println("status message:", resp.Status)
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
_ = fmt.Errorf("close body error: %v", err)
}
}(resp.Body)
// 可选:读取响应体进行日志或错误判断
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("read response error: %v", err)
} else {
fmt.Println("response body:", string(respBody))
}
// 根据返回的状态码做相应处理,这里简单返回非 2xx 状态码为错误
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("unexpected status code: %d, response: %s", resp.StatusCode, string(respBody))
}
// 如果需要,你可以在这里解析服务端返回的 JSON 或作其他逻辑处理
return nil
}

7
plain/notify.go Normal file
View File

@@ -0,0 +1,7 @@
package plain
type Notify struct {
Notify string `json:"notify"`
Title string `json:"title" `
Device string `json:"device"`
}