-
Notifications
You must be signed in to change notification settings - Fork 23
/
gotify.go
95 lines (77 loc) · 2.13 KB
/
gotify.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
83
84
85
86
87
88
89
90
91
92
93
94
95
package notifier
import (
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/mitchellh/mapstructure"
"github.com/sirupsen/logrus"
"github.com/skibish/ddns/misc"
)
// gotifyHook is a structure for Gotify notifications configuration
type gotifyHook struct {
AppURL string `mapstructure:"app_url"`
AppToken string `mapstructure:"app_token"`
Title string
c *http.Client
}
func newGotifyhook(cfg interface{}) (*gotifyHook, error) {
var hook gotifyHook
if err := mapstructure.Decode(cfg, &hook); err != nil {
return nil, err
}
if hook.Title == "" {
hook.Title = "DDNS"
}
if !isValidURL(hook.AppURL) {
return nil, errors.New("app_url is not a valid url")
}
hook.AppURL = strings.TrimSuffix(hook.AppURL, "/")
hook.c = &http.Client{}
return &hook, nil
}
func (hook *gotifyHook) send(msg string) error {
form := &url.Values{}
form.Add("title", hook.Title)
form.Add("message", msg)
url := fmt.Sprintf("%s/message?token=%s", hook.AppURL, hook.AppToken)
req, err := http.NewRequest(http.MethodGet, url, strings.NewReader(form.Encode()))
if err != nil {
return fmt.Errorf("failed to create a request: %w", err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := hook.c.Do(req)
if err != nil {
return fmt.Errorf("failed to do a request: %w", err)
}
defer res.Body.Close()
if !misc.Success(res.StatusCode) {
return fmt.Errorf("status code is not in a success range: %w", err)
}
return nil
}
// Fire fires hook
func (hook *gotifyHook) Fire(entry *logrus.Entry) error {
if err := hook.send(entry.Message); err != nil {
return fmt.Errorf("failed to send a message to app %w", err)
}
return nil
}
// Levels return array of levels
func (hook *gotifyHook) Levels() []logrus.Level {
return allowedLevels()
}
// Source: https://golangcode.com/how-to-check-if-a-string-is-a-url/
// isValidURL tests a string to determine if it is a well-structured url or not.
func isValidURL(toTest string) bool {
_, err := url.ParseRequestURI(toTest)
if err != nil {
return false
}
u, err := url.Parse(toTest)
if err != nil || u.Scheme == "" || u.Host == "" {
return false
}
return true
}