feat: notification provider gotify
This commit is contained in:
87
pkg/notificationProvider/gotify/gotify.go
Normal file
87
pkg/notificationProvider/gotify/gotify.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package notificationProviderGotify
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
type NotificationProviderImplGotifyConfig struct {
|
||||
Url string `yaml:"url"`
|
||||
Token string `yaml:"token"`
|
||||
Priority int `yaml:"priority"`
|
||||
}
|
||||
|
||||
type NotificationProviderImplGotify struct {
|
||||
Url url.URL
|
||||
Token string
|
||||
Priority int
|
||||
HTTPClient *http.Client
|
||||
}
|
||||
|
||||
func New(config NotificationProviderImplGotifyConfig) (*NotificationProviderImplGotify, error) {
|
||||
if config.Url == "" {
|
||||
return nil, fmt.Errorf("url is required")
|
||||
}
|
||||
|
||||
url, err := url.Parse(config.Url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if config.Token == "" {
|
||||
return nil, fmt.Errorf("token is required")
|
||||
}
|
||||
|
||||
if config.Priority < 0 || config.Priority > 4 {
|
||||
return nil, fmt.Errorf("priority must be between 0 and 4")
|
||||
}
|
||||
|
||||
return &NotificationProviderImplGotify{
|
||||
*url,
|
||||
config.Token,
|
||||
config.Priority,
|
||||
&http.Client{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *NotificationProviderImplGotify) SendNotification(title string, message string) error {
|
||||
type GotifyMessage struct {
|
||||
Message string `json:"message"`
|
||||
Title string `json:"title"`
|
||||
Priority int `json:"priority"`
|
||||
}
|
||||
|
||||
messageJson, err := json.Marshal(GotifyMessage{
|
||||
message,
|
||||
title,
|
||||
p.Priority,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
messageUrl := p.Url
|
||||
messageUrl.JoinPath("message")
|
||||
messageUrl.Query().Add("token", p.Token)
|
||||
|
||||
req, err := http.NewRequest("POST", messageUrl.String(), bytes.NewBuffer(messageJson))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
res, err := p.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if res.StatusCode != 200 {
|
||||
return fmt.Errorf("unexpected status code: %d", res.StatusCode)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user