originmatcher

package module
v0.0.0-...-274b9ed Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2022 License: MIT Imports: 8 Imported by: 3

README

Match HTTP Origin

Read the test case to see what it does.

Documentation

Example

Suppose you host your frontend on https://www.example.com and https://example.com, while your backend is https://api.example.com. Your backend server must serve OPTIONS request with allow-control-allow-origin echoing the value of origin.

var matcher *originmatcher.T

func init() {
	matcher, _ = originmatcher.Parse("https://www.example.com,https://example.com")
}

func handler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "OPTIONS" {
		origin := r.Header.Get("origin")
		if matcher.MatchOrigin(origin) {
			w.Header().Set("allow-control-allow-origin", origin)
			// Set more CORS headers as you like
		} else {
			// Unknown cross-origin request!
		}
	} else {
		// Serve your request as normal
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckValidSpecStrict

func CheckValidSpecStrict(spec string) (err error)

CheckValidSpecStrict checks if spec is valid and does not contain extra information.

Types

type T

type T struct {
	// contains filtered or unexported fields
}

func New

func New(specs []string) (*T, error)

New creates a T from a slice of origin spec. An origin spec consist of a mandatory host, with optionally scheme and port. As a special case, "*" matches any origin. An origin spec is lenient that extra userinfo, path, query or fragment are ignored silently.

func Parse

func Parse(s string) (*T, error)

Parse parses s into T, where s is comma-separated origin specs.

func (*T) MatchOrigin

func (t *T) MatchOrigin(s string) bool

MatchOrigin tells whether s is an allowed origin. s typically should be the value of HTTP header "Origin". MatchOrigin is lenient that extra userinfo, path , query or fragment in s are ignored silently.

func (*T) String

func (t *T) String() string

String returns the original string that was parsed into t.

Jump to

Keyboard shortcuts

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