Skip to content

Commit

Permalink
fixed #labstack#743
Browse files Browse the repository at this point in the history
Signed-off-by: Vishal Rana <[email protected]>
  • Loading branch information
vishr committed Nov 21, 2016
1 parent d4dff98 commit fe269b3
Show file tree
Hide file tree
Showing 9 changed files with 91 additions and 65 deletions.
25 changes: 13 additions & 12 deletions middleware/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ type (
Skipper Skipper

// AllowOrigin defines a list of origins that may access the resource.
// Optional. If request header `Origin` is set, value is []string{"<Origin>"}
// else []string{"*"}.
// Optional. Default value []string{"*"}.
AllowOrigins []string `json:"allow_origins"`

// AllowMethods defines a list methods allowed when accessing the resource.
Expand Down Expand Up @@ -52,6 +51,7 @@ var (
// DefaultCORSConfig is the default CORS middleware config.
DefaultCORSConfig = CORSConfig{
Skipper: defaultSkipper,
AllowOrigins: []string{"*"},
AllowMethods: []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH, echo.POST, echo.DELETE},
}
)
Expand All @@ -69,11 +69,13 @@ func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc {
if config.Skipper == nil {
config.Skipper = DefaultCORSConfig.Skipper
}
if len(config.AllowOrigins) == 0 {
config.AllowOrigins = DefaultCORSConfig.AllowOrigins
}
if len(config.AllowMethods) == 0 {
config.AllowMethods = DefaultCORSConfig.AllowMethods
}

allowedOrigins := strings.Join(config.AllowOrigins, ",")
allowMethods := strings.Join(config.AllowMethods, ",")
allowHeaders := strings.Join(config.AllowHeaders, ",")
exposeHeaders := strings.Join(config.ExposeHeaders, ",")
Expand All @@ -88,21 +90,20 @@ func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc {
req := c.Request()
res := c.Response()
origin := req.Header.Get(echo.HeaderOrigin)
allowOrigin := ""

if allowedOrigins == "" {
if origin != "" {
allowedOrigins = origin
} else {
if !config.AllowCredentials {
allowedOrigins = "*"
}
// Check allowed origins
for _, o := range config.AllowOrigins {
if o == "*" || o == origin {
allowOrigin = o
break
}
}

// Simple request
if req.Method != echo.OPTIONS {
res.Header().Add(echo.HeaderVary, echo.HeaderOrigin)
res.Header().Set(echo.HeaderAccessControlAllowOrigin, allowedOrigins)
res.Header().Set(echo.HeaderAccessControlAllowOrigin, allowOrigin)
if config.AllowCredentials {
res.Header().Set(echo.HeaderAccessControlAllowCredentials, "true")
}
Expand All @@ -116,7 +117,7 @@ func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc {
res.Header().Add(echo.HeaderVary, echo.HeaderOrigin)
res.Header().Add(echo.HeaderVary, echo.HeaderAccessControlRequestMethod)
res.Header().Add(echo.HeaderVary, echo.HeaderAccessControlRequestHeaders)
res.Header().Set(echo.HeaderAccessControlAllowOrigin, allowedOrigins)
res.Header().Set(echo.HeaderAccessControlAllowOrigin, allowOrigin)
res.Header().Set(echo.HeaderAccessControlAllowMethods, allowMethods)
if config.AllowCredentials {
res.Header().Set(echo.HeaderAccessControlAllowCredentials, "true")
Expand Down
17 changes: 5 additions & 12 deletions middleware/cors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,29 +12,22 @@ import (
func TestCORS(t *testing.T) {
e := echo.New()

// Origin origin
// Wildcard origin
req, _ := http.NewRequest(echo.GET, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
h := CORS()(echo.NotFoundHandler)
req.Header.Set(echo.HeaderOrigin, "localhost")
h(c)
assert.Equal(t, "localhost", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))

// Wildcard origin
req, _ = http.NewRequest(echo.GET, "/", nil)
rec = httptest.NewRecorder()
c = e.NewContext(req, rec)
h = CORS()(echo.NotFoundHandler)
h(c)
assert.Equal(t, "*", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))

// Simple request
// Allow origins
req, _ = http.NewRequest(echo.GET, "/", nil)
rec = httptest.NewRecorder()
c = e.NewContext(req, rec)
h = CORSWithConfig(CORSConfig{
AllowOrigins: []string{"localhost"},
})(echo.NotFoundHandler)
req.Header.Set(echo.HeaderOrigin, "localhost")
h = CORS()(echo.NotFoundHandler)
h(c)
assert.Equal(t, "localhost", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))

Expand Down
2 changes: 1 addition & 1 deletion website/config.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"baseurl": "https://echo.labstack.com/",
"baseurl": "https://echo.labstack.com",
"languageCode": "en-us",
"title": "Echo - Fast and unfancy HTTP server framework for Go (Golang)",
"canonifyurls": true,
Expand Down
68 changes: 34 additions & 34 deletions website/content/middleware/cors.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,41 +30,41 @@ e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
## Configuration

```go
// CORSConfig defines the config for CORS middleware.
CORSConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper

// AllowOrigin defines a list of origins that may access the resource.
// Optional. If request header `Origin` is set, value is []string{"<Origin>"}
// else []string{"*"}.
AllowOrigins []string `json:"allow_origins"`

// AllowMethods defines a list methods allowed when accessing the resource.
// This is used in response to a preflight request.
// Optional. Default value DefaultCORSConfig.AllowMethods.
AllowMethods []string `json:"allow_methods"`

// AllowHeaders defines a list of request headers that can be used when
// making the actual request. This in response to a preflight request.
// Optional. Default value []string{}.
AllowHeaders []string `json:"allow_headers"`

// AllowCredentials indicates whether or not the response to the request
// can be exposed when the credentials flag is true. When used as part of
// a response to a preflight request, this indicates whether or not the
// actual request can be made using credentials.
// Optional. Default value false.
AllowCredentials bool `json:"allow_credentials"`

// ExposeHeaders defines a whitelist headers that clients are allowed to
// access.
// Optional. Default value []string{}.
ExposeHeaders []string `json:"expose_headers"`

// MaxAge indicates how long (in seconds) the results of a preflight request
// can be cached.
// Optional. Default value 0.
MaxAge int `json:"max_age"`
// Skipper defines a function to skip middleware.
Skipper Skipper

// AllowOrigin defines a list of origins that may access the resource.
// Optional. Default value []string{"*"}.
AllowOrigins []string `json:"allow_origins"`

// AllowMethods defines a list methods allowed when accessing the resource.
// This is used in response to a preflight request.
// Optional. Default value DefaultCORSConfig.AllowMethods.
AllowMethods []string `json:"allow_methods"`

// AllowHeaders defines a list of request headers that can be used when
// making the actual request. This in response to a preflight request.
// Optional. Default value []string{}.
AllowHeaders []string `json:"allow_headers"`

// AllowCredentials indicates whether or not the response to the request
// can be exposed when the credentials flag is true. When used as part of
// a response to a preflight request, this indicates whether or not the
// actual request can be made using credentials.
// Optional. Default value false.
AllowCredentials bool `json:"allow_credentials"`

// ExposeHeaders defines a whitelist headers that clients are allowed to
// access.
// Optional. Default value []string{}.
ExposeHeaders []string `json:"expose_headers"`

// MaxAge indicates how long (in seconds) the results of a preflight request
// can be cached.
// Optional. Default value 0.
MaxAge int `json:"max_age"`
}
```

Expand Down
25 changes: 25 additions & 0 deletions website/data/index.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,27 @@
h1 = "Echo"
h2 = "High performance, extensible, minimalist web framework for Go"
[[features]]
icon = "rocket"
title = "Optimized Router"
text = "Highly optimized HTTP router which smartly prioritize routes"
[[features]]
icon = "cloud"
title = "RESTful API"
text = "Build robust and scalable RESTful API"
[[features]]
icon = "license"
title = "Automatic TLS"
text = "Automatically install TLS certificates from Let's Encrypt"
[[features]]
icon = "funnel"
title = "Middleware Levels"
text = "Define middleware at root, group or route level"
[[features]]
icon = "sync"
title = "Data Binding"
text = "Data binding for JSON, XML and form payload"
[[features]]
icon = "code"
title = "Templates"
text = "Template rendering with any template engine"

2 changes: 1 addition & 1 deletion website/layouts/_default/single.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<div class="w3-main w3-padding-64">
{{ partial "ad.html" }}
<div class="w3-row-padding">
<div class="w3-col m9 l9">
<div class="w3-col m10 l10">
{{ partial "notice.html" }}
<article class="content">
<section>
Expand Down
13 changes: 10 additions & 3 deletions website/layouts/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<div class="w3-container w3-content w3-padding-64">
{{ partial "ad.html" }}
<div class="w3-row-padding">
<div class="w3-col m9 l9">
<div class="w3-col m10 l10">
<div class="hero">
<h1>{{ .Site.Data.index.h1 }}</h1>
<h2>{{ .Site.Data.index.h2 }}</h2>
Expand All @@ -23,8 +23,15 @@ <h2>{{ .Site.Data.index.h2 }}</h2>

<div class="features">
{{ range .Site.Data.index.features }}
<div class="feature">
</div>
<div class="feature">
<img src="/images/{{ .icon }}.svg">
<h3>
{{ .title }}
</h3>
<p>
{{ .text | safeHTML }}
</p>
</div>
{{ end }}
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion website/layouts/partials/sidenav.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<nav id="sidenav" class="w3-sidenav w3-collapse">
<nav id="sidenav" class="w3-sidenav w3-collapse w3-card-2">
<span class="w3-closenav w3-xxlarge w3-hide-large" onclick="closeSidenav()">
&times;
</span>
Expand Down
2 changes: 1 addition & 1 deletion website/layouts/single/single.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
{{ partial "topnav.html" . }}
<div class="w3-container w3-content w3-padding-64">
<div class="w3-row-padding">
<div class="w3-col m9 l9">
<div class="w3-col m10 l10">
<h1>{{ .Title }}</h1>
{{ .Content }}
</div>
Expand Down

0 comments on commit fe269b3

Please sign in to comment.