Go SQL Prepared Statements: SQL Injection
In this tutorial, you'll learn about Go SQL Prepared Statements: SQL Injection. We cover key concepts, practical examples, and best practices.
Prepared statements in Go -- Use parameterized queries to prevent SQL injection in Go database applications.
The Problem
Building SQL queries with fmt.Sprintf using user input is an SQL injection vulnerability. Go's database/sql supports parameterized queries.
Wrong
username := r.URL.Query().Get("username")
query := fmt.Sprintf("SELECT * FROM users WHERE name = '%s'", username)
rows, _ := db.Query(query)
Output:
$ curl "http://localhost:8080/search?username=' OR '1'='1"
// Returns ALL users! SQL injection!
Right
db.Query("SELECT * FROM users WHERE name = $1", username)
Output:
$ curl "http://localhost:8080/search?username=' OR '1'='1"
// Returns 0 results -- injection prevented
Prevention
- Always use parameterized queries with placeholders
- Never concatenate user input into SQL strings
- Postgres uses $1, MySQL/SQLite use ?
- Use db.Prepare() for repeated queries
- Validate input types even with placeholders
Common Mistakes with sql prepared statement
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro