From ec8b3805696c0253366c954a39d02df8c56fbb31 Mon Sep 17 00:00:00 2001 From: codeskyblue Date: Sun, 24 Jul 2016 14:22:44 +0800 Subject: [PATCH] simple but enough to use --- .fsw.yml | 16 ++++++++++++++++ assets/index.html | 6 ++++++ httpstaticserver.go | 24 +++++++++++++++++++++++- main.go | 2 +- 4 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 .fsw.yml create mode 100644 assets/index.html diff --git a/.fsw.yml b/.fsw.yml new file mode 100644 index 0000000..dbaa1b2 --- /dev/null +++ b/.fsw.yml @@ -0,0 +1,16 @@ +desc: Auto generated by fswatch [gohttp-vue] +triggers: +- name: "" + pattens: + - '**/*.go' + - '**/*.c' + - '**/*.py' + env: + DEBUG: "1" + cmd: go build && ./gohttp-vue + shell: true + delay: 100ms + signal: KILL +watch_paths: +- . +watch_depth: 5 diff --git a/assets/index.html b/assets/index.html new file mode 100644 index 0000000..7157a60 --- /dev/null +++ b/assets/index.html @@ -0,0 +1,6 @@ + + +

Gohttp VUE

+

Explore

+ + diff --git a/httpstaticserver.go b/httpstaticserver.go index 04208ff..acea976 100644 --- a/httpstaticserver.go +++ b/httpstaticserver.go @@ -1,7 +1,10 @@ package main import ( + "html/template" + "log" "net/http" + "path/filepath" "github.com/gorilla/mux" ) @@ -12,12 +15,17 @@ type HTTPStaticServer struct { } func NewHTTPStaticServer(root string) *HTTPStaticServer { + if root == "" { + root = "." + } m := mux.NewRouter() s := &HTTPStaticServer{ Root: root, m: m, } m.HandleFunc("/", s.hIndex) + m.HandleFunc("/assets/{path:.*}", s.hAssets) + m.HandleFunc("/raw/{path:.*}", s.hFileOrDirectory) return s } @@ -26,5 +34,19 @@ func (s *HTTPStaticServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { } func (s *HTTPStaticServer) hIndex(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("Hello world!")) + indexPath := filepath.Join("./assets", "index.html") + tmpl := template.Must(template.New("index").ParseFiles(indexPath)) + tmpl.ExecuteTemplate(w, "index.html", nil) +} + +func (s *HTTPStaticServer) hAssets(w http.ResponseWriter, r *http.Request) { + path := mux.Vars(r)["path"] + w.Header().Set("Content-Type", "text/plain") // -_-! not working in chrome + http.ServeFile(w, r, filepath.Join("./assets", path)) +} + +func (s *HTTPStaticServer) hFileOrDirectory(w http.ResponseWriter, r *http.Request) { + path := mux.Vars(r)["path"] + log.Println("Path:", s.Root, path) + http.ServeFile(w, r, filepath.Join(s.Root, path)) } diff --git a/main.go b/main.go index 11f310a..b165095 100644 --- a/main.go +++ b/main.go @@ -26,7 +26,7 @@ func parseFlags() { func main() { parseFlags() - ss := NewHTTPStaticServer("/") + ss := NewHTTPStaticServer("./") log.Printf("Listening on addr: %s\n", strconv.Quote(gcfg.Addr)) log.Fatal(http.ListenAndServe(gcfg.Addr, ss))