Adding authentication to your Golang microservice!

Adding an authentication middleware to my microservices in Golang using the HTTP Gin framework.

 func authMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// Define the list of endpoints that require authentication
		securedEndpoints := []string{
			"/users/",
			"/admin",
		}

		// Check if the current request path requires authentication
		for _, path := range securedEndpoints {
			if path == c.Request.URL.Path {
				// Check if the header exists and has the expected value
				headerValue := c.GetHeader("Authorization")
				expectedValue := "your_super_secure_password"

				if headerValue != expectedValue {
					// If the header value doesn't match the expected value,
					// return a 401 Unauthorized response
					c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
						"error": "Unauthorized",
					})
					return
				}
				break
			}
		}

		// If the path doesn't require authentication, continue to the next handler
		c.Next()
	}
}

When setting up the router. You can use

r.Use(authMiddleware())

This will run before each method.