-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
82 lines (69 loc) · 2.09 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Serves the current working directory over HTTP (static file server). Has a directory listing and all that stuff.
package main
import (
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"time"
"github.com/briandowns/spinner"
"github.com/fatih/color"
)
var path string
var listenAddress string
var spin *spinner.Spinner
func init() {
// Use the working directory as the default location to serve
wd, err := os.Getwd()
if err != nil {
fmt.Println("Could not determine current working directory.", err)
os.Exit(1)
}
// input flags
flag.StringVar(&listenAddress, "l", ":9001", "The address for the server to listen on. Examples: :80, 127.0.0.1:8000")
flag.StringVar(&path, "p", wd, "The path for the server to serve.")
flag.Parse()
}
func main() {
// watch for kill signals and exit nicely
go watchForKill()
// setup a spinner
spin = spinner.New(spinner.CharSets[14], time.Millisecond*50)
spin.Color("green")
spin.FinalMSG = "" // causes it to erase the current message when stopped
// formulate the proper clickable listen address for output
var listenAddressClickable string
if len(strings.Split(listenAddress, ".")) < 4 {
listenAddressClickable = "http://127.0.0.1" + listenAddress
} else {
listenAddressClickable = "http://" + listenAddress
}
// configure the spinner output and start it up
var spinnerMessage string
spinnerMessage = color.WhiteString(" %s", "Server running at ")
spinnerMessage = spinnerMessage + color.YellowString("%s ", path)
spinnerMessage = spinnerMessage + color.WhiteString("%s ", "on")
spinnerMessage = spinnerMessage + color.GreenString("%s", listenAddressClickable)
spin.Suffix = spinnerMessage
spin.Start()
// initialze a file server handler
http.Handle("/", http.FileServer(http.Dir(path)))
err := http.ListenAndServe(listenAddress, nil)
spin.Stop()
if err != nil {
fmt.Println("Server exited with error: ", err)
os.Exit(254)
}
os.Exit(0)
}
// watchForKill watches for kill and interrupt signals
func watchForKill() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, os.Kill)
<-c
spin.Stop()
os.Exit(0)
}