-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
45 lines (35 loc) · 1015 Bytes
/
Copy pathmain.go
File metadata and controls
45 lines (35 loc) · 1015 Bytes
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
package main
import (
"os"
"fmt"
"net/http"
)
func main() {
port := "3000"
serveRoot := false
// First argument is port
if len(os.Args) > 1 {
port = os.Args[1]
fmt.Println("port", os.Args[1])
}
// Second argument allows for not appending path
// but always serving from the root
// Useful for developing SPAs with routers
if len(os.Args) > 2 {
serveRoot = os.Args[2] == "true" || os.Args[2] == "1"
}
http.HandleFunc("/", createHandler(serveRoot))
fmt.Println("Starting simple server on port", port)
http.ListenAndServe(":" + port, nil)
}
func createHandler(serveRoot bool) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
dir, _ := os.Getwd()
// Check if file exists
_, err := os.Stat(dir + r.URL.Path)
if serveRoot == false || ! os.IsNotExist(err) {
dir += r.URL.Path
}
http.ServeFile(w, r, dir)
}
}