change dep to go module

This commit is contained in:
Jay
2018-11-16 11:10:19 +08:00
parent c21d43a691
commit ac1dcb7827
431 changed files with 43733 additions and 4366 deletions
+3
View File
@@ -5,6 +5,9 @@ go:
- 1.6.x
- 1.7.x
- 1.8.x
- 1.9.x
- 1.10.x
- 1.11.x
- tip
script:
+3 -4
View File
@@ -15,13 +15,13 @@ Gin middleware/handler to enable CORS support.
Download and install it:
```sh
$ go get gopkg.in/gin-contrib/cors.v1
$ go get github.com/gin-contrib/cors
```
Import it in your code:
```go
import "gopkg.in/gin-contrib/cors.v1"
import "github.com/gin-contrib/cors"
```
### Canonical example:
@@ -32,7 +32,7 @@ package main
import (
"time"
"gopkg.in/gin-contrib/cors.v1"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
@@ -69,7 +69,6 @@ func main() {
// - Preflight requests cached for 12 hours
config := cors.DefaultConfig()
config.AllowOrigins = []string{"http://google.com"}
config.AddAllowOrigins("http://facebook.com")
// config.AllowOrigins == []string{"http://google.com", "http://facebook.com"}
router.Use(cors.New(config))
+52 -1
View File
@@ -2,6 +2,7 @@ package cors
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
@@ -14,12 +15,34 @@ type cors struct {
exposeHeaders []string
normalHeaders http.Header
preflightHeaders http.Header
wildcardOrigins [][]string
}
var (
DefaultSchemas = []string{
"http://",
"https://",
}
ExtensionSchemas = []string{
"chrome-extension://",
"safari-extension://",
"moz-extension://",
"ms-browser-extension://",
}
FileSchemas = []string{
"file://",
}
WebSocketSchemas = []string{
"ws://",
"wss://",
}
)
func newCors(config Config) *cors {
if err := config.Validate(); err != nil {
panic(err.Error())
}
return &cors{
allowOriginFunc: config.AllowOriginFunc,
allowAllOrigins: config.AllowAllOrigins,
@@ -27,6 +50,7 @@ func newCors(config Config) *cors {
allowOrigins: normalize(config.AllowOrigins),
normalHeaders: generateNormalHeaders(config),
preflightHeaders: generatePreflightHeaders(config),
wildcardOrigins: config.parseWildcardRules(),
}
}
@@ -36,6 +60,14 @@ func (cors *cors) applyCors(c *gin.Context) {
// request is not a CORS request
return
}
host := c.Request.Header.Get("Host")
if origin == "http://"+host || origin == "https://"+host {
// request is not a CORS request but have origin header.
// for example, use fetch api
return
}
if !cors.validateOrigin(origin) {
c.AbortWithStatus(http.StatusForbidden)
return
@@ -43,7 +75,7 @@ func (cors *cors) applyCors(c *gin.Context) {
if c.Request.Method == "OPTIONS" {
cors.handlePreflight(c)
defer c.AbortWithStatus(200)
defer c.AbortWithStatus(http.StatusNoContent) // Using 204 is better than 200 when the request status is OPTIONS
} else {
cors.handleNormal(c)
}
@@ -53,6 +85,22 @@ func (cors *cors) applyCors(c *gin.Context) {
}
}
func (cors *cors) validateWildcardOrigin(origin string) bool {
for _, w := range cors.wildcardOrigins {
if w[0] == "*" && strings.HasSuffix(origin, w[1]) {
return true
}
if w[1] == "*" && strings.HasPrefix(origin, w[0]) {
return true
}
if strings.HasPrefix(origin, w[0]) && strings.HasSuffix(origin, w[1]) {
return true
}
}
return false
}
func (cors *cors) validateOrigin(origin string) bool {
if cors.allowAllOrigins {
return true
@@ -62,6 +110,9 @@ func (cors *cors) validateOrigin(origin string) bool {
return true
}
}
if len(cors.wildcardOrigins) > 0 && cors.validateWildcardOrigin(origin) {
return true
}
if cors.allowOriginFunc != nil {
return cors.allowOriginFunc(origin)
}
+72 -6
View File
@@ -14,7 +14,7 @@ type Config struct {
// AllowedOrigins is a list of origins a cross-domain request can be executed from.
// If the special "*" value is present in the list, all origins will be allowed.
// Default value is ["*"]
// Default value is []
AllowOrigins []string
// AllowOriginFunc is a custom function to validate the origin. It take the origin
@@ -28,8 +28,6 @@ type Config struct {
// AllowedHeaders is list of non simple headers the client is allowed to use with
// cross-domain requests.
// If the special "*" value is present in the list, all headers will be allowed.
// Default value is [] but "Origin" is always appended to the list.
AllowHeaders []string
// AllowCredentials indicates whether the request can include user credentials like
@@ -43,6 +41,18 @@ type Config struct {
// MaxAge indicates how long (in seconds) the results of a preflight request
// can be cached
MaxAge time.Duration
// Allows to add origins like http://some-domain/*, https://api.* or http://some.*.subdomain.com
AllowWildcard bool
// Allows usage of popular browser extensions schemas
AllowBrowserExtensions bool
// Allows usage of WebSocket protocol
AllowWebSockets bool
// Allows usage of file:// schema (dangerous!) use it only when you 100% sure it's needed
AllowFiles bool
}
// AddAllowMethods is allowed to add custom methods
@@ -60,6 +70,30 @@ func (c *Config) AddExposeHeaders(headers ...string) {
c.ExposeHeaders = append(c.ExposeHeaders, headers...)
}
func (c Config) getAllowedSchemas() []string {
allowedSchemas := DefaultSchemas
if c.AllowBrowserExtensions {
allowedSchemas = append(allowedSchemas, ExtensionSchemas...)
}
if c.AllowWebSockets {
allowedSchemas = append(allowedSchemas, WebSocketSchemas...)
}
if c.AllowFiles {
allowedSchemas = append(allowedSchemas, FileSchemas...)
}
return allowedSchemas
}
func (c Config) validateAllowedSchemas(origin string) bool {
allowedSchemas := c.getAllowedSchemas()
for _, schema := range allowedSchemas {
if strings.HasPrefix(origin, schema) {
return true
}
}
return false
}
// Validate is check configuration of user defined.
func (c Config) Validate() error {
if c.AllowAllOrigins && (c.AllowOriginFunc != nil || len(c.AllowOrigins) > 0) {
@@ -69,17 +103,49 @@ func (c Config) Validate() error {
return errors.New("conflict settings: all origins disabled")
}
for _, origin := range c.AllowOrigins {
if !strings.HasPrefix(origin, "http://") && !strings.HasPrefix(origin, "https://") {
return errors.New("bad origin: origins must include http:// or https://")
if !strings.Contains(origin, "*") && !c.validateAllowedSchemas(origin) {
return errors.New("bad origin: origins must contain '*' or include " + strings.Join(c.getAllowedSchemas(), ","))
}
}
return nil
}
func (c Config) parseWildcardRules() [][]string {
var wRules [][]string
if !c.AllowWildcard {
return wRules
}
for _, o := range c.AllowOrigins {
if !strings.Contains(o, "*") {
continue
}
if c := strings.Count(o, "*"); c > 1 {
panic(errors.New("only one * is allowed").Error())
}
i := strings.Index(o, "*")
if i == 0 {
wRules = append(wRules, []string{"*", o[1:]})
continue
}
if i == (len(o) - 1) {
wRules = append(wRules, []string{o[:i-1], "*"})
continue
}
wRules = append(wRules, []string{o[:i], o[i+1:]})
}
return wRules
}
// DefaultConfig returns a generic default configuration mapped to localhost.
func DefaultConfig() Config {
return Config{
AllowMethods: []string{"GET", "POST", "PUT", "HEAD"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"},
AllowHeaders: []string{"Origin", "Content-Length", "Content-Type"},
AllowCredentials: false,
MaxAge: 12 * time.Hour,