Skip to content
This repository has been archived by the owner on Oct 22, 2019. It is now read-only.

Commit

Permalink
fix cors
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastianbenz committed Dec 20, 2016
1 parent 7cf27e0 commit 17d6d37
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 18 deletions.
32 changes: 15 additions & 17 deletions backend/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
package backend

import (
"bytes"
"fmt"
"net/http"
"strings"
Expand All @@ -32,17 +31,6 @@ func IsInsecureRequest(r *http.Request) bool {
return r.TLS == nil && !strings.HasPrefix(r.Host, "localhost")
}

func buildSourceOrigin(host string) string {
var sourceOrigin bytes.Buffer
if strings.HasPrefix(host, "localhost") {
sourceOrigin.WriteString("http://")
} else {
sourceOrigin.WriteString("https://")
}
sourceOrigin.WriteString(host)
return sourceOrigin.String()
}

func isFormPostRequest(method string, w http.ResponseWriter) bool {
if method != "POST" {
http.Error(w, "post only", http.StatusMethodNotAllowed)
Expand All @@ -51,12 +39,22 @@ func isFormPostRequest(method string, w http.ResponseWriter) bool {
return true
}

func buildSourceOrigin(host string) string {
if strings.HasPrefix(host, "localhost") {
return "http://" + host
} else {
return "https://" + host
}
}

func EnableCors(w http.ResponseWriter, r *http.Request) {
sourceOrigin := buildSourceOrigin(r.Host)
w.Header().Set("Access-Control-Allow-Origin", sourceOrigin)
w.Header().Set("Access-Control-Expose-Headers", "AMP-Access-Control-Allow-Source-Origin")
w.Header().Set("AMP-Access-Control-Allow-Source-Origin", sourceOrigin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "POST, GET")
w.Header().Set("Access-Control-Expose-Headers", "AMP-Access-Control-Allow-Source-Origin")
w.Header().Set("AMP-Access-Control-Allow-Source-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
}

func SetContentTypeJson(w http.ResponseWriter) {
Expand Down
2 changes: 1 addition & 1 deletion gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ gulp.task('default', 'Run a webserver and watch for changes', [
'serve']);

gulp.task('backend:watch', 'run the go backend and watch for changes', function(callback) {
config.host = 'http://localhost:8080';
runSequence(
'build',
'watch',
Expand All @@ -366,7 +367,6 @@ gulp.task('backend:watch', 'run the go backend and watch for changes', function(
});

gulp.task('backend:serve', 'Run the go backend', function(){
config.host = 'http://localhost:8080';
return run('goapp serve').exec();
});

Expand Down

0 comments on commit 17d6d37

Please sign in to comment.