package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"os"
)
func webhookHandler(w http.ResponseWriter, r *http.Request) {
webhookSignature := r.Header.Get("X-Dock-Signature")
if webhookSignature == "" {
http.Error(w, "No signature provided.", http.StatusUnauthorized)
return
}
secret := os.Getenv("DOCK_WEBHOOK_SECRET")
if secret == "" {
http.Error(w, "No secret provided.", http.StatusUnauthorized)
return
}
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Unable to read request body.", http.StatusInternalServerError)
return
}
// Reconstruct the payload
url := r.Host + r.URL.Path
payload := r.Method + "\n" + url + "\n" + string(bodyBytes)
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(payload))
computedSignature := hex.EncodeToString(h.Sum(nil))
if !hmac.Equal([]byte(webhookSignature), []byte(computedSignature)) {
http.Error(w, "Invalid signature.", http.StatusBadRequest)
return
}
// Handle the webhook event
//...
}