0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 10
click for more info
No active XP Potion
Accept a Quest
Login to submit answers
We've written the SQL query, now it's time to write the API handler that will allow users to create a new user.
The context
package is a part of Go's standard library. It does several things, but the most important thing is that it handles timeouts. All of SQLC's database queries accept a context.Context
as their first argument:
user, err := cfg.db.CreateUser(r.Context(), params.Email)
By passing your handler's http.Request.Context()
to the query, the library will automatically cancel the database query if the HTTP request is canceled or times out.
The benefit is that it will save your server from getting bogged down by long-running queries!
Request:
{
"email": "user@example.com"
}
Response:
HTTP 201 Created
{
"id": "50746277-23c6-4d85-a890-564c0044c2fb",
"created_at": "2021-07-07T00:00:00Z",
"updated_at": "2021-07-07T00:00:00Z",
"email": "user@example.com"
}
Run and submit the CLI tests.
I created a User
struct in my main
package. When the database
package returns a database.User
, I map it to my main
package's User
struct before marshalling it to JSON so that I can control the JSON keys:
type User struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Email string `json:"email"`
}
Alternatively, you can use the 'emit_json_tags` configuration option to automatically include the JSON tags. However, in larger projects, this may be more restrictive than useful.
The Boot.dev CLI requires you to be signed in to submit your solution!
Copy/paste one of the following commands into your terminal:
Run
bootdev run 0820daf4-4006-425a-a50c-f45c0eb97d06
Submit
bootdev run 0820daf4-4006-425a-a50c-f45c0eb97d06 -s
To run and submit the tests for this lesson, you must have an active Boot.dev membership
Become a member to view solution
Using the Bootdev CLI
The Bootdev CLI is the only way to submit your solution for this type of lesson. We need to be able to run commands in your environment to verify your solution.
You can install it here. It's a Go program hosted on GitHub, so you'll need Go installed as well. Instructions are on the GitHub page.