fileboy/notifer.go

80 lines
1.6 KiB
Go
Raw Normal View History

2019-01-02 11:07:52 +00:00
package main
import (
"bytes"
"encoding/json"
"net/http"
"strings"
2019-01-03 01:54:25 +00:00
"time"
2019-01-02 11:07:52 +00:00
)
type postParams struct {
ProjectFolder string `json:"project_folder"`
File string `json:"file"`
Changed int64 `json:"changed"`
Ext string `json:"ext"`
2019-12-04 03:50:11 +00:00
Event string `json:"event"`
2019-01-02 11:07:52 +00:00
}
type NetNotifier struct {
CallUrl string
CanPost bool
}
func newNetNotifier(callUrl string) *NetNotifier {
callPost := true
if strings.TrimSpace(callUrl) == "" {
callPost = false
}
return &NetNotifier{
CallUrl: callUrl,
CanPost: callPost,
}
}
2019-01-03 01:56:26 +00:00
func (n *NetNotifier) Put(cf *changedFile) {
2019-01-02 11:07:52 +00:00
if !n.CanPost {
2020-01-02 09:25:02 +00:00
logWarn("notifier call url ignore. ", n.CallUrl)
2019-01-02 11:07:52 +00:00
return
}
n.dispatch(&postParams{
ProjectFolder: projectFolder,
File: cf.Name,
Changed: cf.Changed,
Ext: cf.Ext,
2019-12-04 03:50:11 +00:00
Event: cf.Event,
2019-01-02 11:07:52 +00:00
})
}
func (n *NetNotifier) dispatch(params *postParams) {
b, err := json.Marshal(params)
if err != nil {
2020-01-02 09:25:02 +00:00
logError("json.Marshal n.params. ", err)
2019-01-02 11:07:52 +00:00
return
}
2019-01-03 01:54:25 +00:00
client := &http.Client{
Timeout: time.Second * 15,
}
2019-01-02 11:07:52 +00:00
req, err := http.NewRequest("POST", n.CallUrl, bytes.NewBuffer(b))
if err != nil {
2020-01-02 09:25:02 +00:00
logError("http.NewRequest. ", err)
2019-01-02 11:07:52 +00:00
return
}
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
2019-12-17 08:38:14 +00:00
req.Header.Set("User-Agent", "FileBoy Net Notifier v1.12")
2019-01-02 11:07:52 +00:00
resp, err := client.Do(req)
if err != nil {
2020-01-02 09:25:02 +00:00
logError("notifier call failed. err:", err)
return
}
defer func() {
if resp != nil && resp.Body != nil {
_ = resp.Body.Close()
}
}()
2019-01-02 11:07:52 +00:00
if resp.StatusCode >= 300 {
// todo retry???
}
2020-01-02 09:25:02 +00:00
logInfo("notifier done .")
2019-01-02 11:07:52 +00:00
}