first commit

This commit is contained in:
Beyhan Oğur
2026-04-26 21:40:14 +03:00
commit e04ba85564
129 changed files with 17541 additions and 0 deletions

View File

@@ -0,0 +1,75 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func TestDynamicCORS(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Setenv("CORS_ALLOW_ORIGIN", "http://example.com")
r := gin.New()
r.Use(DynamicCORS())
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"ok": true})
})
req := httptest.NewRequest(http.MethodGet, "/ping", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
if got := w.Header().Get("Access-Control-Allow-Origin"); got != "http://example.com" {
t.Fatalf("unexpected allow origin: %q", got)
}
}
func TestDynamicCORSOptions(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Setenv("CORS_ALLOW_ORIGIN", "*")
r := gin.New()
r.Use(DynamicCORS())
r.OPTIONS("/ping", func(c *gin.Context) {
c.Status(http.StatusOK)
})
req := httptest.NewRequest(http.MethodOptions, "/ping", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusNoContent {
t.Fatalf("expected 204, got %d", w.Code)
}
}
func TestDynamicRateLimit(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Setenv("RATE_LIMIT_RPM", "2")
r := gin.New()
r.Use(DynamicRateLimit())
r.GET("/limited", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"ok": true})
})
for i := 1; i <= 3; i++ {
req := httptest.NewRequest(http.MethodGet, "/limited", nil)
req.RemoteAddr = "127.0.0.1:12345"
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if i < 3 && w.Code != http.StatusOK {
t.Fatalf("request %d expected 200, got %d", i, w.Code)
}
if i == 3 && w.Code != http.StatusTooManyRequests {
t.Fatalf("request %d expected 429, got %d", i, w.Code)
}
}
}