-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpublish.go
62 lines (48 loc) · 1.23 KB
/
publish.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
package websub
import (
"bytes"
"crypto/hmac"
"encoding/hex"
"errors"
"fmt"
"github.com/jpillora/backoff"
"net/http"
"time"
)
func Notify(client *http.Client, job PublishJob) (bool, error) {
req, err := http.NewRequest(http.MethodPost, job.Subscription.Callback, bytes.NewReader(job.Data))
if err != nil {
return false, err
}
if job.Subscription.Secret != "" {
mac := hmac.New(NewHasher(job.Hub.Hasher), []byte(job.Subscription.Secret))
mac.Write(job.Data)
req.Header.Set("X-Hub-Signature", job.Hub.Hasher+"="+hex.EncodeToString(mac.Sum(nil)))
}
req.Header.Set("Content-Type", job.ContentType)
req.Header.Set("Link", fmt.Sprintf("<%s>; rel=\"hub\", <%s>; rel=\"self\"", job.Hub.URL, job.Subscription.Topic))
b := &backoff.Backoff{
Min: 100 * time.Millisecond,
Max: 10 * time.Minute,
Factor: 2,
Jitter: false,
}
var attempts int
for {
res, err := client.Do(req)
if err == nil {
res.Body.Close()
if res.StatusCode >= 200 && res.StatusCode <= 299 {
return true, nil
} else if res.StatusCode == http.StatusGone {
return false, nil
}
}
attempts++
if attempts >= 3 {
break
}
<-time.After(b.Duration())
}
return false, errors.New("failed to publish after 3 attempts")
}