How to Implement Webhook Handlers in Go

Web
Implement Go webhook handlers by creating an HTTP endpoint that validates signatures and parses JSON payloads securely.

Implement webhook handlers in Go by defining an HTTP handler function that reads the request body, validates the signature, and processes the payload.

package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"io"
	"net/http"
	"strings"
)

func webhookHandler(w http.ResponseWriter, r *http.Request) {
	secret := []byte("your-webhook-secret")
	signature := r.Header.Get("X-Signature")
	if signature == "" {
		http.Error(w, "Missing signature", http.StatusUnauthorized)
		return
	}

	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Invalid body", http.StatusBadRequest)
		return
	}

	h := hmac.New(sha256.New, secret)
	h.Write(body)
	expectedSig := "sha256=" + hex.EncodeToString(h.Sum(nil))

	if !hmac.Equal([]byte(signature), []byte(expectedSig)) {
		http.Error(w, "Invalid signature", http.StatusUnauthorized)
		return
	}

	var payload map[string]interface{}
	if err := json.Unmarshal(body, &payload); err != nil {
		http.Error(w, "Invalid JSON", http.StatusBadRequest)
		return
	}

	// Process payload
	_ = payload
	w.WriteHeader(http.StatusOK)
}

func main() {
	http.HandleFunc("/webhook", webhookHandler)
	http.ListenAndServe(":8080", nil)
}