diff --git a/cmd/hubserver/handler.go b/cmd/hubserver/handler.go index a5b6b2f..da8d6a9 100644 --- a/cmd/hubserver/handler.go +++ b/cmd/hubserver/handler.go @@ -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