Commit fd9e4610 authored by Matt Bell's avatar Matt Bell Committed by Brian Tiger Chow

commands/http: Allow API requests from whitelisted origins

parent 9acedbbb
...@@ -14,6 +14,7 @@ var log = u.Logger("commands/http") ...@@ -14,6 +14,7 @@ var log = u.Logger("commands/http")
type Handler struct { type Handler struct {
ctx cmds.Context ctx cmds.Context
root *cmds.Command root *cmds.Command
origin string
} }
var ErrNotFound = errors.New("404 page not found") var ErrNotFound = errors.New("404 page not found")
...@@ -29,13 +30,23 @@ var mimeTypes = map[string]string{ ...@@ -29,13 +30,23 @@ var mimeTypes = map[string]string{
cmds.Text: "text/plain", cmds.Text: "text/plain",
} }
func NewHandler(ctx cmds.Context, root *cmds.Command) *Handler { func NewHandler(ctx cmds.Context, root *cmds.Command, origin string) *Handler {
return &Handler{ctx, root} // allow whitelisted origins (so we can make API requests from the browser)
if len(origin) > 0 {
log.Info("Allowing API requests from origin: " + origin)
}
return &Handler{ctx, root, origin}
} }
func (i Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (i Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Debug("Incoming API request: ", r.URL) log.Debug("Incoming API request: ", r.URL)
if len(i.origin) > 0 {
w.Header().Set("Access-Control-Allow-Origin", i.origin)
}
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
req, err := Parse(r, i.root) req, err := Parse(r, i.root)
if err != nil { if err != nil {
if err == ErrNotFound { if err == ErrNotFound {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment