♻️ 通知支持自定义 request header

This commit is contained in:
naiba
2021-11-05 12:04:39 +08:00
parent d20fd7a9fe
commit 6636d77cfd
7 changed files with 60 additions and 17 deletions

View File

@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
@@ -29,6 +30,7 @@ type Notification struct {
URL string
RequestMethod int
RequestType int
RequestHeader string `gorm:"type:longtext" `
RequestBody string `gorm:"type:longtext" `
VerifySSL *bool
}
@@ -39,6 +41,16 @@ func (n *Notification) reqURL(message string) string {
})
}
func (n *Notification) reqMethod() string {
switch n.RequestMethod {
case NotificationRequestMethodGET:
return http.MethodGet
case NotificationRequestMethodPOST:
return http.MethodGet
}
return ""
}
func (n *Notification) reqBody(message string) (string, error) {
if n.RequestMethod == NotificationRequestMethodGET {
return "", nil
@@ -73,6 +85,20 @@ func (n *Notification) reqContentType() string {
return "application/json"
}
func (n *Notification) setRequestHeader(req *http.Request) error {
if n.RequestHeader == "" {
return nil
}
var m map[string]string
if err := json.Unmarshal([]byte(n.RequestHeader), &m); err != nil {
return err
}
for k, v := range m {
req.Header.Set(k, v)
}
return nil
}
func (n *Notification) Send(message string) error {
var verifySSL bool
@@ -86,24 +112,32 @@ func (n *Notification) Send(message string) error {
}
client := &http.Client{Transport: transCfg, Timeout: time.Minute * 10}
reqBody, err := n.reqBody(message)
var resp *http.Response
if err == nil {
if n.RequestMethod == NotificationRequestMethodGET {
resp, err = client.Get(n.reqURL(message))
} else {
resp, err = client.Post(n.reqURL(message), n.reqContentType(), strings.NewReader(reqBody))
}
if err != nil {
return err
}
if err == nil && (resp.StatusCode < 200 || resp.StatusCode > 299) {
err = fmt.Errorf("%d %s", resp.StatusCode, resp.Status)
req, err := http.NewRequest(n.reqMethod(), n.reqURL(message), strings.NewReader(reqBody))
if err != nil {
return err
}
return err
if err := n.setRequestHeader(req); err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("%d@%s %s", resp.StatusCode, resp.Status, string(body))
}
return nil
}
func replaceParamsInString(str string, message string, mod func(string) string) string {