Fix SQL Injection (Legacy & Modern) in Chi
Chi is a lean, idiomatic router for Go, but it offers zero built-in protection against SQL injection if you're writing raw queries. The vulnerability isn't in the router—it's in how you handle data between the Chi URL parameters and your database driver. Legacy mistakes involve string interpolation; modern fixes require strict parameterization or type-safe abstraction layers.
The Vulnerable Pattern
func GetUserHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userID := chi.URLParam(r, "id")
// LEAKY: String concatenation/formatting is a death sentence
query := fmt.Sprintf("SELECT name FROM users WHERE id = '%s'", userID)
row := db.QueryRow(query)
// ... scan result
}
}
The Secure Implementation
The vulnerable code treats user input as executable SQL logic. An attacker passing '1 OR 1=1' bypasses authentication entirely. The fix utilizes the 'database/sql' package's prepared statement functionality. By passing arguments separately from the query string, the database engine treats the input strictly as data (literals), never as part of the SQL command. For modern Go stacks, consider using 'sqlc' to generate type-safe code from raw SQL or 'ent' for a graph-based ORM to eliminate manual query building altogether.
func GetUserHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userID := chi.URLParam(r, "id")
// SECURE: Use positional placeholders ($1 for PG, ? for MySQL)
// The driver handles escaping and prevents command injection.
row := db.QueryRowContext(r.Context(), "SELECT name FROM users WHERE id = $1", userID)
// ... scan result
}
}
Your Chi API
might be exposed to SQL Injection (Legacy & Modern)
74% of Chi apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.