Golang : Basic Middleware in Golang

Okky Muhamad Budiman
2 min readSep 15, 2020

--

middleware in golang

What is Middleware ?

Middleware is the layer in between routers and controllers. In web programming especially in backend programming, middleware will use for some action before accessing the controllers.

https://drstearns.github.io/tutorials/gomiddleware

Middleware usually used for :

  1. Authentication
  2. Authorization
  3. Rate Limiter
  4. Access Control Layer
  5. Whitelist Service
  6. Etc

In this Article I will show you how to implementation the middleware in Go programming language.

The first we create golang projects and creating some router for Rest API. We will use mux https://github.com/gorilla/mux for router package.

Let’s start create main.go :

func main() {
r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
return
})
r.HandleFunc("/products", ProductsHandler)
}
func ProductsHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
return
}

Next we will create file called middleware.go and create method BasicAuthorize for checking authentication before accessing the controller

func BasicAuthorize(handlerFunc http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, pass, _ := r.BasicAuth()
if user != "foo" && pass != "bar"{
w.WriteHeader(http.StatusUnauthorized)
return
}

handlerFunc.ServeHTTP(w, r)
}
}

In this code we will check the user and password before accessing the controller, so if user and password do not match with the rules, we will return statusUnauthorized that means the authentication is not valid.

Now we will wrapper the endpoint /products with BasicAuthorize method.

r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
return
})
r.HandleFunc("/products", BasicAuthorize(ProductsHandler))

with this code we will check the authentication before accessing the ProductHandler. So this is it the basic Middleware implementation in Golang, you can create another middleware that you want such as whitelist services if we implement in microservices, rate limiter for limit the request or etc.

the next discussion is how to apply cobra command in Golang.

Reference :

Previous Article

Golang + RabbitMQ

--

--

Okky Muhamad Budiman

Tech Enthusiast, Punk Rock Software Engineer, Hustler Harder