Files
go-kite/middleware/cors.go
Timo Riegebauer dd92f23e0b feat: initial implementation of go-kite
Core framework:
- Kite router with full HTTP method support (GET, POST, PUT, DELETE, HEAD, OPTIONS, CONNECT, TRACE)
- Nestable route groups with prefix and middleware inheritance
- Global, group, and route-level middleware with onion ordering
- Centralized error, not-found, and method-not-allowed handlers
- Graceful shutdown on SIGTERM/SIGINT with configurable timeout
- Configurable server read, write, and idle timeouts
- Context with typed request/response helpers, value store, cookie, form, and body binding support
- Response writer wrapper for status code tracking

Middleware:
- Logger with configurable output, format, and skip function
- Recovery with configurable panic handler
- RequestID with configurable header and generator, forwards incoming IDs
- CORS with configurable origins, methods, headers, credentials, and max age
- MaxBodySize with configurable byte limit

Docs:
- README with quickstart, routing, middleware, context API reference, and TLS guide
2026-04-23 20:25:13 +02:00

68 lines
1.6 KiB
Go

package middleware
import (
"fmt"
"net/http"
"strings"
"git.trcreatives.at/trcreatives/go-kite"
)
type CORSConfig struct {
AllowedOrigins []string
AllowedMethods []string
AllowedHeaders []string
ExposedHeaders []string
AllowCredentials bool
MaxAge int
}
func CORS(allowedOrigins ...string) kite.Middleware {
return CORSWithConfig(CORSConfig{AllowedOrigins: allowedOrigins})
}
func CORSWithConfig(cfg CORSConfig) kite.Middleware {
if len(cfg.AllowedOrigins) == 0 {
cfg.AllowedOrigins = []string{"*"}
}
if len(cfg.AllowedMethods) == 0 {
cfg.AllowedMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "CONNECT", "TRACE"}
}
if len(cfg.AllowedHeaders) == 0 {
cfg.AllowedHeaders = []string{"Content-Type", "Authorization"}
}
origins := strings.Join(cfg.AllowedOrigins, ", ")
methods := strings.Join(cfg.AllowedMethods, ", ")
headers := strings.Join(cfg.AllowedHeaders, ", ")
exposed := strings.Join(cfg.ExposedHeaders, ", ")
return func(h kite.Handler) kite.Handler {
return func(ctx *kite.Context) error {
ctx.SetHeader("Access-Control-Allow-Origin", origins)
ctx.SetHeader("Access-Control-Allow-Methods", methods)
ctx.SetHeader("Access-Control-Allow-Headers", headers)
if exposed != "" {
ctx.SetHeader("Access-Control-Expose-Headers", exposed)
}
if cfg.AllowCredentials {
ctx.SetHeader("Access-Control-Allow-Credentials", "true")
}
if cfg.MaxAge > 0 {
ctx.SetHeader("Access-Control-Max-Age", fmt.Sprintf("%d", cfg.MaxAge))
}
if ctx.IsMethod(http.MethodOptions) {
return ctx.WriteNoContent()
}
return h(ctx)
}
}
}