This commit is contained in:
2025-03-18 07:43:46 +08:00
commit d2e93a2736
26 changed files with 918 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
package middleware
import (
"log"
"net/http"
"time"
)
// 审计日志中间件
func AuditLog(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Printf(
"Method=%s Path=%s Duration=%s",
r.Method,
r.URL.Path,
time.Since(start),
)
})
}

View File

@@ -0,0 +1,32 @@
package middleware
import (
"net/http"
"github.com/gorilla/sessions"
)
var store = sessions.NewCookieStore([]byte("your-secret-key"))
// 用户认证中间件
func Auth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session")
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
http.Error(w, "未授权访问", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
// 管理员认证中间件
func AdminAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session")
if role, ok := session.Values["role"].(string); !ok || role != "admin" {
http.Error(w, "需要管理员权限", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}

View File

@@ -0,0 +1,19 @@
package middleware
import (
"net/http"
"golang.org/x/time/rate"
)
var limiter = rate.NewLimiter(rate.Every(1*time.Minute), 5)
// 请求频率限制中间件
func RateLimit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !limiter.Allow() {
http.Error(w, "请求过于频繁", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}