help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
go-rest-api
/
internal
/
middleware
RSK World
go-rest-api
Go REST API - Enterprise-grade REST API with JWT Authentication + PostgreSQL + Redis Caching + Docker + Comprehensive Testing + Educational Design
middleware
  • auth_middleware.go1.6 KB
  • auth_middleware_test.go2.7 KB
  • cors.go819 B
  • logger.go736 B
  • ratelimit.go1.3 KB
  • role_middleware.go1.1 KB
auth_middleware.gostorage.ymljumping_002.mp4categories.ymlstyle.cssprocess_images.cpython-313.pycwrap_parameters.rbuser.goerror_messages.html.erbsample_009.jsonlogger.gotest.rbsample_010.jsonsample_006.jsonsample_002.jsonsample_008.jsonsample_004.jsonsample_007.jsondevise.rbratelimit.go
internal/middleware/auth_middleware.go
Raw Download
Find: Go to:
/*
* Author: RSK World
* Email: help@rskworld.in / support@rskworld.in
* Website: https://rskworld.in/contact.php
* Year: 2026
*/

package middleware

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"github.com/rskworld/go-rest-api/internal/config"
	"github.com/rskworld/go-rest-api/internal/response"
)

func AuthMiddleware(cfg *config.Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			response.Unauthorized(c, "Authorization header is required")
			c.Abort()
			return
		}

		bearerToken := strings.Split(authHeader, " ")
		if len(bearerToken) != 2 {
			response.Unauthorized(c, "Invalid token format")
			c.Abort()
			return
		}

		tokenString := bearerToken[1]
		token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
			}
			return []byte(cfg.JWTSecret), nil
		})

		if err != nil || !token.Valid {
			response.Unauthorized(c, "Invalid token")
			c.Abort()
			return
		}

		if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
			c.Set("user_id", claims["user_id"])
			if role, exists := claims["role"]; exists {
				c.Set("user_role", role)
			} else {
				c.Set("user_role", "user") // Default role if not specified
			}
		} else {
			response.Unauthorized(c, "Invalid token claims")
			c.Abort()
			return
		}

		c.Next()
	}
}
67 lines•1.6 KB
go
internal/models/user.go
Raw Download
Find: Go to:
/*
* Author: RSK World
* Email: help@rskworld.in / support@rskworld.in
* Website: https://rskworld.in/contact.php
* Year: 2026
*/

package models

import (
	"time"

	"gorm.io/gorm"
)

type User struct {
	ID        uint           `gorm:"primaryKey" json:"id"`
	Email     string         `gorm:"uniqueIndex;not null" json:"email" validate:"required,email"`
	Password  string         `gorm:"not null" json:"-" validate:"required,min=6,max=128"` // Don't expose password in JSON
	Name      string         `gorm:"not null" json:"name" validate:"required,min=2,max=100"`
	Role      string         `gorm:"not null;default:'user'" json:"role" validate:"required,oneof=admin user"`
	IsActive  bool           `gorm:"not null;default:true" json:"is_active"`
	LastLogin *time.Time     `json:"last_login"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}
28 lines•963 B
go
internal/middleware/logger.go
Raw Download
Find: Go to:
/*
* Author: RSK World
* Email: help@rskworld.in / support@rskworld.in
* Website: https://rskworld.in/contact.php
* Year: 2026
*/

package middleware

import (
	"log"
	"time"

	"github.com/gin-gonic/gin"
)

func LoggerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		startTime := time.Now()

		// Process request
		c.Next()

		endTime := time.Now()
		latency := endTime.Sub(startTime)

		statusCode := c.Writer.Status()
		clientIP := c.ClientIP()
		method := c.Request.Method
		path := c.Request.URL.Path

		log.Printf("[RSK API] %v | %3d | %13v | %15s | %-7s %s\n",
			endTime.Format("2006/01/02 - 15:04:05"),
			statusCode,
			latency,
			clientIP,
			method,
			path,
		)
	}
}
42 lines•736 B
go
internal/middleware/ratelimit.go
Raw Download
Find: Go to:
/*
* Author: RSK World
* Email: help@rskworld.in / support@rskworld.in
* Website: https://rskworld.in/contact.php
* Year: 2026
*/

package middleware

import (
	"net/http"
	"sync"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/rskworld/go-rest-api/internal/response"
	"golang.org/x/time/rate"
)

type IPRateLimiter struct {
	ips map[string]*rate.Limiter
	mu  *sync.RWMutex
	r   rate.Limit
	b   int
}

func NewIPRateLimiter(r rate.Limit, b int) *IPRateLimiter {
	i := &IPRateLimiter{
		ips: make(map[string]*rate.Limiter),
		mu:  &sync.RWMutex{},
		r:   r,
		b:   b,
	}

	return i
}

func (i *IPRateLimiter) AddIP(ip string) *rate.Limiter {
	i.mu.Lock()
	defer i.mu.Unlock()

	limiter := rate.NewLimiter(i.r, i.b)
	i.ips[ip] = limiter
	return limiter
}

func (i *IPRateLimiter) GetLimiter(ip string) *rate.Limiter {
	i.mu.Lock()
	limiter, exists := i.ips[ip]
	if !exists {
		i.mu.Unlock()
		return i.AddIP(ip)
	}
	i.mu.Unlock()
	return limiter
}

func RateLimitMiddleware() gin.HandlerFunc {
	// Allow 5 requests per second with a burst of 10
	limiter := NewIPRateLimiter(5, 10)

	return func(c *gin.Context) {
		ip := c.ClientIP()
		limiter := limiter.GetLimiter(ip)
		if !limiter.Allow() {
			response.Error(c, http.StatusTooManyRequests, "Too many requests")
			c.Abort()
			return
		}
		c.Next()
	}
}
73 lines•1.3 KB
go
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer