package main
import (
"errors"
"io"
"log"
"net/http"
"os"
"github.com/ShieldLabs-ai/shieldlabs-go/webhook"
)
func main() {
http.HandleFunc("POST /webhooks/shieldlabs", handleWebhook)
log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}
func handleWebhook(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
http.Error(w, "cannot read the body", http.StatusBadRequest)
return
}
event, err := webhook.ConstructEvent(body, r.Header.Get(webhook.SignatureHeader),
os.Getenv("SHIELDLABS_WEBHOOK_SECRET")) // whsec_your_signing_secret
if errors.Is(err, webhook.ErrSignature) {
http.Error(w, "invalid signature", http.StatusUnauthorized)
return
}
if err != nil {
http.Error(w, "invalid payload", http.StatusBadRequest)
return
}
if e, ok := event.(*webhook.IdentificationScoredEvent); ok {
// Keep this idempotent on the request ID: a later server release
// retries failed deliveries with identical bytes.
log.Printf("request %s scored %d (%s)", e.Data.RequestID, e.Data.RiskScore, e.Data.Band())
}
w.WriteHeader(http.StatusOK) // answer within one second
}