Merge pull request #153 from philips/add-cors

feat(etcd_handlers): enable CORS
release-0.4
Xiang Li 2013-09-03 16:10:03 -07:00
commit dee496b5ae
2 changed files with 46 additions and 0 deletions

27
etcd.go
View File

@ -3,9 +3,11 @@ package main
import (
"crypto/tls"
"flag"
"fmt"
"github.com/coreos/etcd/store"
"github.com/coreos/go-raft"
"io/ioutil"
"net/url"
"os"
"strings"
"time"
@ -40,6 +42,9 @@ var (
maxClusterSize int
cpuprofile string
cors string
corsList map[string]bool
)
func init() {
@ -77,6 +82,8 @@ func init() {
flag.IntVar(&maxClusterSize, "maxsize", 9, "the max size of the cluster")
flag.StringVar(&cpuprofile, "cpuprofile", "", "write cpu profile to file")
flag.StringVar(&cors, "cors", "", "whitelist origins for cross-origin resource sharing (e.g. '*' or 'http://localhost:8001,etc')")
}
const (
@ -152,6 +159,8 @@ func main() {
raft.SetLogLevel(raft.Debug)
}
parseCorsFlag()
if machines != "" {
cluster = strings.Split(machines, ",")
} else if machinesFile != "" {
@ -206,3 +215,21 @@ func main() {
e.ListenAndServe()
}
// parseCorsFlag gathers up the cors whitelist and puts it into the corsList.
func parseCorsFlag() {
if cors != "" {
corsList = make(map[string]bool)
list := strings.Split(cors, ",")
for _, v := range list {
fmt.Println(v)
if v != "*" {
_, err := url.Parse(v)
if err != nil {
panic(fmt.Sprintf("bad cors url: %s", err))
}
}
corsList[v] = true
}
}
}

View File

@ -29,7 +29,26 @@ func NewEtcdMuxer() *http.ServeMux {
type errorHandler func(http.ResponseWriter, *http.Request) error
// addCorsHeader parses the request Origin header and loops through the user
// provided allowed origins and sets the Access-Control-Allow-Origin header if
// there is a match.
func addCorsHeader(w http.ResponseWriter, r *http.Request) {
val, ok := corsList["*"]
if val && ok {
w.Header().Add("Access-Control-Allow-Origin", "*")
return
}
requestOrigin := r.Header.Get("Origin")
val, ok = corsList[requestOrigin]
if val && ok {
w.Header().Add("Access-Control-Allow-Origin", requestOrigin)
return
}
}
func (fn errorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
addCorsHeader(w, r)
if e := fn(w, r); e != nil {
if etcdErr, ok := e.(etcdErr.Error); ok {
debug("Return error: ", etcdErr.Error())