Go integrācija

Verificējiet SilentShield nonce savā Go aizmugurē. Darbojas ar net/http, Gin, Echo un jebkuru Go ietvaru.

1. Verifikācijas funkcija

Izveidojiet atkārtoti lietojamu verifikācijas funkciju:

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 starpprogrammatūra

Apvienojiet savu apstrādātāju ar SilentShield verifikāciju:

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 starpprogrammatūra

Gin ietvara lietotājiem:

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. Lietošana

Reģistrējiet starpprogrammatūru savos maršrutos:

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)