hardikm9850 / Go-Playground

1 stars 0 forks source link

Roadmap for Go API Development #3

Open hardikm9850 opened 1 month ago

hardikm9850 commented 1 month ago

Intermediate Level

1. Data Validation and Error Handling

2. Routing and Middleware

3. Database Integration

4. Authentication and Authorization

Advanced Level

5. Testing

6. Concurrency and Goroutines

7. Performance Optimization

8. API Documentation

9. Deploying and Scaling

hardikm9850 commented 1 month ago

2. B

Middleware

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.

Commonly Used Middleware

  1. Logger Middleware

    • Logs information about each HTTP request, such as the request method, URL, status code, and response time.
    • Useful for debugging and monitoring.
    import "github.com/go-chi/chi/v5/middleware"
    
    r.Use(middleware.Logger)
  2. Recovery Middleware

    • Recovers from panics in your application and returns a 500 Internal Server Error.
    • Ensures that your server doesn't crash and provides a graceful error response.
    r.Use(middleware.Recoverer)
  3. CORS Middleware

    • Handles Cross-Origin Resource Sharing (CORS) to allow or restrict resources on a web server to be requested from another domain.
    • Important for web applications that interact with APIs from different origins.
    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,
    }))
  4. Authentication Middleware

    • Verifies the presence and validity of authentication tokens, such as JWTs.
    • Protects routes to ensure only authenticated users can access certain endpoints.
    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)
  5. Rate Limiting Middleware

    • Limits the number of requests a client can make in a given period.
    • Helps protect your server from abuse and ensures fair usage.
    import "github.com/go-chi/httprate"
    
    r.Use(httprate.LimitByIP(100, 1*time.Minute))
  6. Request ID Middleware

    • Assigns a unique request ID to each incoming request, useful for tracing and debugging.
    import "github.com/go-chi/chi/v5/middleware"
    
    r.Use(middleware.RequestID)
  7. Compression Middleware

    • Compresses HTTP responses to reduce the amount of data transmitted over the network.
    import "github.com/go-chi/chi/v5/middleware"
    
    r.Use(middleware.Compress(5))

Using Middleware in Echo

Here's how you might use some of the same middleware concepts with the Echo framework:

  1. 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())
  2. CORS Middleware

    e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
       AllowOrigins: []string{"https://foo.com"},
       AllowMethods: []string{echo.GET, echo.POST, echo.PUT, echo.DELETE},
    }))
  3. JWT Authentication Middleware

    e.Use(middleware.JWTWithConfig(middleware.JWTConfig{
       SigningKey: []byte("secret"),
    }))
  4. 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)
       }
    })

Using Middleware in Gorilla Mux

  1. 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)
  2. 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)
hardikm9850 commented 1 month ago

2.A

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

  1. 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.

  2. 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.

  3. 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.

  4. 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