Go integrácia
Overte SilentShield nonce vo vašom Go backende. Funguje s net/http, Gin, Echo a akýmkoľvek Go frameworkom.
1. Overovacia funkcia
Vytvorte znovupoužiteľnú overovaciu funkciu:
silentshield/verify.gogo
package silentshield
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
)
type VerifyResponse struct {
Verdict string `json:"verdict"`
Score float64 `json:"score"`
}
func VerifyNonce(apiKey, nonce string) (*VerifyResponse, error) {
body, _ := json.Marshal(map[string]string{"nonce": nonce})
req, err := http.NewRequest("POST",
"https://api.silentshield.io/api/v1/captcha/verify-nonce",
bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Api-Key", apiKey)
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result VerifyResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("decode error: %w", err)
}
return &result, nil
}2a. net/http Middleware
Obaľte váš handler overením SilentShield:
net/http Middlewarego
func SilentShieldMiddleware(apiKey string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
next.ServeHTTP(w, r)
return
}
nonce := r.FormValue("ss_nonce")
if nonce == "" {
http.Error(w, "missing nonce", http.StatusUnprocessableEntity)
return
}
result, err := VerifyNonce(apiKey, nonce)
if err != nil {
next.ServeHTTP(w, r) // fail open
return
}
if result.Verdict == "bot" {
http.Error(w, "bot detected", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}2b. Gin Middleware
Pre používateľov frameworku Gin:
Gin Middlewarego
func SilentShieldMiddleware(apiKey string) gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Method != http.MethodPost {
c.Next()
return
}
nonce := c.PostForm("ss_nonce")
if nonce == "" {
c.JSON(422, gin.H{"error": "missing nonce"})
c.Abort()
return
}
result, err := VerifyNonce(apiKey, nonce)
if err != nil {
c.Next() // fail open
return
}
if result.Verdict == "bot" {
c.JSON(403, gin.H{"error": "bot detected"})
c.Abort()
return
}
c.Next()
}
}3. Použitie
Zaregistrujte middleware na vašich trasách:
Usagego
// net/http
http.Handle("/contact", SilentShieldMiddleware(os.Getenv("SILENTSHIELD_API_KEY"), contactHandler))
// Gin
r := gin.Default()
r.POST("/contact", SilentShieldMiddleware(os.Getenv("SILENTSHIELD_API_KEY")), contactHandler)