itsjamie / cors

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

CORS for Gin GoDoc Build Status Coverage Status

cors is a middleware written in Go (Golang) to be compatible with the http.Handler interface. It implements the Cross Origin Resource Sharing specification from the W3C. Implementing CORS headers enable pages within a modern web browser to consume resources (such as REST APIs) from servers that are on a different domain.

Initially was implemented as a middleware explicitly for the framework Gin, it now works with the standard interface.

Getting Started

To use this library, add the following code into your Gin router setup:

import "github.com/itsjamie/cors"

cors.New(cors.Options{
	Origins:        "*",
	Methods:        "GET, PUT, POST, DELETE",
	RequestHeaders: "Origin, Authorization, Content-Type",
	ExposedHeaders: "",
	MaxAge: 50 * time.Second,
	Credentials: true,
	ValidateHeaders: false,
})

Setup Options

The middleware can be configured with four options, which match the HTTP headers that it generates:

Parameter Type Details
Origins string A comma delimited list of origins which have access. For example: "http://localhost, http://api.server.com, http://files.server.com"
RequestHeaders string A comma delimited list of allowed HTTP that is passed to the browser in the Access-Control-Allow-Headers header.
ExposeHeaders string A comma delimited list of HTTP headers that should be exposed to the CORS client via the Access-Control-Expose-Headers header.
Methods string A comma delimited list of allowed HTTP methods that is passed to the browser in the Access-Control-Allow-Methods.
MaxAge time.Duration The amount of time a preflight request should be cached, if not specified, the header Access-Control-Max-Age will not be set.
Credentials bool This is passed in the Access-Control-Allow-Credentials header. If true Cookies, HTTP authentication and the client-side SSL certificates will be sent on previous interactions with the origin.
ValidateHeaders bool If false we skip validating the requested headers/methods with the list of allowed ones, and instead just respond with all what we support, it is up to the client implementating CORS to deny the request. This is an optimization allowed by the specification.

CORS Resources

Special Thanks

Special thanks to benpate for providing a foundation to work from.

License

The code is licensed under the MIT License. See LICENSE file for more details.

About

License:MIT License


Languages

Language:Go 100.0%