Skip to content

Commit

Permalink
better versatility for the first argument
Browse files Browse the repository at this point in the history
  • Loading branch information
syntaqx committed Jan 15, 2019
1 parent e4d3d01 commit 5297aa8
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 13 deletions.
2 changes: 1 addition & 1 deletion .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
36 changes: 24 additions & 12 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
17 changes: 17 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit 5297aa8

Please sign in to comment.