forked from airbrake/gobrake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotifier.go
98 lines (86 loc) · 2.12 KB
/
notifier.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
package gobrake
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"runtime"
"time"
)
var httpClient = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: func(netw, addr string) (net.Conn, error) {
return net.DialTimeout(netw, addr, 3*time.Second)
},
ResponseHeaderTimeout: 5 * time.Second,
},
Timeout: 10 * time.Second,
}
type Notifier struct {
Client *http.Client
StackFilter func(string, int, string, string) bool
createNoticeURL string
context map[string]string
}
func NewNotifier(host, key string) *Notifier {
n := &Notifier{
Client: httpClient,
StackFilter: stackFilter,
createNoticeURL: getCreateNoticeURL(host, key),
context: map[string]string{
"language": runtime.Version(),
"os": runtime.GOOS,
"architecture": runtime.GOARCH,
},
}
if hostname, err := os.Hostname(); err == nil {
n.context["hostname"] = hostname
}
if wd, err := os.Getwd(); err == nil {
n.context["rootDirectory"] = wd
}
return n
}
func (n *Notifier) SetContext(name, value string) {
n.context[name] = value
}
func (n *Notifier) Notify(e interface{}, req *http.Request) error {
notice := n.Notice(e, req, 3)
if err := n.SendNotice(notice); err != nil {
log.Printf("gobrake failed (%s) reporting error: %v", err, e)
return err
}
return nil
}
func (n *Notifier) Notice(e interface{}, req *http.Request, startFrame int) *Notice {
stack := stack(startFrame, n.StackFilter)
notice := NewNotice(e, stack, req)
for k, v := range n.context {
notice.Context[k] = v
}
return notice
}
func (n *Notifier) SendNotice(notice *Notice) error {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
if err := enc.Encode(notice); err != nil {
return err
}
resp, err := n.Client.Post(n.createNoticeURL, "application/json", buf)
if err != nil {
return err
}
// Read response so underlying connection can be reused.
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
return fmt.Errorf("gobrake: got %d response, wanted 201", resp.StatusCode)
}
return nil
}