cors

package module
v0.0.0-...-ec228b0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 7 Imported by: 205

README

cors

Cross-Origin Resource Sharing for Iris v14. A port of rs/cors.

Iris has its own CORS middleware, kataras/iris/middleware/cors, which is maintained with the framework. Prefer it for new code. This module remains for applications that already use its Options.

Install

go get github.com/iris-contrib/middleware/cors@main
import "github.com/iris-contrib/middleware/cors"

Example

package main

import (
	"github.com/kataras/iris/v14"

	"github.com/iris-contrib/middleware/cors"
)

func main() {
	app := iris.New()

	crs := cors.New(cors.Options{
		AllowedOrigins:   []string{"https://app.example.com"},
		AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE"},
		AllowedHeaders:   []string{"Content-Type", "Authorization"},
		AllowCredentials: true,
		MaxAge:           600,
	})

	// UseRouter runs the handler before the router, so it also answers the
	// preflight (OPTIONS) request of a path that has no OPTIONS route.
	app.UseRouter(crs)

	app.Post("/api/send", func(ctx iris.Context) {
		ctx.WriteString("sent")
	})

	app.Listen(":8080")
}

To register it for a group of routes instead, let the group answer OPTIONS as well:

package main

import (
	"github.com/kataras/iris/v14"

	"github.com/iris-contrib/middleware/cors"
)

func main() {
	app := iris.New()

	api := app.Router("/api")
	// Every route registered below is also registered for OPTIONS,
	// which is what the browser's preflight request needs.
	api.AllowMethods(iris.MethodOptions)
	api.Use(cors.Default())

	api.Get("/items", func(ctx iris.Context) {
		ctx.WriteString("items")
	})

	app.Listen(":8080")
}

Constructors

Function Description
New(Options) iris.Handler The handler for the given options.
Default() iris.Handler New(Options{}): any origin, the methods GET, POST and HEAD, no credentials.
AllowAll() iris.Handler Any origin, six methods, any header, with credentials. See the warning below.

Options

Field Default Description
AllowedOrigins []string any origin Origins that may make cross-origin requests. * allows all. An origin may contain one * wildcard, as in https://*.example.com.
AllowOriginFunc func(origin string) bool none Decides per origin. When set, AllowedOrigins is ignored.
AllowedMethods []string GET, POST, HEAD Methods a cross-origin request may use.
AllowedHeaders []string Origin, Accept, Content-Type, X-Requested-With Request headers a cross-origin request may send. * allows all. Origin is always added to your list.
ExposedHeaders []string none Response headers that scripts may read.
MaxAge int 0, header not sent Seconds a browser may cache a preflight answer.
AllowCredentials bool false Sends Access-Control-Allow-Credentials: true.
OptionsPassthrough bool false After the preflight headers are set, calls the next handler instead of answering 200.
Debug bool false Logs each decision to the standard output.

Behavior

  • A request from an origin, or with a method, that the options do not allow is answered with 403 Forbidden and the route's handler does not run. Browsers send the Origin header on same-origin POST requests too, so list your own origin when you list any.
  • Vary: Origin is added to every answer, and the three preflight header names to a preflight answer. The values are appended, so a Vary set by another middleware survives.
  • A preflight request is answered with 200 OK and no body.
Credentials and the wildcard origin

Browsers refuse Access-Control-Allow-Origin: * together with Access-Control-Allow-Credentials: true. When AllowCredentials is true and every origin is allowed (*, or an empty AllowedOrigins), this middleware answers with the origin of the request instead of *. The browser accepts that, which means any website can then make requests with the visitor's cookies and read the answers. AllowAll() is configured exactly like that.

Do not combine the two for an API that authenticates with cookies or HTTP authentication. List the origins you trust. The framework's own middleware has cors.Strict() for this case.

Examples

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllowAll

func AllowAll() iris.Handler

AllowAll create a new Cors handler with permissive configuration allowing all origins with all standard methods with any header and credentials.

Every origin may then read the responses of credentialed requests, see Options.AllowCredentials. Do not use it for an API that authenticates with cookies or HTTP authentication.

func Default

func Default() iris.Handler

Default creates a new Cors handler with default options.

func New

func New(options Options) iris.Handler

New creates a new Cors handler with the provided options. Use the Application.UseRouter method to register it globally, this is the best option as it enables all the middleware's features. Or to register it per group of routes use: the Router.AllowMethods(iris.MethodOptions) and Router.Use methods instead.

Types

type Cors

type Cors struct {
	// Debug logger
	Log *log.Logger
	// contains filtered or unexported fields
}

Cors http handler

func (*Cors) Serve

func (c *Cors) Serve(ctx iris.Context)

Serve apply the CORS specification on the request, and add relevant CORS headers as necessary.

type Options

type Options struct {
	// AllowedOrigins is a list of origins a cross-domain request can be executed from.
	// If the special "*" value is present in the list, all origins will be allowed.
	// An origin may contain a wildcard (*) to replace 0 or more characters
	// (i.e.: http://*.domain.com). Usage of wildcards implies a small performance penalty.
	// Only one wildcard can be used per origin.
	// Default value is ["*"]
	AllowedOrigins []string
	// AllowOriginFunc is a custom function to validate the origin. It take the origin
	// as argument and returns true if allowed or false otherwise. If this option is
	// set, the content of AllowedOrigins is ignored.
	AllowOriginFunc func(origin string) bool
	// AllowedMethods is a list of methods the client is allowed to use with
	// cross-domain requests. Default value is simple methods (HEAD, GET and POST).
	AllowedMethods []string
	// AllowedHeaders is list of non simple headers the client is allowed to use with
	// cross-domain requests.
	// If the special "*" value is present in the list, all headers will be allowed.
	// Default value is [] but "Origin" is always appended to the list.
	AllowedHeaders []string
	// ExposedHeaders indicates which headers are safe to expose to the API of a CORS
	// API specification
	ExposedHeaders []string
	// MaxAge indicates how long (in seconds) the results of a preflight request
	// can be cached
	MaxAge int
	// AllowCredentials indicates whether the request can include user credentials like
	// cookies, HTTP authentication or client side SSL certificates.
	//
	// Together with an AllowedOrigins of "*" (or no AllowedOrigins at all) the
	// middleware answers with the origin of the request instead of "*", because
	// browsers refuse "*" with credentials. Every origin is then allowed to send
	// credentialed requests. List the origins you trust instead.
	AllowCredentials bool
	// OptionsPassthrough instructs preflight to let other potential next handlers to
	// process the OPTIONS method. Turn this on if your application handles OPTIONS.
	OptionsPassthrough bool
	// Debugging flag adds additional output to debug server side CORS issues
	Debug bool
}

Options is a configuration container to setup the CORS middleware.

Directories

Path Synopsis
client command
manually command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL