github.com/brycereitano/goa@v0.0.0-20170315073847-8ffa6c85e265/cors/cors.go (about)

     1  /*
     2  Package cors provides the means for implementing the server side of CORS,
     3  see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
     4  */
     5  package cors
     6  
     7  import (
     8  	"net/http"
     9  	"regexp"
    10  	"strings"
    11  
    12  	"golang.org/x/net/context"
    13  
    14  	"github.com/goadesign/goa"
    15  )
    16  
    17  // key is the private type used to key context values.
    18  type key string
    19  
    20  // OriginKey is the context key used to store the request origin match
    21  const OriginKey key = "origin"
    22  
    23  // MatchOrigin returns true if the given Origin header value matches the
    24  // origin specification.
    25  // Spec can be one of:
    26  // - a plain string identifying an origin. eg http://swagger.goa.design
    27  // - a plain string containing a wildcard. eg *.goa.design
    28  // - the special string * that matches every host
    29  func MatchOrigin(origin, spec string) bool {
    30  	if spec == "*" {
    31  		return true
    32  	}
    33  
    34  	// Check regular expression
    35  	if strings.HasPrefix(spec, "/") && strings.HasSuffix(spec, "/") {
    36  		stripped := strings.Trim(spec, "/")
    37  		r := regexp.MustCompile(stripped)
    38  		return r.Match([]byte(origin))
    39  	}
    40  
    41  	if !strings.Contains(spec, "*") {
    42  		return origin == spec
    43  	}
    44  	parts := strings.SplitN(spec, "*", 2)
    45  	if !strings.HasPrefix(origin, parts[0]) {
    46  		return false
    47  	}
    48  	if !strings.HasSuffix(origin, parts[1]) {
    49  		return false
    50  	}
    51  	return true
    52  }
    53  
    54  // MatchOriginRegexp returns true if the given Origin header value matches the
    55  // origin specification.
    56  // Spec must be a valid regex
    57  func MatchOriginRegexp(origin string, spec *regexp.Regexp) bool {
    58  	return spec.Match([]byte(origin))
    59  }
    60  
    61  // HandlePreflight returns a simple 200 response. The middleware takes care of handling CORS.
    62  func HandlePreflight() goa.Handler {
    63  	return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
    64  		rw.WriteHeader(200)
    65  		return nil
    66  	}
    67  }