first commit
This commit is contained in:
81
plain/nad-notifier.go
Normal file
81
plain/nad-notifier.go
Normal 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
|
||||
}
|
Reference in New Issue
Block a user