-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch.go
246 lines (202 loc) · 7.27 KB
/
watch.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package watch
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/smtp"
"net/url"
"os"
"regexp"
"runtime/debug"
"strconv"
"strings"
"time"
"github.com/alecthomas/chroma/formatters/html"
"github.com/alecthomas/chroma/lexers"
"github.com/alecthomas/chroma/styles"
)
func WatchMw(app http.Handler, opts ...WatchHandlerOption) http.HandlerFunc {
wh := newWatchHandler(opts)
return func(w http.ResponseWriter, r *http.Request) {
defer wh.handleExceptions(w)
if path := r.URL.Path; strings.Contains(path, wh.debugPath) {
sourceCodeHandler(w, r)
return
}
nw := &customResponseWriter{ResponseWriter: w}
app.ServeHTTP(nw, r)
// Copy contents from writer to original writer
nw.flush()
}
}
func (wh *watchHandler) handleExceptions(w http.ResponseWriter) {
err := recover()
if err != nil {
stackTrace := string(debug.Stack())
log.Println("----------WATCH: LOG START----------")
log.Printf("[WATCH] panic: %v\nFollowing is the stack trace: %s", err, stackTrace)
log.Println("----------WATCH: LOG END----------")
t := time.Now()
if !wh.dev {
http.Error(w, "Something went wrong!", http.StatusInternalServerError)
if wh.sendEmail {
// Run in another go-routine to make it non-blocking
go issueEmail(wh.emailDetails, t.Format(time.UnixDate), err.(string), stackTrace)
}
if wh.sendSlack {
go issueSlack(wh.slackDetails, t.Format(time.UnixDate), err.(string), stackTrace)
}
if wh.sendDiscord {
go issueDiscord(wh.discordDetails, t.Format(time.UnixDate), err.(string), stackTrace)
}
return
}
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "<html><body><h1>panic: %v</h1><h2>Stack trace:</h2><pre>%s</pre></body></html>", err, getLinkTrace(stackTrace, wh.debugPath))
}
}
func issueEmail(d EmailDetails, timeError, panicError, stackTrace string) {
recipients := strings.Join(d.To, ",")
log.Println("[WATCH]: Issuing panic email alert to", recipients)
mime := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"
msgBody := fmt.Sprintf("<h1>Panic Alert!</h1>This is to bring to your attention that your application has hit an unexpected panic.<br />Fortunately, you use <b><a href=\"https://github.com/ojaswa1942/go-watch\">watch</a></b>. Just kidding, here is what you need to know:<br /><h2>Timestamp:</h2>%s<h2>Error:</h2>%s<h2>Stack trace:</h2><pre style=\"background:#1c1b1b;color:#fff;padding:12px;\">%s</pre>",
timeError, panicError, stackTrace)
msg := []byte("From: " + d.From + "\r\n" +
"To: " + recipients + "\r\n" +
"Subject: [WATCH] Panic Alert!\r\n" +
mime + "\r\n" +
"\r\n" +
msgBody)
err := smtp.SendMail(d.Addr, d.A, d.From, d.To, msg)
if err != nil {
log.Print("[WATCH]: Error while issuing panic email: ", err)
} else {
log.Println("[WATCH]: Issued email alerts")
}
}
func issueSlack(d SlackDetails, timeError, panicError, stackTrace string) {
webHook := d.WebHookURL
log.Println("[WATCH]: Issuing panic slack alert to ", webHook)
txt := ":bangbang: *Panic Alert!* :bangbang:\nThis is to bring to your attention that your application has hit an unexpected panic.\nFortunately, you use <https://github.com/ojaswa1942/go-watch|go-watch>. Just kidding, here is what you need to know:\n ```Timestamp: %s \nError: %s \nStack trace: %s ```"
slackBody, _ := json.Marshal(map[string]string{"text": fmt.Sprintf(txt, timeError, panicError, stackTrace)})
req, err := http.NewRequest(http.MethodPost, webHook, bytes.NewBuffer(slackBody))
if err != nil {
log.Print("[WATCH]: Error while issuing panic to slack: ", err)
}
req.Header.Add("Content-Type", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
log.Print("[WATCH]: Error while issuing panic slack: ", err)
}
if resp.StatusCode != http.StatusOK {
log.Print("[WATCH]: Error while issuing panic slack, got response code ", resp.StatusCode)
} else {
log.Println("[WATCH]: Issued slack alerts")
}
}
func issueDiscord(d DiscordDetails, timeError, panicError, stackTrace string) {
var (
webHook = d.WebHookURL
template = `
:bangbang: *Panic Alert!* :bangbang:
This is to bring to your attention that your application has hit an unexpected panic.
Fortunately, you use <https://github.com/ojaswa1942/go-watch|go-watch>. Just kidding, here is what you need to know:
Timestamp: %s
Error: %s
Stack trace: %s
`
err error
body []byte
req *http.Request
res *http.Response
)
log.Println("[WATCH]: Issuing panic discord alert to ", webHook)
if body, err = json.Marshal(map[string]string{"content": fmt.Sprintf(template, timeError, panicError, stackTrace)}); err != nil {
log.Print("[WATCH]: Error while issuing panic to discord: ", err)
return
}
if req, err = http.NewRequest(http.MethodPost, webHook, bytes.NewBuffer(body)); err != nil {
log.Print("[WATCH]: Error while issuing panic to discord: ", err)
return
}
req.Header.Add("Content-Type", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
if res, err = client.Do(req); err != nil {
log.Print("[WATCH]: Error while issuing panic to discord: ", err)
return
}
if res.StatusCode != http.StatusOK {
log.Print("[WATCH]: Error while issuing panic discord, got response code ", res.StatusCode)
return
}
log.Println("[WATCH]: Issued discord alerts")
}
func sourceCodeHandler(w http.ResponseWriter, r *http.Request) {
filePath := r.FormValue("path")
lineStr := r.FormValue("line")
lineNumber, err := strconv.Atoi(lineStr)
if err != nil {
lineNumber = -1
}
fileContent, err := getFileContent(filePath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
writeSource, err := getFormattedSource(fileContent, lineNumber)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html")
err = writeSource(w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func getFileContent(filePath string) (string, error) {
file, err := os.Open(strings.Trim(filePath, "\""))
if err != nil {
return "", err
}
fileBytes := bytes.NewBuffer(nil)
if _, err = io.Copy(fileBytes, file); err != nil {
return "", err
}
return fileBytes.String(), nil
}
func getFormattedSource(content string, lineNumber int) (func(io.Writer) error, error) {
var highlightLine [][2]int
if lineNumber > 0 {
highlightLine = append(highlightLine, [2]int{lineNumber, lineNumber})
}
lexer := lexers.Get("go")
iterator, err := lexer.Tokenise(nil, content)
if err != nil {
return nil, err
}
style := styles.Get("monokailight")
if style == nil {
style = styles.Fallback
}
formatter := html.New(html.TabWidth(2), html.WithLineNumbers(true), html.LineNumbersInTable(true), html.HighlightLines(highlightLine))
return func(w io.Writer) error {
err := formatter.Format(w, style, iterator)
if err != nil {
return err
}
return nil
}, nil
}
func getLinkTrace(stackTrace, debugPath string) string {
re := regexp.MustCompile(`\t.*:\d*`)
matches := re.ReplaceAllStringFunc(stackTrace, func(match string) string {
split := strings.Split(match, ":")
path, lineNum := strings.Trim(split[0], "\t "), split[1]
return fmt.Sprintf("> <a target=\"_blank\" href=%s?line=%s&path=%s>%s:%s</a>", debugPath, lineNum, url.PathEscape(path), path, lineNum)
})
return matches
}