From 664e291742c6200994268a858a90cdd317fd4000 Mon Sep 17 00:00:00 2001 From: gutmet Date: Sun, 9 Dec 2018 00:51:40 +0100 Subject: [PATCH] initial commit --- go.mod | 3 +++ server.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 go.mod create mode 100644 server.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f7de00b --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.gutmet.org/simpleserver.git + +require git.gutmet.org/goutil.git v0.0.0-20181208191316-76ae04a2662a diff --git a/server.go b/server.go new file mode 100644 index 0000000..34cc9a9 --- /dev/null +++ b/server.go @@ -0,0 +1,45 @@ +package simpleserver + +import ( + "fmt" + "git.gutmet.org/goutil.git" + "net/http" + "os" + "os/signal" + "path" +) + +func viewHandler(root string, w http.ResponseWriter, r *http.Request) { + file := path.Join(root, r.URL.Path[1:]) + info, err := os.Stat(file) + if err != nil { + fmt.Fprint(w, err) + return + } + if info.IsDir() { + file = path.Join(file, "index.html") + } + fmt.Println("GET " + file) + content, _ := goutil.ReadFile(file) + fmt.Fprint(w, content) +} + +func Serve(root string) { + address := "0.0.0.0:8000" + fmt.Println("Serving at http://" + address + " ...") + fmt.Println("Use Ctrl+C to exit") + fmt.Println("(This is not a production web server, don't get any funny ideas)") + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { viewHandler(root, w, r) }) + srv := &http.Server{Addr: address} + c := make(chan os.Signal, 1) + signal.Notify(c, os.Interrupt) + go func() { + <-c + fmt.Println("Received interrupt, closing...") + srv.Close() + }() + err := srv.ListenAndServe() + if err != nil && err != http.ErrServerClosed { + fmt.Fprintln(os.Stderr, err) + } +}