From 5297aa80bb75137df6958aa355ada7f02765281d Mon Sep 17 00:00:00 2001 From: Chase Hutchins Date: Mon, 14 Jan 2019 19:55:18 -0700 Subject: [PATCH] better versatility for the first argument --- .goreleaser.yml | 2 +- main.go | 36 ++++++++++++++++++++++++------------ main_test.go | 17 +++++++++++++++++ 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/.goreleaser.yml b/.goreleaser.yml index cd88dc0..757ec93 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -30,7 +30,7 @@ brew: name: homebrew-tap folder: Formula homepage: https://github.com/syntaqx/serve - description: `serve` is a static http server anywhere you need one. + description: serve is a static http server anywhere you need one. test: | system "#{bin}/serve version" changelog: diff --git a/main.go b/main.go index 172fd62..02dfa19 100644 --- a/main.go +++ b/main.go @@ -20,37 +20,49 @@ const version = "0.0.0-develop" type flags struct { Host string `json:"host"` Port int `json:"port"` + Dir string `json:"dir"` } func main() { var opt flags flag.StringVar(&opt.Host, "host", "", "host address to bind to") flag.IntVar(&opt.Port, "port", 8080, "listening port") + flag.StringVar(&opt.Dir, "dir", "", "directory to serve") flag.Parse() log := log.New(os.Stderr, "[serve] ", log.LstdFlags) - // If an argument is provided, use it as the root directory. - dir := flag.Arg(0) - if len(dir) == 0 { - cwd, err := os.Getwd() - if err != nil { - log.Printf("unable to determine current working directory: %v\n", err) - os.Exit(1) - } - dir = cwd - } + // If an argument was provided, see if it's a command, or use it as opt.Dir + arg := flag.Arg(0) // Version command, mostly used for testing if the binary is working. - if dir == "version" { + if arg == "version" { fmt.Printf(fmt.Sprintf("serve version %s %s/%s", version, runtime.GOOS, runtime.GOARCH)) os.Exit(0) } + // If an argument is provided, use it as the root directory. + if opt.Dir == "" { + if len(arg) == 0 { + cwd, err := os.Getwd() + if err != nil { + log.Printf("unable to determine current working directory: %v\n", err) + os.Exit(1) + } + opt.Dir = cwd + } else { + opt.Dir = arg + } + } + + startHTTPServer(opt, log) +} + +func startHTTPServer(opt flags, log *log.Logger) { r := http.NewServeMux() // Handler, wrapped with middleware - handler := http.FileServer(http.Dir(dir)) + handler := http.FileServer(http.Dir(opt.Dir)) handler = Logger(log)(handler) handler = CORS()(handler) handler = NoCache()(handler) diff --git a/main_test.go b/main_test.go index df347d8..3eeccc8 100644 --- a/main_test.go +++ b/main_test.go @@ -11,6 +11,23 @@ import ( "github.com/stretchr/testify/assert" ) +func TestStartHTTPServer(t *testing.T) { + t.Skip() + + t.Parallel() + + assert := assert.New(t) + + opt := flags{Port: 0, Dir: "."} + + var b bytes.Buffer + log := log.New(&b, "[test] ", 0) + + go startHTTPServer(opt, log) + + assert.Contains(b.String(), "http server listening at") +} + func TestLogger(t *testing.T) { t.Parallel()