From 9ecbdd5a3fcee65bf6570f62abaed5db372bf1d6 Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Wed, 31 Jul 2019 14:18:31 +0200 Subject: [PATCH] Add CORS and logging to serve command Signed-off-by: Knut Ahlers --- cmd/serve.go | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/cmd/serve.go b/cmd/serve.go index 0593547..ce95c4e 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -14,6 +14,18 @@ import ( "github.com/spf13/cobra" ) +type corsWrap struct { + next http.Handler + header string +} + +func newCorsWrap(next http.Handler, header string) *corsWrap { return &corsWrap{next, header} } + +func (c corsWrap) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", c.header) + c.next.ServeHTTP(w, r) +} + // serveCmd represents the serve command var serveCmd = &cobra.Command{ Use: "serve", @@ -46,7 +58,19 @@ var serveCmd = &cobra.Command{ return fmt.Errorf("Unable to create tunnel: %s", err) } - go http.Serve(listener, http_helper.GzipHandler(http.FileServer(http.Dir(".")))) + var handler http.Handler + handler = http.FileServer(http.Dir(".")) + handler = http_helper.GzipHandler(handler) + + if c, err := cmd.Flags().GetString("cors"); err == nil && c != "" { + handler = newCorsWrap(handler, c) + } + + if l, err := cmd.Flags().GetBool("http-logs"); err == nil && l { + handler = http_helper.NewHTTPLogHandler(handler) + } + + go http.Serve(listener, handler) fmt.Printf("Created HTTP server for this directory with URL %s\nPress Ctrl+C to stop server and tunnel", tun.PublicURL) c := make(chan os.Signal, 1) @@ -60,6 +84,8 @@ var serveCmd = &cobra.Command{ }() } + fmt.Println() + for range c { if err := client.StopTunnel(tun.Name); err != nil { return fmt.Errorf("Unable to stop tunnel %q: %s", tun.Name, err) @@ -76,6 +102,8 @@ func init() { RootCmd.AddCommand(serveCmd) serveCmd.Flags().DurationP("timeout", "t", 0, "Automatically close tunnel after timeout") + serveCmd.Flags().String("cors", "", "Enable setting CORS header") + serveCmd.Flags().Bool("http-logs", true, "Enable HTTP access logs") // Here you will define your flags and configuration settings.