From aaab7d0898cb69097736f00eea2c270e62510401 Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Tue, 18 Nov 2014 22:16:30 -0800 Subject: [PATCH] commands/http: Allow API requests from whitelisted origins --- commands/http/handler.go | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/commands/http/handler.go b/commands/http/handler.go index 658d6ebe4..7f7280c88 100644 --- a/commands/http/handler.go +++ b/commands/http/handler.go @@ -12,8 +12,9 @@ import ( var log = u.Logger("commands/http") type Handler struct { - ctx cmds.Context - root *cmds.Command + ctx cmds.Context + root *cmds.Command + origin string } var ErrNotFound = errors.New("404 page not found") @@ -29,13 +30,23 @@ var mimeTypes = map[string]string{ cmds.Text: "text/plain", } -func NewHandler(ctx cmds.Context, root *cmds.Command) *Handler { - return &Handler{ctx, root} +func NewHandler(ctx cmds.Context, root *cmds.Command, origin string) *Handler { + // 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) { 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) if err != nil { if err == ErrNotFound {