Skip to content
This repository has been archived by the owner on Sep 15, 2020. It is now read-only.

add cors headers to ui/webserver fn responses #741

Merged
merged 2 commits into from
Jun 13, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions ui/webserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ func NewWebServer(h *holo.Holochain, port string) *WebServer {
return &w
}

// Helper for managing CORS responses
func AddCors(w http.ResponseWriter) {
headers := w.Header()
headers.Set("Access-Control-Allow-Origin", "*")
headers.Set("Access-Control-Allow-Headers", "Content-Type")
}

//Start starts up a web server and returns a channel which will shutdown
func (ws *WebServer) Start() {

Expand Down Expand Up @@ -104,6 +111,11 @@ func (ws *WebServer) Start() {

ws.log.Logf("REQUEST:%v", r)

AddCors(w)
if r.Method == "OPTIONS" {
return
}

body, err := ioutil.ReadAll(r.Body)
if err != nil {
errCode, err = mkErr("unable to read body", 500)
Expand Down Expand Up @@ -190,6 +202,11 @@ func (ws *WebServer) Start() {
}
}()

AddCors(w)
if r.Method == "OPTIONS" {
return
}

body, err := ioutil.ReadAll(r.Body)
if err != nil {
errCode, err = mkErr("unable to read body", 500)
Expand Down
9 changes: 9 additions & 0 deletions ui/webserver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ func TestWebServer(t *testing.T) {
So(string(b), ShouldEqual, "en")
})

Convey("it should return CORS headers when calling functions", t, func() {
body := bytes.NewBuffer([]byte("language"))
resp, err := http.Post("http://0.0.0.0:31415/fn/jsSampleZome/getProperty", "", body)
So(err, ShouldBeNil)
defer resp.Body.Close()
_, corsPresent := resp.Header["Access-Control-Allow-Origin"]
So(corsPresent, ShouldEqual, true)
})

Convey("it should return Holochain errors from call functions as 400", t, func() {
body := bytes.NewBuffer([]byte("2"))
resp, err := http.Post("http://0.0.0.0:31415/fn/jsSampleZome/addOdd", "", body)
Expand Down