Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How To Use BasicAuth Middleware With Go Echo Framework

How To Use BasicAuth Middleware With Go Echo Framework

This is another golang tutorial for Echo web framework. I am implementing basicauth middle-ware functionality into echo golang projects.ECHO Framework is providing many Middleware that supports logger, recover,JWT and basichAuth. You can call Middleware with routes or groups.

This golang tutorial use BasicAuth into rest apis or group of rest api.

Let’s Impliment BasicAuth Middleware

I am assuming, You have created golang application and uses Echo.We will create echo golang instance,

e := echo.New()
e.Use(middleware.Logger())

Logger() is use to lg message, I am using Logger middleware as well, you can remove this line if you don’t want logs.

We will create versioning of api with groups,

//define api version
v1 := e.Group("/api/v1")

Where 'e' is the echo instance variable.

Now we will use middleware with echo instance and passed ValidateUser method for validate user credentials using BasicAuth.

//added middleware
v1.Use(middleware.BasicAuth(helper.ValidateUser))

We will create auth.go file and added 'helper' as package name. We will define ValidateUser method here.

package helper
 
import (
   "net/http"
   "fmt"
   "github.com/labstack/echo"
   "github.com/spf13/viper"
)
 
func ValidateUser(username, password string, c echo.Context) (bool, error) {
      if username == "joe" && password == "secret" {
                                return true, nil
                }
                return false, nil
}

We have imports all required packages and created method ValidateUser() with username and password parameters, that will pass from user side.

Now we will create rest end point to validate middleware working or not, if its working then get true otherwise false.

The ValidateUser() methods will call on each request of v1 groups.

The post How To Use Basicauth Middleware With Go Echo Framework appeared first on Rest Api Example.



This post first appeared on Rest Api Example, please read the originial post: here

Share the post

How To Use BasicAuth Middleware With Go Echo Framework

×

Subscribe to Rest Api Example

Get updates delivered right to your inbox!

Thank you for your subscription

×