Clean up publish
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Peter Stuifzand 2019-03-19 07:24:13 +01:00
parent fd4ddaf6d6
commit 59668090df

View File

@ -13,11 +13,12 @@ import (
"strings"
"time"
"github.com/pkg/errors"
"p83.nl/go/websub-hub/cmd/hubserver/storage"
)
type subscriptionHandler struct {
store storage.Service
store storage.Service
baseURL string
}
@ -28,51 +29,54 @@ func (handler *subscriptionHandler) handlePublish(w http.ResponseWriter, r *http
client := &http.Client{}
req, err := http.NewRequest("GET", topic, nil)
if err != nil {
return err
return errors.Wrap(err, "could not create request")
}
req.Header.Add("Accept", "*/*")
res, err := client.Do(req)
if err != nil {
return err
return errors.Wrapf(err, "could not request topic %s", topic)
}
defer res.Body.Close()
feedContentType := res.Header.Get("Content-Type")
feedContent, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
return errors.Wrap(err, "could not read body")
}
if subs, err := handler.store.Subscribers(topic); err != nil {
for _, sub := range subs {
log.Printf("publish: creating post to %s\n", sub.Callback)
postReq, err := http.NewRequest("POST", sub.Callback, strings.NewReader(string(feedContent)))
if err != nil {
log.Printf("While creating request to %s: %s", sub.Callback, err)
continue
}
postReq.Header.Add("Content-Type", feedContentType)
postReq.Header.Add("Link",
fmt.Sprintf(
"<%s>; rel=hub, <%s>; rel=self",
handler.baseURL,
topic,
))
if sub.Secret != "" {
mac := hmac.New(sha1.New, []byte(sub.Secret))
mac.Write(feedContent)
signature := mac.Sum(nil)
postReq.Header.Add("X-Hub-Signature", fmt.Sprintf("sha1=%x", signature))
}
postRes, err := client.Do(postReq)
if err != nil {
log.Printf("While POSTing to %s: %s", sub.Callback, err)
continue
}
log.Printf("publish: post send to %s\n", sub.Callback)
log.Println("Response:")
_ = postRes.Write(os.Stdout)
subs, err := handler.store.Subscribers(topic)
if err != nil {
return errors.Wrap(err, "could not get subscribers")
}
for _, sub := range subs {
log.Printf("publish: creating post to %s\n", sub.Callback)
postReq, err := http.NewRequest("POST", sub.Callback, strings.NewReader(string(feedContent)))
if err != nil {
log.Printf("could not creating request to %s: %s", sub.Callback, err)
continue
}
postReq.Header.Add("Content-Type", feedContentType)
postReq.Header.Add("Link",
fmt.Sprintf(
"<%s>; rel=hub, <%s>; rel=self",
handler.baseURL,
topic,
))
if sub.Secret != "" {
mac := hmac.New(sha1.New, []byte(sub.Secret))
mac.Write(feedContent)
signature := mac.Sum(nil)
postReq.Header.Add("X-Hub-Signature", fmt.Sprintf("sha1=%x", signature))
}
postRes, err := client.Do(postReq)
if err != nil {
log.Printf("could not publish to %s: %s", sub.Callback, err)
continue
}
log.Printf("publish: post send to %s\n", sub.Callback)
log.Println("Response:")
_ = postRes.Write(os.Stdout)
}
return nil