Start learning free

LESSON 65 OF 173 · BACKEND: APIS WITH A DATABASE

Connect the Shop to a Database

Practice

A slice inside your code forgets everything when the app stops. A database keeps data in a file instead. From now on the shop's products live in the file shop.db, in the products table, and Go's database/sql package lets your app talk to it.

You open the database once, when the app starts, with sql.Open. Then db.Query(...) runs a SQL query and gives back rows. rows.Next() moves to each row in turn, and rows.Scan copies the row's values into the variables you point it at with &, in the order of the columns you asked for. defer rows.Close() closes the rows when the function ends. For example, with a table books that has a title and a year:

rows, _ := db.Query("SELECT title, year FROM books")
defer rows.Close()
for rows.Next() {
	var title string
	var year int
	rows.Scan(&title, &year)
	fmt.Println(title, year)   // Dune 1965, then Emma 1815
}

An API answers with JSON objects, so each row fills a Product struct, whose tags give the keys. A cell that is empty in the database (NULL) leaves a *string field as nil, and JSON writes it as null. One Go rule to expect on the way: a variable that is declared but not used yet stops the build, until a later line uses it.

GET /           →  200  Welcome to the shop!
GET /products   →  200  [{"id": 1, "name": "Mug", "price": 12, "category": "kitchen"},
                         {"id": 2, "name": "Notebook", "price": 7, "category": "office"},
                         … 8 products in all …
                         {"id": 8, "name": "Gift card", "price": 50, "category": null}]

Your task: open shop.db in db and make GET /products read the products from the products table, scanning each row into a Product and adding it to result.


Assignment
Follow the Coding Tutorial to open the database, run the query and scan its rows into the list of products.


Hint
Pass rows.Scan the addresses in the same order as the columns of your SELECT: id is the first column you named, so &p.ID comes first.


STEP 1 OF 7
    Ctrl + Enter to check