1.4.5.2
This commit is contained in:
89
EdgeAPI/internal/senders/smssenders/sender_web_hook.go
Normal file
89
EdgeAPI/internal/senders/smssenders/sender_web_hook.go
Normal file
@@ -0,0 +1,89 @@
|
||||
// Copyright 2023 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
|
||||
//go:build plus
|
||||
|
||||
package smssenders
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
teaconst "github.com/TeaOSLab/EdgeAPI/internal/const"
|
||||
"github.com/TeaOSLab/EdgeAPI/internal/utils"
|
||||
"github.com/TeaOSLab/EdgeCommon/pkg/userconfigs"
|
||||
"github.com/iwind/TeaGo/types"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type WebHookSender struct {
|
||||
params *userconfigs.SMSSenderWebHookParams
|
||||
}
|
||||
|
||||
func NewWebHookSender() *WebHookSender {
|
||||
return &WebHookSender{}
|
||||
}
|
||||
|
||||
func (this *WebHookSender) Init(params any) error {
|
||||
if params == nil {
|
||||
return errors.New("'params' should not be nil")
|
||||
}
|
||||
var ok bool
|
||||
this.params, ok = params.(*userconfigs.SMSSenderWebHookParams)
|
||||
if !ok {
|
||||
return errors.New("invalid params type")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Send 发送短信
|
||||
func (this *WebHookSender) Send(mobile string, body string, code string) (result string, isOk bool, err error) {
|
||||
var encodedQuery = (&url.Values{
|
||||
"mobile": []string{mobile},
|
||||
"body": []string{body},
|
||||
"code": []string{code},
|
||||
}).Encode()
|
||||
var webHookURL = this.params.URL
|
||||
var reader io.Reader
|
||||
if this.params.Method == "POST" {
|
||||
reader = strings.NewReader(encodedQuery)
|
||||
} else {
|
||||
if strings.Contains(webHookURL, "?") {
|
||||
webHookURL += "&" + encodedQuery
|
||||
} else {
|
||||
webHookURL += "?" + encodedQuery
|
||||
}
|
||||
}
|
||||
req, err := http.NewRequest(this.params.Method, webHookURL, reader)
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("create request failed: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("User-Agent", teaconst.ProductName+"/"+teaconst.Version)
|
||||
if this.params.Method == "POST" {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
|
||||
resp, err := utils.SharedHttpClient(10 * time.Second).Do(req)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if resp == nil || resp.Body == nil {
|
||||
return "", false, errors.New("invalid response")
|
||||
}
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
|
||||
respData, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "StatusCode: " + types.String(resp.StatusCode) + ": " + string(respData), false, nil
|
||||
}
|
||||
|
||||
return string(respData), true, nil
|
||||
}
|
||||
Reference in New Issue
Block a user