Skip to content
This repository has been archived by the owner on Nov 5, 2020. It is now read-only.

Commit

Permalink
feat: add CORS support (#1)
Browse files Browse the repository at this point in the history
Adds a CORS header if the flag is set.
  • Loading branch information
danieleloscozzese authored Apr 24, 2020
1 parent 4b2e015 commit aa3a73a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: *`) |
7 changes: 7 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}

Expand Down

0 comments on commit aa3a73a

Please sign in to comment.