Introduction
In this guide, you’ll learn how to connect to a PlanetScale MySQL database with Go by exploring a sample API built using the Gin routing framework. Prerequisites:- Go
- A PlanetScale account
- VS Code (optional)
- The VS Code Rest Client plugin (optional)
TipAlready have a Go application and just want to connect to PlanetScale? Check out the Go quick connect repo.
Create the database
Start in PlanetScale by creating a new database. From the dashboard, click “New Database”, then “Create new database”. Name the databaseproducts_db
, select the desired Plan type, and click “Create database”.
By default, web console access to production branches is disabled to prevent accidental deletion. From your database’s dashboard page, click on the “Settings” tab, check the box labelled “Allow web console access to production branches”, and click “Save database settings”.
Then, click on the “Console” tab, then “Connect”.


.env
file. You’ll need it for the next section.
Run the demo project
Start by opening a terminal on your workstation and clone the sample repository provided..env
, Populate the file with the contents taken from the Connect modal in the previous section.

Exploring the code
Now that the project is running, let’s explore the code to see how everything works. All of the code is stored inmain.go
, with each of the core SQL operations mapped by HTTP method in the main
function:
HTTP Method Name | Query Type |
---|---|
get | SELECT |
post | INSERT |
put | UPDATE |
delete | DELETE |
tests.http
file, which contains HTTP requests that can be sent to test the API. Running the get {{hostname}}/products
test is the equivalent of running SELECT * FROM products
in SQL and returning the results as JSON.
WarningIf you do not wish to use VS Code with the Rest Client plugin, you may use
tests.http
as a reference for your preferred IDE and API testing software.
GetProducts
function defined in main.go
. Notice how the query
variable is the SELECT
statement, which is passed into db.Query
before being scanned into a slice of Product
structs.
?
as a placeholder for the parameter. For example, GetSingleProduct
uses a query with a WHERE
clause that is passed into the db.QueryRow
function along with the query string.
db
function, as demonstrated in CreateProduct
.