Documentation
¶
Index ¶
- func CORS(config CORSConfig) forge.Middleware
- func Compress(level int) forge.Middleware
- func CompressDefault() forge.Middleware
- func GetRequestID(ctx context.Context) string
- func GetRequestIDFromForgeContext(ctx forge.Context) string
- func Logging(logger forge.Logger) forge.Middleware
- func LoggingWithConfig(logger forge.Logger, config LoggingConfig) forge.Middleware
- func RateLimit(limiter *RateLimiter, logger forge.Logger) forge.Middleware
- func Recovery(logger forge.Logger) forge.Middleware
- func RequestID() forge.Middleware
- func Timeout(duration time.Duration, logger forge.Logger) func(http.Handler) http.Handler
- type CORSConfig
- type LoggingConfig
- type RateLimiter
- type RequestIDContextKey
- type ResponseWriter
- func (w *ResponseWriter) Flush()
- func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (w *ResponseWriter) Push(target string, opts *http.PushOptions) error
- func (w *ResponseWriter) Size() int
- func (w *ResponseWriter) Status() int
- func (w *ResponseWriter) Write(data []byte) (int, error)
- func (w *ResponseWriter) WriteHeader(code int)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CORS ¶
func CORS(config CORSConfig) forge.Middleware
CORS returns middleware that handles Cross-Origin Resource Sharing.
Example (Development) ¶
ExampleCORS_development shows a permissive CORS configuration for development.
package main
import (
"net/http"
"github.com/xraph/forge"
"github.com/xraph/forge/middleware"
)
func main() {
app := forge.New()
router := app.Router()
// Development: Allow all origins (NOT for production)
cors := middleware.CORS(middleware.DefaultCORSConfig())
router.Use(cors)
router.GET("/api/users", func(ctx forge.Context) error {
return ctx.JSON(http.StatusOK, map[string]string{"user": "john"})
})
_ = app.Run()
}
Example (MultipleOrigins) ¶
ExampleCORS_multipleOrigins shows configuration with multiple specific origins.
package main
import (
"net/http"
"github.com/xraph/forge"
"github.com/xraph/forge/middleware"
)
func main() {
app := forge.New()
router := app.Router()
corsConfig := middleware.CORSConfig{
AllowOrigins: []string{
"https://web.example.com",
"https://mobile.example.com",
"https://partner.acme.com",
},
AllowMethods: []string{"GET", "POST", "PATCH"},
AllowHeaders: []string{"Content-Type", "Authorization", "X-API-Key"},
ExposeHeaders: []string{"X-Request-ID"},
AllowCredentials: true,
MaxAge: 3600,
}
cors := middleware.CORS(corsConfig)
router.Use(cors)
router.POST("/api/orders", func(ctx forge.Context) error {
return ctx.JSON(http.StatusCreated, map[string]string{"id": "123"})
})
_ = app.Run()
}
Example (Production) ¶
ExampleCORS_production shows a secure CORS configuration for production.
package main
import (
"net/http"
"github.com/xraph/forge"
"github.com/xraph/forge/middleware"
)
func main() {
app := forge.New()
router := app.Router()
// Production: Specific origins with credentials
corsConfig := middleware.CORSConfig{
AllowOrigins: []string{
"https://app.example.com",
"https://admin.example.com",
},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowHeaders: []string{"Content-Type", "Authorization"},
ExposeHeaders: []string{"X-Request-ID", "X-Total-Count"},
AllowCredentials: true, // Enable cookies/auth headers
MaxAge: 7200, // 2 hours
}
cors := middleware.CORS(corsConfig)
router.Use(cors)
router.GET("/api/users", func(ctx forge.Context) error {
return ctx.JSON(http.StatusOK, map[string]string{"user": "john"})
})
_ = app.Run()
}
Example (SpecificRoutes) ¶
ExampleCORS_specificRoutes shows applying CORS to specific route groups.
package main
import (
"net/http"
"github.com/xraph/forge"
"github.com/xraph/forge/middleware"
)
func main() {
app := forge.New()
router := app.Router()
// Public API: Permissive CORS
publicCORS := middleware.CORS(middleware.CORSConfig{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET"},
AllowHeaders: []string{"Content-Type"},
AllowCredentials: false,
MaxAge: 3600,
})
// Private API: Strict CORS with credentials
privateCORS := middleware.CORS(middleware.CORSConfig{
AllowOrigins: []string{"https://app.example.com"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowHeaders: []string{"Content-Type", "Authorization"},
AllowCredentials: true,
MaxAge: 3600,
})
// Public routes
public := router.Group("/public")
public.Use(publicCORS)
public.GET("/status", func(ctx forge.Context) error {
return ctx.JSON(http.StatusOK, map[string]string{"status": "ok"})
})
// Private routes
private := router.Group("/api")
private.Use(privateCORS)
private.GET("/users", func(ctx forge.Context) error {
return ctx.JSON(http.StatusOK, map[string]string{"user": "john"})
})
_ = app.Run()
}
Example (WildcardSubdomain) ¶
ExampleCORS_wildcardSubdomain shows wildcard subdomain support.
package main
import (
"net/http"
"github.com/xraph/forge"
"github.com/xraph/forge/middleware"
)
func main() {
app := forge.New()
router := app.Router()
// Allow all subdomains of example.com
corsConfig := middleware.CORSConfig{
AllowOrigins: []string{"*.example.com"},
AllowMethods: []string{"GET", "POST"},
AllowHeaders: []string{"Content-Type"},
AllowCredentials: false,
MaxAge: 3600,
}
cors := middleware.CORS(corsConfig)
router.Use(cors)
router.GET("/api/data", func(ctx forge.Context) error {
return ctx.JSON(http.StatusOK, map[string]string{"data": "value"})
})
_ = app.Run()
}
func Compress ¶
func Compress(level int) forge.Middleware
Compress middleware compresses HTTP responses using gzip Only compresses if client supports gzip and response is suitable for compression This is the new forge middleware pattern using forge.Handler.
func CompressDefault ¶
func CompressDefault() forge.Middleware
CompressDefault returns Compress middleware with default compression level.
func GetRequestID ¶
GetRequestID retrieves the request ID from standard context.
func GetRequestIDFromForgeContext ¶ added in v0.5.0
GetRequestIDFromForgeContext retrieves the request ID from Forge context.
func Logging ¶
func Logging(logger forge.Logger) forge.Middleware
Logging middleware logs HTTP requests with timing information.
func LoggingWithConfig ¶
func LoggingWithConfig(logger forge.Logger, config LoggingConfig) forge.Middleware
LoggingWithConfig middleware logs HTTP requests with custom configuration.
func RateLimit ¶
func RateLimit(limiter *RateLimiter, logger forge.Logger) forge.Middleware
RateLimit middleware enforces rate limiting per client.
func Recovery ¶
func Recovery(logger forge.Logger) forge.Middleware
Recovery middleware recovers from panics and logs them Returns http.StatusInternalServerError on panic.
func RequestID ¶
func RequestID() forge.Middleware
RequestID middleware adds a unique request ID to each request If X-Request-ID header is present, it uses that, otherwise generates a new UUID.
Types ¶
type CORSConfig ¶
type CORSConfig struct {
// AllowOrigins defines the allowed origin(s)
// Use []string{"*"} for all origins (not compatible with AllowCredentials=true)
// Or specific origins like []string{"https://example.com", "https://app.example.com"}
AllowOrigins []string
// AllowMethods defines allowed HTTP methods
AllowMethods []string
// AllowHeaders defines allowed request headers
AllowHeaders []string
// ExposeHeaders defines headers exposed to the client
ExposeHeaders []string
// AllowCredentials indicates whether credentials are allowed
// Cannot be true when AllowOrigins contains "*"
AllowCredentials bool
// MaxAge indicates how long preflight requests can be cached (seconds)
MaxAge int
}
CORSConfig defines configuration for CORS middleware.
func DefaultCORSConfig ¶
func DefaultCORSConfig() CORSConfig
DefaultCORSConfig returns a permissive CORS configuration suitable for development.
type LoggingConfig ¶
type LoggingConfig struct {
// IncludeHeaders includes request headers in logs
IncludeHeaders bool
// ExcludePaths defines paths to exclude from logging
ExcludePaths []string
// SensitiveHeaders defines headers to redact in logs
SensitiveHeaders []string
}
LoggingConfig defines configuration for logging middleware.
func DefaultLoggingConfig ¶
func DefaultLoggingConfig() LoggingConfig
DefaultLoggingConfig returns default logging configuration.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements token bucket algorithm for rate limiting.
func NewRateLimiter ¶
func NewRateLimiter(rate, burst int) *RateLimiter
NewRateLimiter creates a new rate limiter rate: maximum requests per second burst: maximum burst size (capacity)
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(key string) bool
Allow checks if a request from the given key should be allowed.
type RequestIDContextKey ¶
type RequestIDContextKey string
RequestIDContextKey is the context key for storing request ID.
type ResponseWriter ¶
type ResponseWriter struct {
http.ResponseWriter
// contains filtered or unexported fields
}
ResponseWriter wraps http.ResponseWriter to capture status code and size.
func NewResponseWriter ¶
func NewResponseWriter(w http.ResponseWriter) *ResponseWriter
NewResponseWriter creates a new ResponseWriter.
func (*ResponseWriter) Hijack ¶
func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack implements http.Hijacker.
func (*ResponseWriter) Push ¶
func (w *ResponseWriter) Push(target string, opts *http.PushOptions) error
Push implements http.Pusher.
func (*ResponseWriter) Size ¶
func (w *ResponseWriter) Size() int
Size returns the response size in bytes.
func (*ResponseWriter) Status ¶
func (w *ResponseWriter) Status() int
Status returns the HTTP status code.
func (*ResponseWriter) Write ¶
func (w *ResponseWriter) Write(data []byte) (int, error)
Write writes data and captures size.
func (*ResponseWriter) WriteHeader ¶
func (w *ResponseWriter) WriteHeader(code int)
WriteHeader captures the status code.