Skip to content

Instantly share code, notes, and snippets.

@aonemd
Created November 29, 2024 15:13
Show Gist options
  • Save aonemd/ccc16d63ca64e8540ca6f4853a931c91 to your computer and use it in GitHub Desktop.
Save aonemd/ccc16d63ca64e8540ca6f4853a931c91 to your computer and use it in GitHub Desktop.
Pusher Beams Webhook Server
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
// WebhookData represents the structure of the incoming webhook data from Pusher Beams
type RequestBody struct {
Interests []string `json:"interests"`
WebhookUrl string `json:"webhookUrl"`
Web struct {
Notification struct {
Title string `json:"title"`
Body string `json:"body"`
} `json:"notification"`
} `json:"web"`
}
type Results struct {
Web struct {
NumSuccessfulPublishes int `json:"numSuccessfulPublishes"`
NumFailedPublishes int `json:"numFailedPublishes"`
} `json:"web"`
}
type WebhookData struct {
PublishId string `json:"publishId"`
Status string `json:"status"`
RequestBody RequestBody `json:"requestBody"`
Results Results `json:"results"`
}
func webhookHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Receving Request....")
if r.Method != http.MethodPost {
fmt.Println("An error happened...")
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Unable to read request body", http.StatusBadRequest)
return
}
fmt.Println("Hey body...", string(body))
var webhookData WebhookData
err = json.NewDecoder(bytes.NewBuffer(body)).Decode(&webhookData)
if err != nil {
fmt.Println("An error happened...")
http.Error(w, "Error decoding JSON", http.StatusBadRequest)
return
}
// Log the received webhook data
log.Printf("Received webhook: %+v\n", webhookData)
// Respond with a success message
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "Webhook received successfully")
}
func main() {
http.HandleFunc("/webhook", webhookHandler)
port := ":8080"
log.Printf("Starting server on port %s\n", port)
if err := http.ListenAndServe(port, nil); err != nil {
log.Fatalf("Error starting server: %v\n", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment