Quick Start: Go Email Webhook
JsonHook delivers every inbound email as a JSON POST request to your webhook endpoint. Setting up a Go handler takes less than 5 minutes. Start by initializing your project:
go mod init myapp && go mod tidy
Then create your webhook endpoint. The following example shows the minimal code needed to receive and acknowledge a JsonHook delivery:
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type EmailPayload struct {
Event string `json:"event"`
Timestamp string `json:"timestamp"`
Address string `json:"address"`
Email struct {
From string `json:"from"`
To []string `json:"to"`
Subject string `json:"subject"`
TextBody string `json:"textBody"`
HtmlBody string `json:"htmlBody"`
} `json:"email"`
}
func webhookHandler(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
var payload EmailPayload
if err := json.Unmarshal(body, &payload); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
fmt.Printf("Email from %s: %s\n", payload.Email.From, payload.Email.Subject)
w.WriteHeader(http.StatusOK)
}
func main() {
http.HandleFunc("/webhook", webhookHandler)
http.ListenAndServe(":3000", nil)
}
Point your JsonHook address webhook URL to this endpoint and you will start receiving parsed emails as JSON within seconds of the email arriving.
Full Go Implementation
The quick start example above is enough to get started, but a production implementation should include signature verification, structured error handling, and proper HTTP response codes. The complete example below demonstrates all of these patterns together.
This implementation verifies the X-JsonHook-Signature header to confirm the request genuinely came from JsonHook, parses the full email payload, and returns the appropriate HTTP status codes to trigger or suppress retries.
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
var webhookSecret = []byte(os.Getenv("JSONHOOK_WEBHOOK_SECRET"))
type Attachment struct {
Filename string `json:"filename"`
ContentType string `json:"contentType"`
Size int `json:"size"`
ContentID string `json:"contentId"`
}
type Email struct {
From string `json:"from"`
To []string `json:"to"`
Subject string `json:"subject"`
TextBody string `json:"textBody"`
HtmlBody string `json:"htmlBody"`
Attachments []Attachment `json:"attachments"`
}
type Payload struct {
Event string `json:"event"`
Timestamp string `json:"timestamp"`
Address string `json:"address"`
Email Email `json:"email"`
}
func verifySignature(body []byte, sigHeader string) bool {
if sigHeader == "" {
return false
}
mac := hmac.New(sha256.New, webhookSecret)
mac.Write(body)
expected := hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(expected), []byte(sigHeader))
}
func webhookHandler(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "failed to read body", http.StatusInternalServerError)
return
}
sig := r.Header.Get("X-JsonHook-Signature")
if !verifySignature(body, sig) {
log.Println("Invalid signature")
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
var payload Payload
if err := json.Unmarshal(body, &payload); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
// Acknowledge before processing
w.WriteHeader(http.StatusOK)
// Process asynchronously
go func(p Payload) {
log.Printf("[%s] Email at %s from %s", p.Timestamp, p.Address, p.Email.From)
log.Printf("Subject: %s", p.Email.Subject)
for _, att := range p.Email.Attachments {
log.Printf("Attachment: %s (%s, %d bytes)", att.Filename, att.ContentType, att.Size)
}
}(payload)
}
func main() {
http.HandleFunc("/webhook", webhookHandler)
fmt.Println("Listening on :3000")
log.Fatal(http.ListenAndServe(":3000", nil))
}
The webhook handler returns 200 immediately after queuing the email for processing. Avoid doing expensive work (database writes, API calls) synchronously inside the handler — process the payload in a background job to stay within JsonHook's 10-second response timeout.
Build Your Go Email Integration
Free API key — start receiving webhooks in 5 minutes.
Get Free API KeyParsing the Webhook Payload
Every JsonHook delivery is an HTTP POST with Content-Type: application/json. The payload follows a consistent schema regardless of the originating email client or provider:
// Define structs matching the JsonHook payload schema
type Attachment struct {
Filename string `json:"filename"`
ContentType string `json:"contentType"`
Size int `json:"size"`
ContentID string `json:"contentId"`
}
type Email struct {
From string `json:"from"`
To []string `json:"to"`
Subject string `json:"subject"`
TextBody string `json:"textBody"`
HtmlBody string `json:"htmlBody"`
Attachments []Attachment `json:"attachments"`
}
type Payload struct {
Event string `json:"event"` // "email.received"
Timestamp string `json:"timestamp"` // "2026-03-15T12:34:56.789Z"
Address string `json:"address"` // "[email protected]"
Email Email `json:"email"`
}
// Parse after signature verification:
var p Payload
if err := json.Unmarshal(body, &p); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
fmt.Println(p.Email.From, p.Email.Subject, p.Email.TextBody)
Key fields in the payload:
- event — Always
"email.received"for inbound email events - timestamp — ISO 8601 timestamp of when JsonHook received the email
- address — The JsonHook inbound address that received the email (e.g.,
[email protected]) - email.from — Sender address string, e.g.,
"Alice <[email protected]>" - email.to — Array of recipient address strings
- email.subject — Email subject line
- email.textBody — Plain text body of the email (may be empty if HTML-only)
- email.htmlBody — HTML body of the email (may be empty if plain-text-only)
- email.attachments — Array of attachment objects, each with
filename,contentType,size, andcontentId
Verifying Webhook Signatures
JsonHook signs every webhook delivery using HMAC-SHA256. The signature is included in the X-JsonHook-Signature request header as a hex digest. To verify it, compute the HMAC-SHA256 of the raw request body using your address's webhook secret and compare it to the header value.
Your webhook secret is returned when you create an inbound address via the API (POST /api/addresses). Store it as an environment variable — never hard-code it.
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
)
func verifyJsonHookSignature(body []byte, sigHeader string, secret []byte) bool {
if sigHeader == "" || len(secret) == 0 {
return false
}
mac := hmac.New(sha256.New, secret)
mac.Write(body)
computed := hex.EncodeToString(mac.Sum(nil))
// hmac.Equal is constant-time
return hmac.Equal([]byte(computed), []byte(sigHeader))
}
// Usage:
// body, _ := io.ReadAll(r.Body)
// sig := r.Header.Get("X-JsonHook-Signature")
// secret := []byte(os.Getenv("JSONHOOK_WEBHOOK_SECRET"))
// if !verifyJsonHookSignature(body, sig, secret) {
// http.Error(w, "unauthorized", http.StatusUnauthorized)
// return
// }
Always verify the signature before processing the payload. Return 401 for invalid signatures so that legitimate retries from JsonHook (which always include a valid signature) are distinguishable from spoofed requests.
Error Handling Best Practices
Reliable webhook handling requires careful attention to error responses. JsonHook uses your HTTP response code to decide whether to retry a delivery:
- Return 200 quickly: Acknowledge receipt immediately and process asynchronously. JsonHook will retry any non-2xx response.
- Return 400 for bad requests: If the payload fails your own validation (not signature — use 401 for that), return 400 to prevent retries of malformed deliveries.
- Return 500 to trigger retries: If your downstream system is temporarily unavailable, returning 500 causes JsonHook to retry with exponential backoff (up to 5 attempts over ~1 hour).
- Never return 200 before verifying the signature: Doing so silently accepts spoofed requests.
Go ecosystem tips:
- Use
io.ReadAll(r.Body)to read the full body into a[]bytebefore both signature verification and JSON unmarshaling — reading the body twice requires resetting it withbytes.NewReader - Use
hmac.Equal()from thecrypto/hmacpackage for constant-time comparison — do not use==orbytes.Equal() - Spin up a goroutine with
go func(p Payload) { ... }(payload)to process asynchronously after writing the 200 response - Use
log.Fatal(http.ListenAndServe(...))to ensure the process exits and is restarted by your supervisor if the server fails to bind
Go Ecosystem Tips
The Go ecosystem offers several libraries and patterns that pair well with JsonHook webhook handling. Here are general recommendations:
- Use a well-maintained HTTP server library appropriate for your use case — the examples in this guide use the most common choice, but any library that gives you raw body access works.
- Store your webhook secret in an environment variable and load it via your language's standard env access pattern — never commit secrets to version control.
- Use your language's standard HMAC library rather than a third-party package — all languages featured in this guide have HMAC-SHA256 in their standard library.
- Consider a structured logging library to capture the
address,event, andtimestampfields from every webhook delivery for observability. - Test your handler locally using a tunneling tool like ngrok or a local webhook testing service before pointing your JsonHook address at a production URL.