cors

package
v0.18.1 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2026 License: MIT Imports: 5 Imported by: 2

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AllowOriginFunc added in v0.12.2

type AllowOriginFunc func(origin string) bool
Example

Decide allowed origins dynamically by supplying a custom AllowOriginFunc — here, any subdomain of example.com. AllowOrigins is just a convenience that builds one of these from a fixed list.

package main

import (
	"strings"
	"time"

	"github.com/moonrhythm/parapet"
	"github.com/moonrhythm/parapet/pkg/cors"
)

func main() {
	s := parapet.New()
	s.Use(&cors.CORS{
		AllowOrigins: cors.AllowOriginFunc(func(origin string) bool {
			return strings.HasSuffix(origin, ".example.com")
		}),
		AllowMethods: []string{"GET", "POST"},
		AllowHeaders: []string{"Authorization", "Content-Type"},
		MaxAge:       time.Hour,
	})
}

func AllowOrigins added in v0.12.2

func AllowOrigins(origins ...string) AllowOriginFunc
Example

Restrict to an explicit allow-list of origins and turn on credentials. With a non-wildcard origin the browser will accept Access-Control-Allow-Credentials, so cookies and Authorization headers are honored on cross-origin requests.

package main

import (
	"time"

	"github.com/moonrhythm/parapet"
	"github.com/moonrhythm/parapet/pkg/cors"
)

func main() {
	s := parapet.New()
	s.Use(&cors.CORS{
		AllowOrigins:     cors.AllowOrigins("https://app.example.com", "https://admin.example.com"),
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
		AllowHeaders:     []string{"Authorization", "Content-Type"},
		ExposeHeaders:    []string{"X-Request-Id"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour, // cache the preflight result this long
	})
}

type CORS

type CORS struct {
	AllowOrigins     AllowOriginFunc
	AllowMethods     []string
	AllowHeaders     []string
	ExposeHeaders    []string
	MaxAge           time.Duration
	AllowAllOrigins  bool
	AllowCredentials bool
}

CORS middleware

func New

func New() *CORS

New creates new default cors middleware for public api

Example

Apply the permissive default policy for a public API: any origin is allowed, credentials are not. cors.New emits Access-Control-Allow-Origin: * and answers preflight (OPTIONS) requests for you.

package main

import (
	"github.com/moonrhythm/parapet"
	"github.com/moonrhythm/parapet/pkg/cors"
)

func main() {
	s := parapet.New()
	s.Use(cors.New())
	// s.Use(upstream.SingleHost(...)) — the handler the policy guards.
}

func (CORS) ServeHandler

func (m CORS) ServeHandler(h http.Handler) http.Handler

ServeHandler implements middleware interface

Jump to

Keyboard shortcuts

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