Creating an Authentication API with Golang

A short article for beginners on how to create an authentication API using Go.

Requirements

You need to install Go on your computer.

Let’s get to work

First of all, let’s create a new project. Create a new file named main.go and enter the start code:

package main

import (
  "fmt"
  "net/http"
  "github.com/gin-gonic/gin"
)

POST and GET methods

To handle GET and POST requests, let’s create GetMethod and PostMethod:

func PostMethod(c *gin.Context) {
  fmt.Println("napi.go 'PostMethod' called")
  message := "PostMethod called"
  c.JSON(http.StatusOK, message)
}
func GetMethod(c *gin.Context) {
  fmt.Println("napi.go 'GetMethod' called")
  message := "GetMethod called"
  c.JSON(http.StatusOK, message)
}

Main function

You need to create a router Gin to process all requests:

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

After that add GetMethod and PostMethod:

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

router.POST("/", PostMethod)
  router.GET("/", GetMethod)

}

And, at the end of everything, add a port that the server will listen on and on which it will run:

func main() {
  router := gin.Default()
router.POST("/", PostMethod)
  router.GET("/", GetMethod)
listenPort := "4000"
router.Run(":"+listenPort)
}

Now let’s run the code to check if the server is running.

Authentication

With the basic web server set up, let’s start adding elements for the authentication API.

Let’s start with func main ():

func main() {
  router := gin.Default()
subRouterAuthenticated := router.Group("/api/v1/PersonId", gin.BasicAuth(gin.Accounts{
    "admin": "adminpass",
  }))
listenPort := "1357"
router.Run(":"+listenPort)
}

Now pass the query parameters:

func main() {
  router := gin.Default()
subRouterAuthenticated := router.Group("/api/v1/PersonId", gin.BasicAuth(gin.Accounts{
    "admin": "adminpass",
  }))
subRouterAuthenticated.GET("/:IdValue", GetMethod)
listenPort := "1357"
  router.Run(":"+listenPort)
}

Setting up GetMethod ()

GetMethod () requests and outputs Person IdValue from the query parameter passed in the API url:

func GetMethod(c *gin.Context) {
  fmt.Println("n'GetMethod' called")
  IdValue := c.Params.ByName("IdValue")
  message := "GetMethod Called With Param: " + IdValue
  c.JSON(http.StatusOK, message)
ReqPayload := make([]byte, 1024)
  ReqPayload, err := c.GetRawData()
  if err != nil {
        fmt.Println(err)
        return
  }
  fmt.Println("Request Payload Data: ", string(ReqPayload))
}

Complete example:

package main
import (
  "fmt"
  "net/http"
  "github.com/gin-gonic/gin"
)
func GetMethod(c *gin.Context) {
  fmt.Println("n'GetMethod' called")
  IdValue := c.Params.ByName("IdValue")
  message := "GetMethod Called With Param: " + IdValue
  c.JSON(http.StatusOK, message)
ReqPayload := make([]byte, 1024)
  ReqPayload, err := c.GetRawData()
  if err != nil {
        fmt.Println(err)
        return
  }
  fmt.Println("Request Payload Data: ", string(ReqPayload))
}
func main() {
  router := gin.Default()
subRouterAuthenticated := router.Group("/api/v1/PersonId", gin.BasicAuth(gin.Accounts{
    "admin": "adminpass",
  }))
subRouterAuthenticated.GET("/:IdValue", GetMethod)
listenPort := "1357"
  
  router.Run(":"+listenPort)
}

Testing with ngrok

First, let’s launch our application in Go:

go run main.go

1. Download ngrok

2. Unpack the ngrok executable file to a folder on the server.

3. Run ngrok on port 1357 (which you specified in the code):

./ngrok http 1357

Result:

ngrok by @emmyc (Ctrl+C to quit)
Session Status online
Session Expires 7 hours, 12 minutes
Version 2.3.35
Region Netherlands (nl)
Web Interface http://127.0.0.1:4040
Forwarding http://ca6d2c4cee3e.ngrok.io -> http://localhost:4000
Forwarding https://ca6d2c4cee3e.ngrok.io -> http://localhost:4000

The command will generate a random dynamic URL where you can test your API and log in with your login details to check if everything is working.

After logging in, you will see:

GetMethod Called With Param: Id456

Everything is working!

Conclusion

This quick tutorial shows you how to create a basic Go API using Gin… In addition, we learned how to create an authentication application and test it using ngrok.

Hopefully this knowledge will be enough to create your own authenticated Go application.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *