/
handlers.go
187 lines (149 loc) · 5.13 KB
/
handlers.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package dnclient
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"path"
"strconv"
"strings"
"time"
"github.com/Go-Lift-TV/discordnotifier-client/bindata"
"github.com/Go-Lift-TV/discordnotifier-client/ui"
"golift.io/version"
)
// allowedIPs determines who can set x-forwarded-for.
type allowedIPs []*net.IPNet
// internalHandlers initializes "special" internal API paths.
func (c *Client) internalHandlers() {
// GET /api/status (w/o key)
c.router.Handle(path.Join("/", c.Config.URLBase, "api", "status"),
http.HandlerFunc(c.statusResponse)).Methods("GET", "HEAD")
// PUT /api/info (w/ key)
c.handleAPIpath("", "info", c.updateInfo, "PUT")
// PUT /api/info/alert (w/ key)
c.handleAPIpath("", "info/alert", c.updateInfoAlert, "PUT")
// GET /api/version (w/ key)
c.handleAPIpath("", "version", c.versionResponse, "GET", "HEAD")
// Initialize internal-only paths.
c.router.Handle("/favicon.ico", http.HandlerFunc(c.favIcon)) // built-in icon.
c.router.Handle("/", http.HandlerFunc(c.slash)) // "hi" page on /
c.router.PathPrefix("/").Handler(http.HandlerFunc(c.notFound)) // 404 everything
}
func (c *Client) respond(w http.ResponseWriter, stat int, msg interface{}) {
statusTxt := strconv.Itoa(stat) + ": " + http.StatusText(stat)
if m, ok := msg.(error); ok {
c.Errorf("Status: %s, Message: %v", statusTxt, m)
msg = m.Error()
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(stat)
b, _ := json.Marshal(map[string]interface{}{"status": statusTxt, "message": msg})
_, _ = w.Write(b)
_, _ = w.Write([]byte("\n")) // curl likes new lines.
}
func (c *Client) updateInfoAny(r *http.Request) (int, string, interface{}) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return http.StatusInternalServerError, "", fmt.Errorf("reading PUT body: %w", err)
}
c.Print("New Info from DiscordNotifier.com:", string(body))
if _, ok := c.menu["dninfo"]; !ok {
return http.StatusAccepted, "", "menu UI is not active"
}
c.info = string(body) // not lockd, prob should be.
c.menu["dninfo"].Show()
return http.StatusOK, string(body), "info updated and menu shown"
}
func (c *Client) updateInfo(r *http.Request) (int, interface{}) {
code, _, err := c.updateInfoAny(r)
return code, err
}
// updateInfoAlert is the same as updateInfo except it adds a popup window.
func (c *Client) updateInfoAlert(r *http.Request) (int, interface{}) {
code, body, err := c.updateInfoAny(r)
if body == "" {
return code, err
}
c.alert.Lock()
defer c.alert.Unlock()
if c.alert.active {
return http.StatusLocked, "previous alert not acknowledged"
}
c.alert.active = true
go func() {
_, _ = ui.Warning(Title+" Alert", body)
c.alert.Lock()
defer c.alert.Unlock()
c.alert.active = false
}()
return code, err
}
// versionResponse returns application run and build time data: /api/version.
func (c *Client) versionResponse(r *http.Request) (int, interface{}) {
return http.StatusOK, map[string]interface{}{
"version": version.Version,
"uptime": time.Since(version.Started).Round(time.Second).String(),
"uptime_seconds": time.Since(version.Started).Round(time.Second).Seconds(),
"build_date": version.BuildDate,
"branch": version.Branch,
"go_version": version.GoVersion,
"revision": version.Revision,
}
}
// notFound is the handler for paths that are not found: 404s.
func (c *Client) notFound(w http.ResponseWriter, r *http.Request) {
c.respond(w, http.StatusNotFound, "Check your request parameters and try again.")
}
// statusResponse is the handler for /api/status.
func (c *Client) statusResponse(w http.ResponseWriter, r *http.Request) {
c.respond(w, http.StatusOK, c.Flags.Name()+" alive!")
}
// slash is the handler for /.
func (c *Client) slash(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("<p>" + c.Flags.Name() + ": <strong>working</strong></p>\n"))
}
func (c *Client) favIcon(w http.ResponseWriter, r *http.Request) {
if b, err := bindata.Asset("files/favicon.ico"); err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else {
http.ServeContent(w, r, r.URL.Path, time.Now(), bytes.NewReader(b))
}
}
// fixForwardedFor sets the X-Forwarded-For header to the client IP
// under specific circumstances.
func (c *Client) fixForwardedFor(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := strings.Trim(r.RemoteAddr[:strings.LastIndex(r.RemoteAddr, ":")], "[]")
if x := r.Header.Get("X-Forwarded-For"); x == "" || !c.allow.contains(ip) {
r.Header.Set("X-Forwarded-For", ip)
} else if l := strings.LastIndexAny(x, ", "); l != -1 {
r.Header.Set("X-Forwarded-For", strings.Trim(x[l:len(x)-1], ", "))
}
next.ServeHTTP(w, r)
})
}
var _ = fmt.Stringer(allowedIPs(nil))
// String turns a list of allowedIPs into a printable masterpiece.
func (n allowedIPs) String() (s string) {
if len(n) < 1 {
return "(none)"
}
for i := range n {
if s != "" {
s += ", "
}
s += n[i].String()
}
return s
}
func (n allowedIPs) contains(ip string) bool {
for i := range n {
if n[i].Contains(net.ParseIP(ip)) {
return true
}
}
return false
}