-
Notifications
You must be signed in to change notification settings - Fork 69
/
notifer.go
82 lines (75 loc) · 1.81 KB
/
notifer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright (c) 2018-2022 Author dengsgo<dengsgo@yoytang.com> [https://github.com/dengsgo/fileboy]
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
package main
import (
"bytes"
"encoding/json"
"net/http"
"strings"
"time"
)
type postParams struct {
ProjectFolder string `json:"project_folder"`
File string `json:"file"`
Changed int64 `json:"changed"`
Ext string `json:"ext"`
Event string `json:"event"`
}
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,
}
}
func (n *NetNotifier) Put(cf *changedFile) {
if !n.CanPost {
logWarn("notifier call url ignore. ", n.CallUrl)
return
}
n.dispatch(&postParams{
ProjectFolder: projectFolder,
File: cf.Name,
Changed: cf.Changed,
Ext: cf.Ext,
Event: cf.Event,
})
}
func (n *NetNotifier) dispatch(params *postParams) {
b, err := json.Marshal(params)
if err != nil {
logError("json.Marshal n.params. ", err)
return
}
client := http.DefaultClient
client.Timeout = time.Second * 15
req, err := http.NewRequest("POST", n.CallUrl, bytes.NewBuffer(b))
if err != nil {
logError("http.NewRequest. ", err)
return
}
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
req.Header.Set("User-Agent", "FileBoy Net Notifier v1.17")
resp, err := client.Do(req)
if err != nil {
logError("notifier call failed. err:", err)
return
}
defer func() {
if resp != nil && resp.Body != nil {
_ = resp.Body.Close()
}
}()
if resp.StatusCode >= 300 {
// todo retry???
}
logInfo("notifier done .")
}