Learn go series: Part II - Gorm up!

Mon Dec 25 2017

This is Part 2 of "Learn go" series. You can find the previous post here.

In this post, I will be walking you through an example of interacting with database. A very common scenario, creating a user and storing the password securely. This post picks up from the previous post, so if you haven't read, please skim through it.

CreateUserHandler as the name suggests, gets the users details from the request body and parses it using a newUser struct. We then instantiate the user and save it to the database. In case of any validation issues it sends back a string explaining the error as response with 422 - Unprocessable Entity error code.

Pay close attention to user.HashedPassword = model.HashAndSalt(newUser.Password). We haven't defined the function yet. Let's go back to user.go in model package and define it...

We have built a simple way of storing new user information along with their password in a secure format. Gorm does a lot of things right. And for the sake keeping this post short, I haven't dived deep into some of its interesting aspects. You can see it in action in a sample api on Github.