Add option to enable a simple CORS implementation for the api server

This commit is contained in:
Jessica Forrester
2014-09-02 12:28:24 -04:00
parent a4e3a4e351
commit 8723eece49
11 changed files with 161 additions and 59 deletions

View File

@@ -18,10 +18,8 @@ package apiserver
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"runtime/debug"
"strings"
"time"
@@ -57,8 +55,11 @@ func Handle(storage map[string]RESTStorage, codec runtime.Codec, prefix string)
mux := http.NewServeMux()
group.InstallREST(mux, prefix)
InstallSupport(mux)
return &defaultAPIServer{RecoverPanics(mux), group}
handler := RecoverPanics(mux)
if enableCORS {
handler = CORS(handler, []string{".*"}, nil, nil, "true")
}
return &defaultAPIServer{handler, group}
}
// APIGroup is a http.Handler that exposes multiple RESTStorage objects
@@ -116,33 +117,6 @@ func InstallSupport(mux mux) {
mux.HandleFunc("/", handleIndex)
}
// RecoverPanics wraps an http Handler to recover and log panics.
func RecoverPanics(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer func() {
if x := recover(); x != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "apis panic. Look in log for details.")
glog.Infof("APIServer panic'd on %v %v: %#v\n%s\n", req.Method, req.RequestURI, x, debug.Stack())
}
}()
defer httplog.NewLogged(req, &w).StacktraceWhen(
httplog.StatusIsNot(
http.StatusOK,
http.StatusAccepted,
http.StatusMovedPermanently,
http.StatusTemporaryRedirect,
http.StatusConflict,
http.StatusNotFound,
StatusUnprocessableEntity,
),
).Log()
// Dispatch to the internal handler
handler.ServeHTTP(w, req)
})
}
// handleVersion writes the server's version information.
func handleVersion(w http.ResponseWriter, req *http.Request) {
writeRawJSON(http.StatusOK, version.Get(), w)