Fix SQL Injection (Legacy & Modern) in Gin
SQL Injection in Go's Gin framework occurs when untrusted user input from context parameters (c.Query, c.Param, c.PostForm) is concatenated directly into SQL strings. This bypasses the database driver's ability to distinguish between executable logic and data. To neutralize this, developers must transition from string interpolation to parameterized queries or safe ORM patterns.
The Vulnerable Pattern
func GetUser(c *gin.Context) { id := c.Query("id") // VULNERABLE: Direct string interpolation query := fmt.Sprintf("SELECT * FROM users WHERE id = %s", id) rows, _ := db.Query(query) // ... }
// Modern ORM Vulnerability (GORM) func GetUserORM(c *gin.Context) { id := c.Query(“id”) var user User // VULNERABLE: String formatting inside Where clause db.Where(fmt.Sprintf(“id = %s”, id)).First(&user) }
The Secure Implementation
The secure implementation utilizes prepared statements via the '?' placeholder (or $1 for PostgreSQL). When parameters are passed separately from the query string, the database driver sends the SQL template and the data in two distinct steps or packets. The database engine then treats the input strictly as a literal value, making it impossible for an attacker to inject sub-queries or logic-altering commands. In modern ORMs like GORM, ensure that methods like .Where(), .Raw(), and .Order() never consume formatted strings; always pass user-controlled variables as secondary arguments to the method.
func GetUser(c *gin.Context) { id := c.Query("id") // SECURE: Using database/sql placeholders rows, err := db.Query("SELECT * FROM users WHERE id = ?", id) if err != nil { c.JSON(500, gin.H{"error": "query failed"}) return } // ... }
// Modern SECURE ORM (GORM) func GetUserORM(c *gin.Context) { id := c.Query(“id”) var user User // SECURE: Parameterized arguments db.Where(“id = ?”, id).First(&user) }
Your Gin API
might be exposed to SQL Injection (Legacy & Modern)
74% of Gin 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.