cors

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2019 License: MIT Imports: 6 Imported by: 0

README

CORS Filter for Golang

Another CORS filter middleware for Golang net/http handler.

Like some other CORS filters (e.g. the Jetty's CORS filter), you can define your AllowedMethod list, even non standard. As default, AllowedMethods list is "GET,POST,HEAD,OPTIONS".

Warning: if you don't add "OPTIONS" to your AllowedMethod list, the filter can't handle preflight request.

This CORS Filter can forward preflight request.

Getting Started

The package is go gettable: go get -u github.com/vpxyz/cors

Example
package main

import (
	"github.com/vpxyz/cors"
	"log"
	"net/http"
	"os"
)

func main() {
	logger := log.New(os.Stdout, "CORS: ", log.LstdFlags)

	corsMiddleware := cors.Filter(cors.Config{
		AllowedOrigins:   "http://foobar.com, http://*.example.com", // origins
		AllowedMethods:   cors.DefaultAllowedMethods + "," + http.MethodPut, // put here your allowed methods
		AllowedHeaders:   cors.DefaultAllowedHeaders + ",X-Custom-Header,X-Requested-With",   // allowed headers
		MaxAge:           3000, // indicates how long the results of a preflight request can be cached (default 1800)
		ExposedHeaders:   "X-Custom-Header", // exposer headers
		AllowCredentials: true, // indicates that request whether include credentials
		ForwardRequest:   true, // if true, preflight request are forwarded to handler (dafault false)
		Logger:           logger, // optional logger
	})

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			w.Header().Set("Content-Type", "application/json")
			w.Write([]byte("{\"hello\": \"world\"}"))
			return
		}
		if r.Method == "OPTIONS" {
			w.Header().Set("Content-Type", "application/json")
			w.Write([]byte("{\"forward\": \"request\"}"))
			return
		}
	})

	http.ListenAndServe(":3000", corsMiddleware(handler))
}

And now, test preflight request:

curl -H "Origin: http://foobar.com" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: X-Requested-With" -X OPTIONS --verbose   http://localhost:3000  

Documentation

Overview

Package cors CORS filter middleware for Golang `net/http` handler. Like some other CORS filters (e.g. the Jetty's CORS filter), you can define your AllowedMethod list, even non standard. As default, AllowedMethods list is "GET,POST,HEAD,OPTIONS".

Index

Constants

View Source
const (
	// DefaultAllowedOrigin default origin allowed, as default all origins are allowed
	DefaultAllowedOrigin = "*"

	// DefaultAllowedMethods default allowed method, "OPTIONS" method must added if you want handle preflight request
	DefaultAllowedMethods = http.MethodGet + "," + http.MethodPost + "," + http.MethodHead + "," + http.MethodOptions

	// DefaultAllowedHeaders default allowed headers
	DefaultAllowedHeaders = "Origin,Accept,Content-Type,Accept-Language,Content-Language,Last-Event-ID"

	// DefaultMaxAge default number of seconds that preflight requests can be cached by the client.
	DefaultMaxAge = 1800

	// AccessControlAllowOrigin header
	AccessControlAllowOrigin = "Access-Control-Allow-Origin"

	// AccessControlExposeHeaders header
	AccessControlExposeHeaders = "Access-Control-Expose-Headers"

	// AccessControlControlMaxAge header
	AccessControlControlMaxAge = "Access-Control-Max-Age"

	// AccessControlAllowMethods header
	AccessControlAllowMethods = "Access-Control-Allow-Methods"

	// AccessControlAllowHeaders header
	AccessControlAllowHeaders = "Access-Control-Allow-Headers"

	// AccessControlAllowCredentials header
	AccessControlAllowCredentials = "Access-Control-Allow-Credentials"

	// AccessControlRequestMethod header
	AccessControlRequestMethod = "Access-Control-Request-Method"

	// AccessControlRequestHeaders header
	AccessControlRequestHeaders = "Access-Control-Request-Headers"

	// OriginHeader header
	OriginHeader = "Origin"

	// AcceptHeader header
	AcceptHeader = "Accept"

	// ContentTypeHeader header
	ContentTypeHeader = "Content-Type"

	// AllowHeader header
	AllowHeader = "Allow"

	// VaryHeader header
	VaryHeader = "Vary"

	// HostHeader header
	HostHeader = "Header"

	// OriginMatchAll header
	OriginMatchAll = "*"
)

Variables

This section is empty.

Functions

func Filter

func Filter(config Config) (fn func(next http.Handler) http.Handler)

Filter cors filter middleware

Types

type Config

type Config struct {
	// AllowedOrigins comma separated list of allowed origins (default "*"), may contain whildchar ("*") for e.g. http://*.example.com
	AllowedOrigins,

	AllowedMethods,

	AllowedHeaders,

	ExposedHeaders string
	// MaxAge in seconds (exposed only if > 0) indicates how long the results of a preflight request can be cached
	MaxAge int
	// AllowCredentials if true, indicates that request whether include credentials
	AllowCredentials bool
	// ForwardRequest forward request after preflight
	ForwardRequest bool
	// Logger optional logger
	Logger *log.Logger
}

Config cors filter configuration

Directories

Path Synopsis
examples
chi command
stdmux command

Jump to

Keyboard shortcuts

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