Start learning free

LESSON 158 OF 173 · BACKEND: BACKEND WITH AI

The AI Pasted Text into SQL in Go

Practice

An AI assistant wrote a product search for this shop: /products/search?q=te finds every product whose name contains te. It built the SQL by joining strings with +:

word := r.URL.Query().Get("q")
rows, _ := db.Query("SELECT name, price FROM products WHERE name LIKE '%" + word + "%'")

Joining with + pastes the visitor's text into the SQL itself. A quote in that text ends the SQL string early, and the rest runs as SQL: Ana's breaks the query, and x' UNION SELECT name, email FROM customers -- answers every customer's name and email, as if they were products. This is SQL injection.

The fix is a placeholder: write ? in the SQL and pass the value to db.Query after it, as its own argument. Here it is on another table:

rows, _ := db.Query("SELECT name FROM customers WHERE city = ?", city)

The SQL text stays the same whatever the visitor types, and the database only compares the value, quotes and all. Your code must give these answers:

GET /products/search?q=te     →  200  [{"name": "Notebook", "price": 7}, {"name": "Teapot", "price": 22}]
GET /products/search?q=MUG    →  200  [{"name": "Mug", "price": 12}]
GET /products/search?q=Ana's  →  200  []
GET /products/search?q=x' UNION SELECT name, email FROM customers --  →  200  []
GET /products/search          →  200  [{"name": "Mug", "price": 12}, {"name": "Notebook", "price": 7}, … all 8 products]

Your task: rewrite the GET /products/search handler. Read q into word, build the pattern %word% as a Go string, run the query with LIKE ? and the pattern as its value, scan each row into a Product, and answer the slice result as JSON.


Assignment
Follow the Coding Tutorial to rewrite the search handler with a placeholder.


Hint
The % signs go into the Go value, not into the SQL: the SQL only says LIKE ?. Start result as []Product{} so a search with no match answers [], and pass pointers to Scan: &p.Name, &p.Price.


STEP 1 OF 10
    Ctrl + Enter to check

    Ai Sql Injection in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free