77 lines
2.1 KiB
Go
77 lines
2.1 KiB
Go
package middleware
|
|
|
|
import "github.com/gin-gonic/gin"
|
|
|
|
// CORSConfig chứa cấu hình CORS
|
|
type CORSConfig struct {
|
|
AllowOrigins []string `yaml:"allow_origins"`
|
|
AllowMethods []string `yaml:"allow_methods"`
|
|
AllowHeaders []string `yaml:"allow_headers"`
|
|
}
|
|
|
|
// DefaultCORSConfig trả về cấu hình CORS mặc định
|
|
func DefaultCORSConfig() CORSConfig {
|
|
return CORSConfig{
|
|
AllowOrigins: []string{"*"},
|
|
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
|
|
AllowHeaders: []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
|
|
}
|
|
}
|
|
|
|
// CORS middleware xử lý CORS
|
|
func CORS(config CORSConfig) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
|
if c.Request.Method == "OPTIONS" {
|
|
c.AbortWithStatus(204)
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// RateLimiterConfig chứa cấu hình rate limiting
|
|
type RateLimiterConfig struct {
|
|
Rate int `yaml:"rate"` // Số request tối đa trong khoảng thời gian
|
|
}
|
|
|
|
// DefaultRateLimiterConfig trả về cấu hình rate limiting mặc định
|
|
func DefaultRateLimiterConfig() RateLimiterConfig {
|
|
return RateLimiterConfig{
|
|
Rate: 100, // 100 requests per minute
|
|
}
|
|
}
|
|
|
|
// NewRateLimiter tạo middleware rate limiting
|
|
func NewRateLimiter(config RateLimiterConfig) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// TODO: Implement rate limiting logic
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// SecurityConfig chứa tất cả các cấu hình bảo mật
|
|
type SecurityConfig struct {
|
|
// CORS configuration
|
|
CORS CORSConfig `yaml:"cors"`
|
|
// Rate limiting configuration
|
|
RateLimit RateLimiterConfig `yaml:"rate_limit"`
|
|
}
|
|
|
|
// DefaultSecurityConfig trả về cấu hình bảo mật mặc định
|
|
func DefaultSecurityConfig() SecurityConfig {
|
|
return SecurityConfig{
|
|
CORS: DefaultCORSConfig(),
|
|
RateLimit: DefaultRateLimiterConfig(),
|
|
}
|
|
}
|
|
|
|
// Apply áp dụng tất cả các middleware bảo mật vào router
|
|
func (c *SecurityConfig) Apply(r *gin.Engine) {
|
|
// Áp dụng CORS middleware
|
|
r.Use(CORS(c.CORS))
|
|
|
|
// Áp dụng rate limiting
|
|
r.Use(NewRateLimiter(c.RateLimit))
|
|
}
|