This repository has been archived by the owner on Feb 27, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
webhooktunnel.go
100 lines (82 loc) · 2.19 KB
/
webhooktunnel.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
package webhookserver
import (
"net/http"
"sync"
"github.com/pkg/errors"
"github.com/taskcluster/slugid-go/slugid"
"github.com/taskcluster/taskcluster-client-go"
"github.com/taskcluster/taskcluster-client-go/tcauth"
"github.com/taskcluster/webhooktunnel/whclient"
)
// WebhookTunnel wraps a whclient instance as a WebHookServer
type WebhookTunnel struct {
m sync.RWMutex
handlers map[string]http.Handler
// url is assigned when the client connects to the proxy
client *whclient.Client
}
// NewWebhookTunnel returns a pointer to a new WebhookTunnel instance
func NewWebhookTunnel(credentials *tcclient.Credentials) (*WebhookTunnel, error) {
configurer := func() (whclient.Config, error) {
auth := tcauth.New(credentials)
whresp, err := auth.WebhooktunnelToken()
if err != nil {
return whclient.Config{}, errors.Wrap(err, "could not get token from tc-auth")
}
return whclient.Config{
ID: whresp.TunnelID,
ProxyAddr: whresp.ProxyURL,
Token: whresp.Token,
}, nil
}
client, err := whclient.New(configurer)
if err == whclient.ErrAuthFailed {
client, err = whclient.New(configurer)
}
if err != nil {
return nil, err
}
wt := &WebhookTunnel{
handlers: make(map[string]http.Handler),
client: client,
}
go func() {
_ = http.Serve(wt.client, http.HandlerFunc(wt.handle))
}()
return wt, nil
}
// AttachHook adds a new webhook to the server
func (wt *WebhookTunnel) AttachHook(handler http.Handler) (string, func()) {
id := slugid.Nice()
wt.m.Lock()
wt.handlers[id] = handler
wt.m.Unlock()
url := wt.client.URL() + "/" + id + "/"
detach := func() {
wt.m.Lock()
defer wt.m.Unlock()
delete(wt.handlers, id)
}
return url, detach
}
// Stop will close the webhooktunnel client
func (wt *WebhookTunnel) Stop() {
_ = wt.client.Close()
}
func (wt *WebhookTunnel) handle(w http.ResponseWriter, r *http.Request) {
// URL Path format: "/" + slugid(22 characters) + <endpoint>
if len(r.URL.Path) < 24 || r.URL.Path[23] != '/' {
http.NotFound(w, r)
return
}
id, path := r.URL.Path[1:23], r.URL.Path[23:]
wt.m.RLock()
handler, ok := wt.handlers[id]
wt.m.RUnlock()
if !ok {
http.NotFound(w, r)
return
}
r.URL.Path = path
handler.ServeHTTP(w, r)
}