From aa3a73a170b8f2aa0036939d5a425c35c05f69b4 Mon Sep 17 00:00:00 2001 From: Daniel Arthur Gallagher <8526031+DanArthurGallagher@users.noreply.github.com> Date: Fri, 24 Apr 2020 14:42:21 +0200 Subject: [PATCH] feat: add CORS support (#1) Adds a CORS header if the flag is set. --- README.md | 9 +++++---- main.go | 7 +++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 7499a47..c553d0c 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,8 @@ By default, serves the current working directory on port 8000. If `$GOPATH/bin` ### Command-line Arguments -| Flag | Default | Description | -| --- | --- | --- | -| -port | `8000` | port to listen on | -| -dir | `"."` | directory to serve | +| Flag | Default | Description | +| ----- | ------- | ------------------------------------------------------------ | +| -port | `8000` | port to listen on | +| -dir | `"."` | directory to serve | +| -cors | `false` | `true` to enable CORS (via `Access-Control-Allow-Origin: *`) | diff --git a/main.go b/main.go index 1b70f57..912b06d 100644 --- a/main.go +++ b/main.go @@ -9,10 +9,12 @@ import ( var Port int var Dir string +var UseCors bool func init() { flag.IntVar(&Port, "port", 8000, "port to listen on") flag.StringVar(&Dir, "dir", ".", "directory to serve") + flag.BoolVar(&UseCors, "cors", false, "Set true to enable 'Access-Control-Allow-Origin: *' on all requests") } // ResponseWriter wraps http.ResponseWriter to capture the HTTP status code @@ -23,6 +25,11 @@ type ResponseWriter struct { func (w *ResponseWriter) WriteHeader(statusCode int) { w.StatusCode = statusCode + + if UseCors { + w.ResponseWriter.Header().Add("Access-Control-Allow-Origin", "*") + } + w.ResponseWriter.WriteHeader(statusCode) }