Creating Simple Login API using Go and Mongodb

Shiv kumar
3 min readJan 20, 2019
Image source

In this post we will write a very simple RESTful API for user registration and login .We will be using mongodb official mongo-go-driver for populating data.We will use jwt-go to decode, verify and generate Authentication tokens.

In this post we will write following end points :

  1. /register POST ( New user registration)
  2. /login POST (Existing user can login )
  3. /profile GET (To get user details)

I am assuming that you have already installed go in your system and set the go path. If not then you can follow https://golang.org/doc/install and install go on your system.

Project setup

  1. Create a new folder go-login in your $GOPATH/src directory.
  2. Make your directory structure like :
go-login/
|- controller/ - Contains main API logic files
|- controller.go - Defines handler methods of endpoints
|- model
|- model.go - User and Product models
|- config - Contains all configuration files
|- db
|- db.go - Contains database configuration
|- main.go - Entry point of the API

3. Now install libraries for routing(mux) , database, and authentication. Run following command in terminal to install the dependencies :

$ go get "github.com/gorilla/mux"
$ go get "github.com/mongodb/mongo-go-driver/mongo
$ go get "github.com/dgrijalva/jwt-go"

Writing API

For every go project main.go is the entry point of the application . So we will start with writing our main.go

Import statement will import the packages required by program . Here we are creating a new Router using mux NewRoute() method and then we are registering routes for different different path and handlers.

r.HandleFunc('/register",controller.RegisterHandler).
Methods("POST")

Here /register is the path of register route and controller.RegisterHandler is handler function which will be called when user route to /register . Methods("POST") specify that this is post request .

Now to register user we need to define User model. And it is defined inside model/model.go .Along with user model we will define ResponseResult model in which will store the result of few response object.

All handler functions are defined inside controller/controller.go

First we will see registerHandler in details :

It is taking http.ResponseWrite and *http.Request as argument ,in r we are getting user request body, _ := ioutil.ReadAll(r.Body) reads request body and and stores it inside body . body is a json object to convert it into go variable json.Unmarshal()is used , which converts json object to User object of go.

collection, err := db.GetDBCollection() stores database collection in collection.GetDBCollection function is defined inside db package.

Then it checks if user already exists in DB or not . If not then it hashes the user password using

hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), 5 ) statement and inserting records in database using

_, err = collection.InsertOne(context.TODO(), user) and it returns success message in response.

In loginHandler first we search for user in database and if user is present in database we compare user password and hashed password using

err = bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(user.Password)) if password is correct then the method returns nil otherwise it return error object.

After successful authentication we generate jwt-token with username ,firstname ,lastname as payload .

ProfileHadler reads token from request header then it parses and verifies it with secret key (in our case its “secret”). And then it returns the payload in response .

Now we have seen all the handler functions , it is time to see database connection handling. It is written in config/db/db.go .

Here we are creating connection with mongodb and we return pointer of collection object.

Now we can run our program to see our api in action. To run the appliction , type following command in terminal

$ go run main.go .

And see the magic in postman.

Update :

Syntax for mongodb connection has changed to

client, err := NewClient(options.Client().ApplyURI(“mongodb://localhost:27017”))

References :

  1. https://godoc.org/github.com/mongodb/mongo-go-driver/mongo
  2. https://github.com/gorilla/mux
  3. https://godoc.org/github.com/dgrijalva/jwt-go

--

--

Shiv kumar

Fullstack Frontend Developer, open-source lover, Here to write and read tech. https://www.linkedin.com/in/shiv-kumar-201415