func CORSWithConfig(config CORSConfig) twig.MiddlewareFunc {
	if config.Skipper == nil {
		config.Skipper = DefaultCORSConfig.Skipper
	}
	if len(config.AllowOrigins) == 0 {
		config.AllowOrigins = DefaultCORSConfig.AllowOrigins
	}
	if len(config.AllowMethods) == 0 {
		config.AllowMethods = DefaultCORSConfig.AllowMethods
	}
	allowMethods := strings.Join(config.AllowMethods, ",")
	allowHeaders := strings.Join(config.AllowHeaders, ",")
	exposeHeaders := strings.Join(config.ExposeHeaders, ",")
	maxAge := strconv.Itoa(config.MaxAge)
	return func(next twig.HandlerFunc) twig.HandlerFunc {
		return func(c twig.Ctx) error {
			if config.Skipper(c) {
				return next(c)
			}
			req := c.Req()
			res := c.Resp()
			origin := req.Header.Get(twig.HeaderOrigin)
			allowOrigin := ""
			for _, o := range config.AllowOrigins {
				if o == "*" && config.AllowCredentials {
					allowOrigin = origin
					break
				}
				if o == "*" || o == origin {
					allowOrigin = o
					break
				}
			}
			if req.Method != http.MethodOptions {
				res.Header().Add(twig.HeaderVary, twig.HeaderOrigin)
				res.Header().Set(twig.HeaderAccessControlAllowOrigin, allowOrigin)
				if config.AllowCredentials {
					res.Header().Set(twig.HeaderAccessControlAllowCredentials, "true")
				}
				if exposeHeaders != "" {
					res.Header().Set(twig.HeaderAccessControlExposeHeaders, exposeHeaders)
				}
				return next(c)
			}
			res.Header().Add(twig.HeaderVary, twig.HeaderOrigin)
			res.Header().Add(twig.HeaderVary, twig.HeaderAccessControlRequestMethod)
			res.Header().Add(twig.HeaderVary, twig.HeaderAccessControlRequestHeaders)
			res.Header().Set(twig.HeaderAccessControlAllowOrigin, allowOrigin)
			res.Header().Set(twig.HeaderAccessControlAllowMethods, allowMethods)
			if config.AllowCredentials {
				res.Header().Set(twig.HeaderAccessControlAllowCredentials, "true")
			}
			if allowHeaders != "" {
				res.Header().Set(twig.HeaderAccessControlAllowHeaders, allowHeaders)
			} else {
				h := req.Header.Get(twig.HeaderAccessControlRequestHeaders)
				if h != "" {
					res.Header().Set(twig.HeaderAccessControlAllowHeaders, h)
				}
			}
			if config.MaxAge > 0 {
				res.Header().Set(twig.HeaderAccessControlMaxAge, maxAge)
			}
			return c.NoContent()
		}
	}
}
CORSWithConfig returns a CORS middleware with config.
See: `CORS()`.
package middleware
import (
	"net/http"
	"strconv"
	"strings"
	"github.com/twiglab/twig"
)
type (
	CORSConfig struct {
		Skipper Skipper
		AllowOrigins []string
		AllowMethods []string
		AllowHeaders []string
		AllowCredentials bool
		ExposeHeaders []string
		MaxAge int
	}
)
var (
	DefaultCORSConfig = CORSConfig{
		Skipper:      DefaultSkipper,
		AllowOrigins: []string{"*"},
		AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete},
	}
)
func CORS() twig.MiddlewareFunc {
	return CORSWithConfig(DefaultCORSConfig)
}