Open hardikm9850 opened 1 month ago
Middleware is a fundamental concept in Go web development, allowing developers to manage and manipulate HTTP requests and responses in a centralized and reusable manner. Here's a look at some commonly used middleware in Go, particularly focusing on popular frameworks like Echo, Chi, and Gorilla Mux.
Logger Middleware
import "github.com/go-chi/chi/v5/middleware"
r.Use(middleware.Logger)
Recovery Middleware
r.Use(middleware.Recoverer)
CORS Middleware
import "github.com/go-chi/cors"
r.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"https://foo.com"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300,
}))
Authentication Middleware
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token == "" {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
// Perform token validation...
next.ServeHTTP(w, r)
})
}
r.Use(AuthMiddleware)
Rate Limiting Middleware
import "github.com/go-chi/httprate"
r.Use(httprate.LimitByIP(100, 1*time.Minute))
Request ID Middleware
import "github.com/go-chi/chi/v5/middleware"
r.Use(middleware.RequestID)
Compression Middleware
import "github.com/go-chi/chi/v5/middleware"
r.Use(middleware.Compress(5))
Here's how you might use some of the same middleware concepts with the Echo framework:
Logger and Recover Middleware
import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
CORS Middleware
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"https://foo.com"},
AllowMethods: []string{echo.GET, echo.POST, echo.PUT, echo.DELETE},
}))
JWT Authentication Middleware
e.Use(middleware.JWTWithConfig(middleware.JWTConfig{
SigningKey: []byte("secret"),
}))
Rate Limiting Middleware
Echo doesn't have built-in rate limiting, but you can use third-party packages like golang.org/x/time/rate
:
import (
"golang.org/x/time/rate"
"github.com/labstack/echo/v4"
)
rateLimiter := rate.NewLimiter(1, 3) // 1 request per second with a burst of 3
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !rateLimiter.Allow() {
return c.String(http.StatusTooManyRequests, "Too Many Requests")
}
return next(c)
}
})
Logger Middleware
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.Method, r.URL)
next.ServeHTTP(w, r)
})
}
r := mux.NewRouter()
r.Use(LoggingMiddleware)
Recover Middleware
func RecoverMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
r := mux.NewRouter()
r.Use(RecoverMiddleware)
A router is responsible for directing requests to the correct parts of your application based on the request URL and HTTP method.
Key Concepts of a Router
Routes: These are the mappings between a URL pattern and a handler function. For example, you might have a route that maps the URL /users/:id to a function that retrieves a user by their ID.
Handlers: These are functions that process incoming HTTP requests and generate responses. In Go, a handler typically has the signature func(w http.ResponseWriter, r *http.Request) for the standard library, but frameworks like Echo use a different signature to provide additional functionality.
Path Parameters: These are dynamic segments in the URL that can be captured and passed to the handler. For example, in the route /users/:id, :id is a path parameter.
Middleware: Middleware functions are executed before the main handler and can be used for tasks such as logging, authentication, and request modification.
See microservices for the example
Intermediate Level
1. Data Validation and Error Handling
validator
package for struct validation.2. Routing and Middleware
gorilla/mux
orecho
.3. Database Integration
GORM
orsqlx
.4. Authentication and Authorization
jwt-go
.Advanced Level
5. Testing
testing
,testify
, andhttptest
.6. Concurrency and Goroutines
7. Performance Optimization
pprof
for performance analysis.8. API Documentation
Swagger
andgo-swagger
.9. Deploying and Scaling