User Account Creation
Learn how to create a user registration API in Go.
We'll cover the following
User registration
Users can’t access the application unless they have an account and are signed in successfully. So when a user tries to sign up, what happens?
On sign up, we ask our users to provide the
user_name
anduser_email
. When they do this, we check against the database to see if the username or email address exists. If either of them is found, we throw an error message, notifying our users that they can’t use that username or email because another user with those details already exists.If the
user_name
andemail
are unique, we’ll let the user proceed to the next step, which is password validation.During the
password
validation process, we check to see if thepassword
has a minimum of 8 characters.After the
password
check is complete and the user'spassword
passes it, the user's details are sent through the registration endpoint by triggering aPOST
request.If the registration is successful, a success status code is returned, and if not, an error code is sent.
The user can now proceed to log in and access the platform. If a user creates a profile and doesn’t verify their email address, they will be denied entry.
Registration endpoint
First, let’s create our reviewers model, userModel.go
, in our models
folder. The server parses the data to the client using JSON and the data is stored in our Mongo database using bson
. Our user model contains our user details. We carry out the following steps:
Create a package,
models
:To get our Mongo driver package, we first need to run this command in our terminal:
go get go.mongodb.org/mongo-driver/bson/primitive
.
Next, write an import statement, and within it, we import two packages:
Mongo driver
The
time
package to help with setting the data type for ourCreated_at
andUpdated_at
values
Then we create our
User struct
, which helps us define our data types. The struct acts like a middleman between our MongoDB and Go program. It contains the values we’ll be collecting from our users.
Get hands-on with 1400+ tech skills courses.