spa-server/main.go

50 lines
905 B
Go
Raw Normal View History

2014-12-29 20:30:15 +00:00
package main
import (
2014-12-29 20:41:51 +00:00
"flag"
2014-12-29 20:30:15 +00:00
"fmt"
"log"
"net/http"
"os"
)
func handler(w http.ResponseWriter, r *http.Request) {
path := "." + r.URL.Path
2014-12-29 21:04:46 +00:00
fmt.Print(r.URL.Path)
2014-12-29 20:58:43 +00:00
file, err := os.Stat(path)
if err == nil && !file.IsDir() {
2014-12-29 20:30:15 +00:00
// file exists
2014-12-29 20:58:43 +00:00
fmt.Println(" => " + path)
2014-12-29 20:30:15 +00:00
http.ServeFile(w, r, path)
} else {
2014-12-29 20:58:43 +00:00
// file does not exist
2014-12-29 20:30:15 +00:00
index := "index.html"
2014-12-29 20:58:43 +00:00
file, err := os.Stat(index)
if err == nil && !file.IsDir() {
2014-12-29 20:30:15 +00:00
// index.html exists
2014-12-29 20:58:43 +00:00
fmt.Println(" => " + index)
2014-12-29 20:30:15 +00:00
http.ServeFile(w, r, index)
} else {
2014-12-29 20:58:43 +00:00
// index.html does not exist
fmt.Println(" => NotFound")
2014-12-29 20:30:15 +00:00
http.NotFound(w, r)
}
}
}
func main() {
2014-12-29 20:41:51 +00:00
2014-12-29 20:30:15 +00:00
port := ":5050"
2014-12-29 20:41:51 +00:00
flag.Parse()
if flag.NArg() != 0 {
port = ":" + flag.Arg(0)
}
2014-12-29 20:48:44 +00:00
fmt.Println("spa-server starting on localhost" + port)
2014-12-29 20:41:51 +00:00
2014-12-29 20:30:15 +00:00
http.HandleFunc("/", handler)
err := http.ListenAndServe(port, nil)
if err != nil {
log.Fatal("spa-server: ", err)
}
}