Skip to content

Prompt injection detection for Go

Arcjet prompt injection detection evaluates each incoming prompt for injection patterns inside your application before it reaches the AI provider. Detected attacks are blocked before the AI call is made, protecting both your application behavior and your AI budget.

What is Arcjet? Arcjet is the AI agent runtime security platform. Discover the agents running in your organization, enforce policy across every action, prompt, and tool call, and keep the evidence to prove what happened. Detect prompt injection, authorize agent tool calls, redact PII, and block bots and abuse.

Protect a chat handler with Shield and prompt injection detection. The LLM call is stubbed so the sample compiles without a model key.

Terminal window
export ARCJET_KEY="ajkey_..."
go get github.com/arcjet/arcjet-go
main.go
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"github.com/arcjet/arcjet-go"
)
var aj = must(arcjet.NewClient(arcjet.Config{
Key: os.Getenv("ARCJET_KEY"),
Rules: []arcjet.Rule{
arcjet.Shield(arcjet.ShieldOptions{Mode: arcjet.ModeLive}),
arcjet.DetectPromptInjection(arcjet.PromptInjectionOptions{
Mode: arcjet.ModeLive,
}),
},
}))
type chatRequest struct {
Message string `json:"message"`
}
func chat(w http.ResponseWriter, r *http.Request) {
var body chatRequest
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
decision, err := aj.Protect(
r.Context(),
r,
arcjet.WithDetectPromptInjectionMessage(body.Message),
)
if err != nil {
log.Printf("arcjet: %v", err)
} else if decision.IsDenied() {
if decision.Reason.IsPromptInjection() {
http.Error(w, "Prompt injection detected – rephrase your message", http.StatusBadRequest)
return
}
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
// Safe to pass body.Message to your LLM.
_ = json.NewEncoder(w).Encode(map[string]string{"reply": "..."})
}
func main() {
http.HandleFunc("/chat", chat)
log.Fatal(http.ListenAndServe(":8000", nil))
}
func must[T any](v T, err error) T {
if err != nil {
log.Fatal(err)
}
return v
}
Terminal window
go run .
curl -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-d '{"message": "What is the capital of France?"}'

Need help with anything? Email support@arcjet.com to get support from our engineering team.

Discussion