DEV Community

loading...

Authentication with gin-gonic && gah for golang

#go
Yaşar İÇLİ
I love to Javascript and Golang
・2 min read

Alt Text

I have developed a nice rest api at the weekend with Golang.

What is important here is to log in and register using golang in a simple way.

Gin Auth Handlers - github

I'm very excited and let's get started.

First let's create a golang project:

$ mkdir project
$ cd project
$ touch main.go
Enter fullscreen mode Exit fullscreen mode

Let's install the gin and gah(Gin Auth Handlers) packages.

$ go get -u github.com/gin-gonic/gin
$ go get -u github.com/yasaricli/gah
Enter fullscreen mode Exit fullscreen mode

Open our main.go file as follows

package main

import (
  "github.com/gin-gonic/gin"
  "github.com/yasaricli/gah"
)

func main() {
  router := gin.Default()

  api := router.Group("/api")
  {
    api.POST("/login", gah.LoginHandler)
    api.POST("/register", gah.RegisterHandler)
  }

  router.Run(":3000")
}
Enter fullscreen mode Exit fullscreen mode

Let's set environment variables.

export MONGO_URL=mongodb://127.0.0.1:27017 # MongoDB server URL.
export MONGO_DATABASE=project_db # MongoDB Project db name
export MONGO_COLLECTION=users # Collection to register all users
Enter fullscreen mode Exit fullscreen mode

Let's start api with run command.

go run main.go
Enter fullscreen mode Exit fullscreen mode

Register Request

You need to POST email and password to register.

http POST http://localhost:3000/api/register email=yasaricli@gmail.com password=12345
Enter fullscreen mode Exit fullscreen mode

Response:

Status Code: 200

{
  "data": {
    "_id": "5e18b00ecf1474424f04e68a",
    "email": "yasaricli@gmail.com"
  },
  "status": "success"
}
Enter fullscreen mode Exit fullscreen mode

Login Request

You need to POST email and password to login.

http POST http://localhost:4000/api/login email=yasaricli@gmail.com password=12345
Enter fullscreen mode Exit fullscreen mode

Response:

Status Code: 200

{
  "data": {
    "authToken": "402b2f399114746e583ec3094d613c91c553e238e8f6bdbf55a80865a72d39e7",
    "userId": "5e18b00ecf1474424f04e68a"
  },
  "status": "success"
}
Enter fullscreen mode Exit fullscreen mode

I am developing the gah(Gin Auth Handlers) package. You can help if you want.

Gin Auth Handlers - github

Discussion (0)