gin-contrib/cors

repository·master·Indexed 24 days ago

https://github.com/gin-contrib/cors

A highly configurable CORS (Cross-Origin Resource Sharing) middleware for the Gin web framework in Go. It provides tools to manage allowed origins, methods, and headers through a Config struct, supporting custom validation functions (AllowOriginFunc and AllowOriginWithContextFunc), wildcard patterns, and various URI schemas including WebSockets and browser extensions.

Tokens
2.7K
Snippets
6
Records
17
Agent score
81%

What's inside gin-contrib-cors

  1. CORS Configuration Rules and Constraints

    master

    When configuring the middleware, observe the following rules:

    • Origin Selection: Only one of AllowAllOrigins, AllowOrigins, AllowOriginFunc, or AllowOriginWithContextFunc should be set.
    • Credential Conflict: If AllowAllOrigins is true, other origin settings are ignored and credentialed requests (cookies, etc.) are not allowed.
    • Wildcards: If AllowWildcard is enabled, only one * is allowed per origin string.
    • Protocols: Use AllowBrowserExtensions, AllowWebSockets, or AllowFiles to permit non-HTTP(s) protocols as origins.
    • Validation Errors:
      • Setting AllowAllOrigins while also setting AllowOrigins or an AllowOriginFunc is invalid.
      • If neither AllowAllOrigins, AllowOriginFunc, nor AllowOrigins is set, an error is raised.
      • Using a wildcard in AllowOrigins without setting AllowWildcard: true (or using more than one *) will trigger a panic.
  2. Configure custom origin validation functions

    master

    You can use AllowOriginFunc or AllowOriginWithContextFunc to implement custom logic for validating origins. If AllowOriginWithContextFunc is set, it is preferred over AllowOriginFunc.

    // Using AllowOriginFunc
    config := cors.Config{
      AllowOriginFunc: func(origin string) bool {
        return strings.HasSuffix(origin, "github.com")
      },
    }
    
    // Using AllowOriginWithContextFunc
    config := cors.Config{
      AllowOriginWithContextFunc: func(c *gin.Context, origin string) bool {
        return c.Request.Header.Get("X-Allow-CORS") == "yes"
      },
    }
  3. Customize DefaultConfig

    master

    Instead of defining a full Config struct, you can start with cors.DefaultConfig(). Note that DefaultConfig() does not allow all origins by default (unlike cors.Default()). To allow all origins using this method, you must set AllowAllOrigins = true.

    import (
      "github.com/gin-contrib/cors"
      "github.com/gin-gonic/gin"
    )
    
    func main() {
      router := gin.Default()
      config := cors.DefaultConfig()
      config.AllowOrigins = []string{"http://google.com"}
    
      router.Use(cors.New(config))
      router.Run()
    }
  4. Quick Start: Allow all origins

    master

    To allow all origins by default, use cors.Default().

    ⚠️ Warning: Allowing all origins disables cookies for clients. For credentialed requests, do not allow all origins.

    import (
      "github.com/gin-contrib/cors"
      "github.com/gin-gonic/gin"
    )
    
    func main() {
      router := gin.Default()
      router.Use(cors.Default()) // All origins allowed by default
      router.Run()
    }
  5. Configure CORS with custom settings

    master

    Use cors.New(config) to apply a custom cors.Config struct. This allows you to specify exact origins, methods, headers, and credential support.

    import (
      "time"
      "github.com/gin-contrib/cors"
      "github.com/gin-gonic/gin"
    )
    
    func main() {
      router := gin.Default()
      router.Use(cors.New(cors.Config{
        AllowOrigins:     []string{"https://foo.com"},
        AllowMethods:     []string{"PUT", "PATCH"},
        AllowHeaders:     []string{"Origin"},
        ExposeHeaders:    []string{"Content-Length"},
        AllowCredentials: true,
        AllowOriginFunc: func(origin string) bool {
          return origin == "https://github.com"
        },
        MaxAge: 12 * time.Hour,
      }))
      router.Run()
    }
  6. Use helper methods to update Config

    master

    You can dynamically add methods or headers to an existing cors.Config instance using helper methods.

    config.AddAllowMethods("DELETE", "OPTIONS")
    config.AddAllowHeaders("X-My-Header")
    config.AddExposeHeaders("X-Other-Header")
  7. Configure CORS middleware with Config

    master

    The Config struct allows you to define fine-grained control over Cross-Origin Resource Sharing (CORS) for your Gin application. You can specify allowed origins, methods, headers, and more.

    Key configuration options include:

    • AllowAllOrigins: If true, all origins are allowed. This conflicts with AllowOrigins or custom origin functions.
    • AllowOrigins: A list of specific origins allowed. If * is present, all origins are allowed.
    • AllowOriginFunc: A custom function func(origin string) bool to validate origins.
    • AllowOriginWithContextFunc: A custom function func(c *gin.Context, origin string) bool that provides access to the Gin context for origin validation.
    • AllowMethods: A list of allowed HTTP methods. Defaults to simple methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS) if using DefaultConfig().
    • AllowHeaders: A list of non-simple headers allowed in requests.
    • AllowCredentials: Set to true to allow cookies or HTTP authentication.
    • MaxAge: A time.Duration specifying how long preflight results can be cached.
    • AllowWildcard: Enables support for wildcard patterns like https://api.*.
    • AllowWebSockets, AllowBrowserExtensions, AllowFiles: Enable specific protocol/schema support.
    • CustomSchemas: A list of custom URI schemas (e.g., tauri://) to allow.
  8. Configure CORS with the Config struct

    master

    The Config struct (used by newCors) allows you to define how the CORS middleware handles origins, credentials, and headers.

    Key configuration capabilities include:

    • Allowing all origins: Set AllowAllOrigins: true or include "*" in the AllowOrigins slice.
    • Specifying allowed origins: Use the AllowOrigins slice to list exact origins or patterns.
    • Custom origin validation: Use AllowOriginFunc for simple string-based validation or AllowOriginWithContextFunc for validation that requires access to the *gin.Context.
    • Handling credentials: Set AllowCredentials to allow cross-origin requests with credentials (like cookies).
    • Customizing response status: Set OptionsResponseStatusCode to define the HTTP status returned for preflight OPTIONS requests (defaults to http.StatusNoContent).
  9. Reference cors.Config fields

    master

    The cors.Config struct controls the middleware behavior. All fields are optional unless otherwise stated.

    FieldTypeDefaultDescription
    AllowAllOriginsboolfalseIf true, allows all origins. Credentials cannot be used.
    AllowOrigins[]string[]List of allowed origins. Supports exact match, *, and wildcards.
    AllowOriginFuncfunc(string) boolnilCustom function to validate origin. If set, AllowOrigins is ignored.
    AllowOriginWithContextFuncfunc(*gin.Context,string)boolnilLike AllowOriginFunc, but with request context.
    AllowMethods[]string[]string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}Allowed HTTP methods.
    AllowPrivateNetworkboolfalseAdds Private Network Access CORS header.
    AllowHeaders[]string[]List of non-simple headers permitted in requests.
    AllowCredentialsboolfalseAllow cookies, HTTP auth, or client certs. Only if precise origins are used.
    ExposeHeaders[]string[]Headers exposed to the browser.
    MaxAgetime.Duration12 * time.HourCache time for preflight requests.
    AllowWildcardboolfalseEnables wildcards in origins (e.g. https://*.example.com).
    AllowBrowserExtensionsboolfalseAllow browser extension schemes as origins (e.g. chrome-extension://).
    CustomSchemas[]stringnilAdditional allowed URI schemes (e.g. tauri://).
    AllowWebSocketsboolfalseAllow ws:// and wss:// schemas.
    AllowFilesboolfalseAllow file:// origins (dangerous; use only if necessary).
    OptionsResponseStatusCodeint204Custom status code for OPTIONS responses.
  10. Use custom functions for origin validation

    master

    If the static AllowOrigins list is insufficient, you can provide custom logic via two function fields in the Config struct:

    1. AllowOriginFunc(string) bool: A function that takes the request origin as a string and returns true if it is allowed.
    2. AllowOriginWithContextFunc(*gin.Context, string) bool: A function that takes both the *gin.Context and the origin string, allowing for complex validation logic based on request parameters, headers, or context values.