-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnotifier.go
More file actions
113 lines (88 loc) · 2.41 KB
/
notifier.go
File metadata and controls
113 lines (88 loc) · 2.41 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package notifier
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
const (
// HTTPDefaultHost default of webserver
HTTPDefaultHost = "https://version.similarweb.engineering"
// HTTRequestTimeout defins the http timeout
HTTRequestTimeout = 3
)
// RequestSetting request setting
type RequestSetting struct {
Host string
}
// UpdaterParams are get parameters for notifier HTTP request.
type UpdaterParams struct {
// Name the application
Application string
// Name of the Organization
Organization string
// Name of the component
Component string
// Application/component versions
Version string
}
// Response is the response from notifier webserver.
type Response struct {
CurrentVersion string `json:"current_version"`
CurrentDownloadURL string `json:"current_download_url"`
Outdated bool `json:"outdated"`
Notifications []*Notification `json:"notifications"`
}
// Notification is a Notification message from notifier webserver.
type Notification struct {
Date int `json:"date"`
Message string `json:"message"`
}
// Get creates http call fo getting the latest version of the application
func Get(p *UpdaterParams, requestSetting RequestSetting) (*Response, error) {
client := &http.Client{
Timeout: HTTRequestTimeout * time.Second,
}
data := url.Values{}
data.Set("component", p.Component)
data.Set("version", p.Version)
host := HTTPDefaultHost
if requestSetting.Host != "" {
host = requestSetting.Host
}
versionAPIURL := fmt.Sprintf("%s/api/v1/latest-version/%s/%s", host, p.Organization, p.Application)
req, err := http.NewRequest("GET", versionAPIURL, nil)
if err != nil {
return nil, err
}
// Add the queryparams to versionAPIURL
req.URL.RawQuery = data.Encode()
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var r io.Reader = resp.Body
var result Response
if err := json.NewDecoder(r).Decode(&result); err != nil {
return nil, err
}
return &result, nil
}
// GetInterval called to get the the version of the application during the inteval time.
func GetInterval(ctx context.Context, p *UpdaterParams, interval time.Duration, update func(*Response, error), requestSetting RequestSetting) {
go func() {
for {
select {
case <-time.After(interval):
resp, err := Get(p, requestSetting)
update(resp, err)
case <-ctx.Done():
return
}
}
}()
}