diff --git a/examples/webhooks/webhooks.go b/examples/webhooks/webhooks.go index de3a0418..89596d99 100644 --- a/examples/webhooks/webhooks.go +++ b/examples/webhooks/webhooks.go @@ -16,8 +16,8 @@ import ( func main() { defer examples.HandlePanic() - client := walletclient.NewWithAdminKey("http://localhost:3003/v1", examples.ExampleAdminKey) - wh := walletclient.NewWebhook(client, "http://localhost:5005/notification", "", "") + client := walletclient.NewWithAdminKey("http://localhost:3003/v1", "xprv9s21ZrQH143K2pmNeAHBzU4JHNDaFaPTbzKbBCw55ErhMDLsxDwKqcaDVV3PwmEmRZa9qUaU261iJaUx8eBiBF77zrPxTH8JGXC7LZQnsgA") + wh := walletclient.NewWebhook(client, "http://localhost:5005/notification", "Authorization", "this-is-the-token") err := wh.Subscribe(context.Background()) if err != nil { panic(err) @@ -29,13 +29,25 @@ func main() { for { select { case event := <-wh.Channel: - time.Sleep(100 * time.Millisecond) // simulate processing time - fmt.Println(event) + time.Sleep(50 * time.Millisecond) // simulate processing time + fmt.Println("Processing event:", event) case <-context.Background().Done(): return } } }() - http.ListenAndServe(":5005", nil) + go func() { + _ = http.ListenAndServe(":5005", nil) + }() + + <-time.After(30 * time.Second) + + fmt.Printf("Unsubscribing...\n") + err = wh.Unsubscribe(context.Background()) + if err != nil { + panic(err) + } + + fmt.Printf("Shutting down...\n") } diff --git a/http.go b/http.go index 56320243..fd833a38 100644 --- a/http.go +++ b/http.go @@ -1146,3 +1146,17 @@ func (wc *WalletClient) AdminSubscribeWebhook(ctx context.Context, webhookURL, t err = wc.doHTTPRequest(ctx, http.MethodPost, "/admin/webhooks/subscribe", rawJSON, wc.adminXPriv, true, nil) return WrapError(err) } + +func (wc *WalletClient) AdminUnsubscribeWebhook(ctx context.Context, webhookURL string) ResponseError { + requestModel := struct { + URL string `json:"url"` + }{ + URL: webhookURL, + } + rawJSON, err := json.Marshal(requestModel) + if err != nil { + return WrapError(nil) + } + err = wc.doHTTPRequest(ctx, http.MethodPost, "/admin/webhooks/unsubscribe", rawJSON, wc.adminXPriv, true, nil) + return WrapError(err) +} diff --git a/webhook.go b/webhook.go index 4db3b4d0..e35d8ae2 100644 --- a/webhook.go +++ b/webhook.go @@ -37,8 +37,16 @@ func (w *Webhook) Subscribe(ctx context.Context) ResponseError { return w.client.AdminSubscribeWebhook(ctx, w.URL, w.TokenHeader, w.TokenValue) } +func (w *Webhook) Unsubscribe(ctx context.Context) ResponseError { + return w.client.AdminUnsubscribeWebhook(ctx, w.URL) +} + func (w *Webhook) HTTPHandler() http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + if w.TokenHeader != "" && r.Header.Get(w.TokenHeader) != w.TokenValue { + http.Error(rw, "Unauthorized", http.StatusUnauthorized) + return + } var events []Event if err := json.NewDecoder(r.Body).Decode(&events); err != nil { http.Error(rw, err.Error(), http.StatusBadRequest)