feat: add comments and cleanup unused imports across codebase
This commit is contained in:
@@ -5,6 +5,8 @@ import (
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// VerifyOrigin validates that the request Origin/Referer matches the host
|
||||
// skips validation for safe methods (GET, HEAD, OPTIONS)
|
||||
func VerifyOrigin(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet || r.Method == http.MethodHead || r.Method == http.MethodOptions {
|
||||
@@ -36,7 +38,7 @@ func VerifyOrigin(next http.Handler) http.Handler {
|
||||
|
||||
host := r.Host
|
||||
if forwardedHost := r.Header.Get("X-Forwarded-Host"); forwardedHost != "" {
|
||||
host = forwardedHost
|
||||
host = forwardedHost // support reverse proxies
|
||||
}
|
||||
|
||||
expectedHTTP := "http://" + host
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// statusRecorder wraps ResponseWriter to capture the status code
|
||||
// defaults to 200 if WriteHeader is never called before Write
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
@@ -23,6 +25,7 @@ func newStatusRecorder(w http.ResponseWriter) *statusRecorder {
|
||||
}
|
||||
}
|
||||
|
||||
// WriteHeader records the status code and proxies to underlying writer
|
||||
func (rw *statusRecorder) WriteHeader(code int) {
|
||||
if rw.wroteHeader {
|
||||
return
|
||||
@@ -32,6 +35,7 @@ func (rw *statusRecorder) WriteHeader(code int) {
|
||||
rw.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
// Write ensures a status code is set before writing the body
|
||||
func (rw *statusRecorder) Write(b []byte) (int, error) {
|
||||
if !rw.wroteHeader {
|
||||
rw.WriteHeader(http.StatusOK)
|
||||
@@ -39,12 +43,14 @@ func (rw *statusRecorder) Write(b []byte) (int, error) {
|
||||
return rw.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
// Flush proxies the Flusher interface if supported
|
||||
func (rw *statusRecorder) Flush() {
|
||||
if flusher, ok := rw.ResponseWriter.(http.Flusher); ok {
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
// Hijack proxies the Hijacker interface if supported
|
||||
func (rw *statusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
hijacker, ok := rw.ResponseWriter.(http.Hijacker)
|
||||
if !ok {
|
||||
@@ -53,6 +59,7 @@ func (rw *statusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
return hijacker.Hijack()
|
||||
}
|
||||
|
||||
// Push proxies the Pusher interface if supported
|
||||
func (rw *statusRecorder) Push(target string, opts *http.PushOptions) error {
|
||||
pusher, ok := rw.ResponseWriter.(http.Pusher)
|
||||
if !ok {
|
||||
@@ -61,10 +68,13 @@ func (rw *statusRecorder) Push(target string, opts *http.PushOptions) error {
|
||||
return pusher.Push(target, opts)
|
||||
}
|
||||
|
||||
// Unwrap returns the underlying ResponseWriter for middleware chaining
|
||||
func (rw *statusRecorder) Unwrap() http.ResponseWriter {
|
||||
return rw.ResponseWriter
|
||||
}
|
||||
|
||||
// RequestLogger logs requests that result in 4xx/5xx responses
|
||||
// skips static assets, streaming, and common bot paths
|
||||
func RequestLogger(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
@@ -8,16 +8,19 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// visitor tracks request attempts and last access time per IP
|
||||
type visitor struct {
|
||||
attempts int
|
||||
lastSeen time.Time
|
||||
}
|
||||
|
||||
// Config holds rate limiter settings
|
||||
type Config struct {
|
||||
MaxAttempts int
|
||||
Window time.Duration
|
||||
MaxAttempts int // max requests per window
|
||||
Window time.Duration // sliding window duration
|
||||
}
|
||||
|
||||
// Limiter implements a simple in-memory IP-based rate limiter
|
||||
type Limiter struct {
|
||||
mu sync.Mutex
|
||||
visitors map[string]*visitor
|
||||
@@ -31,6 +34,7 @@ func NewLimiter(cfg Config) *Limiter {
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup removes stale visitor entries older than 3x the window
|
||||
func (l *Limiter) Cleanup(now time.Time) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
@@ -41,21 +45,23 @@ func (l *Limiter) Cleanup(now time.Time) {
|
||||
}
|
||||
}
|
||||
|
||||
// getIP extracts the client IP, checking X-Forwarded-For and X-Real-IP headers
|
||||
func getIP(r *http.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
ips := strings.Split(xff, ",")
|
||||
return strings.TrimSpace(ips[0])
|
||||
return strings.TrimSpace(ips[0]) // first proxy IP
|
||||
}
|
||||
if realIP := r.Header.Get("X-Real-IP"); realIP != "" {
|
||||
return realIP
|
||||
}
|
||||
ip := r.RemoteAddr
|
||||
if colonIdx := strings.LastIndex(ip, ":"); colonIdx != -1 {
|
||||
ip = ip[:colonIdx]
|
||||
ip = ip[:colonIdx] // strip port for IPv4-mapped IPv6
|
||||
}
|
||||
return ip
|
||||
}
|
||||
|
||||
// Middleware returns 429 for rate-limited API requests
|
||||
func (l *Limiter) Middleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !l.allow(getIP(r)) {
|
||||
@@ -66,6 +72,8 @@ func (l *Limiter) Middleware(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// AuthMiddleware redirects rate-limited form submissions back to the page
|
||||
// returns 429 for non-path requests (e.g. API calls)
|
||||
func (l *Limiter) AuthMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !l.allow(getIP(r)) {
|
||||
@@ -80,6 +88,8 @@ func (l *Limiter) AuthMiddleware(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// allow checks and updates the visitor's attempt count; returns true if allowed
|
||||
// resets counter if window has expired, otherwise increments and checks limit
|
||||
func (l *Limiter) allow(ip string) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
@@ -91,7 +101,7 @@ func (l *Limiter) allow(ip string) bool {
|
||||
}
|
||||
|
||||
if time.Since(v.lastSeen) > l.config.Window {
|
||||
v.attempts = 1
|
||||
v.attempts = 1 // reset counter on window expiry
|
||||
v.lastSeen = time.Now()
|
||||
return true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user