hybridgroup.gobot/api/cors.go

57 lines
1.2 KiB
Go
Raw Normal View History

2014-09-18 07:20:18 +08:00
package api
import (
"regexp"
"strings"
)
2014-09-18 07:20:18 +08:00
type CORS struct {
AllowOrigins []string
AllowHeaders []string
AllowMethods []string
ContentType string
allowOriginPatterns []string
2014-09-18 07:20:18 +08:00
}
func NewCORS(allowedOrigins []string) *CORS {
cors := &CORS{
2014-09-18 07:20:18 +08:00
AllowOrigins: allowedOrigins,
AllowMethods: []string{"GET", "POST"},
AllowHeaders: []string{"Origin", "Content-Type"},
ContentType: "application/json; charset=utf-8",
2014-09-18 07:20:18 +08:00
}
cors.generatePatterns()
return cors
2014-09-18 07:20:18 +08:00
}
func (c *CORS) isOriginAllowed(origin string) (allowed bool) {
for _, allowedOriginPattern := range c.allowOriginPatterns {
allowed, _ = regexp.MatchString(allowedOriginPattern, origin)
if allowed {
return
2014-09-18 07:20:18 +08:00
}
}
return
}
func (c *CORS) generatePatterns() {
if c.AllowOrigins != nil {
for _, origin := range c.AllowOrigins {
pattern := regexp.QuoteMeta(origin)
pattern = strings.Replace(pattern, "\\*", ".*", -1)
pattern = strings.Replace(pattern, "\\?", ".", -1)
c.allowOriginPatterns = append(c.allowOriginPatterns, "^"+pattern+"$")
}
}
}
func (c *CORS) AllowedHeaders() string {
return strings.Join(c.AllowHeaders, ",")
}
func (c *CORS) AllowedMethods() string {
return strings.Join(c.AllowMethods, ",")
2014-09-18 07:20:18 +08:00
}