-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
69 lines (60 loc) · 1.27 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
package main
import (
"fmt"
"net/http"
"os"
"path/filepath"
"github.com/codegangsta/cli"
)
func main() {
app := cli.NewApp()
app.Name = "fileserver"
app.Usage = "An simple file server."
app.Author = "Lyric"
app.Email = "[email protected]"
app.Version = "0.1.0"
app.Flags = []cli.Flag{
cli.IntFlag{
Name: "port, p",
Value: 5230,
Usage: "listen port",
},
}
app.Action = func(c *cli.Context) {
args := c.Args()
if len(args) == 0 {
fmt.Println("ERROR:Please specify a static directory.")
os.Exit(1)
}
Run(args[0], c.Int("port"))
}
app.RunAndExitOnError()
}
type MyHandler struct {
FilePath string
}
func (m *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if path == "" || path == "/" {
http.ServeFile(w, r, filepath.Join(m.FilePath, "index.html"))
return
}
fileName := m.FilePath + path
f, err := os.Stat(fileName)
if err != nil {
fmt.Fprintln(w, "404 Not found.")
return
}
if f.IsDir() {
http.ServeFile(w, r, filepath.Join(fileName, "index.html"))
} else {
http.ServeFile(w, r, fileName)
}
}
func Run(dir string, port int) {
handler := &MyHandler{
FilePath: dir,
}
fmt.Printf("===> Server is running at %d port.\n", port)
http.ListenAndServe(fmt.Sprintf(":%d", port), handler)
}