Skip to content

Commit

Permalink
Add origin option so CORS can be configured to a specified policy (#73)
Browse files Browse the repository at this point in the history
  • Loading branch information
scottmmjackson authored and igm committed Jun 21, 2019
1 parent 1840ed9 commit 7e107b4
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 12 deletions.
2 changes: 1 addition & 1 deletion sockjs/handler.go
Expand Up @@ -37,7 +37,7 @@ func newHandler(prefix string, opts Options, handlerFunc func(Session)) *handler
handlerFunc: handlerFunc,
sessions: make(map[string]*session),
}

xhrCors := xhrCorsFactory(opts.Origin)
sessionPrefix := prefix + "/[^/.]+/[^/.]+"
h.mappings = []*mapping{
newMapping("GET", prefix+"[/]?$", welcomeHandler),
Expand Down
3 changes: 3 additions & 0 deletions sockjs/options.go
Expand Up @@ -58,6 +58,9 @@ type Options struct {
// This setting controls if the server should set this cookie to a dummy value.
// By default setting JSessionID cookie is disabled. More sophisticated behaviour can be achieved by supplying a function.
JSessionID func(http.ResponseWriter, *http.Request)
// CORS origin to be set on outgoing responses. If set to the empty string, it will default to the
// incoming `Origin` header, or "*" if the Origin header isn't set.
Origin string
}

// DefaultOptions is a convenient set of options to be used for sockjs
Expand Down
27 changes: 16 additions & 11 deletions sockjs/web.go
Expand Up @@ -6,18 +6,23 @@ import (
"time"
)

func xhrCors(rw http.ResponseWriter, req *http.Request) {
header := rw.Header()
origin := req.Header.Get("origin")
if origin == "" {
origin = "*"
func xhrCorsFactory(defaultOrigin string) func(rw http.ResponseWriter, req *http.Request) {
return func(rw http.ResponseWriter, req *http.Request) {
header := rw.Header()
origin := defaultOrigin
if origin == "" {
origin = req.Header.Get("origin")
}
if origin == "" || origin == "null" {
origin = "*"
}
header.Set("Access-Control-Allow-Origin", origin)

if allowHeaders := req.Header.Get("Access-Control-Request-Headers"); allowHeaders != "" && allowHeaders != "null" {
header.Add("Access-Control-Allow-Headers", allowHeaders)
}
header.Set("Access-Control-Allow-Credentials", "true")
}
header.Set("Access-Control-Allow-Origin", origin)

if allowHeaders := req.Header.Get("Access-Control-Request-Headers"); allowHeaders != "" && allowHeaders != "null" {
header.Add("Access-Control-Allow-Headers", allowHeaders)
}
header.Set("Access-Control-Allow-Credentials", "true")
}

func xhrOptions(rw http.ResponseWriter, req *http.Request) {
Expand Down
1 change: 1 addition & 0 deletions sockjs/web_test.go
Expand Up @@ -10,6 +10,7 @@ import (
func TestXhrCors(t *testing.T) {
recorder := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
xhrCors := xhrCorsFactory("")
xhrCors(recorder, req)
acao := recorder.Header().Get("access-control-allow-origin")
if acao != "*" {
Expand Down

0 comments on commit 7e107b4

Please sign in to comment.