From e187a3e94c9f381b58854cc5429d40cac14e6800 Mon Sep 17 00:00:00 2001 From: ache Date: Tue, 12 Feb 2019 06:25:54 +0100 Subject: Manage GET (the base) --- dir.html | 11 ++++++++++ server.go | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 dir.html diff --git a/dir.html b/dir.html new file mode 100644 index 0000000..b570d3e --- /dev/null +++ b/dir.html @@ -0,0 +1,11 @@ + + + + {{if .Name}}{{ .Name }}{{end}} + + +
{{range .ListEntries}}
+{{ .Name }}	{{ .Size }}{{end}}
+
+ + diff --git a/server.go b/server.go index 29f6a05..c7e55a7 100644 --- a/server.go +++ b/server.go @@ -4,10 +4,75 @@ import ( "fmt" "log" "net/http" + "os" + "html/template" ) +var tmpl *template.Template + func handleGet( w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "It's the root ! [%s]{{%s}}", r.URL.Path[1:], r.Method) + + path := r.URL.Path[1:] + if path == "" { + path = "." + } + fmt.Printf("Trying to get [%s]\n", r.URL.Path[1:]) + + stat, err := os.Stat(path) + + switch { + case err != nil || stat == nil : + if os.IsNotExist(err) { + w.WriteHeader(http.StatusNotFound) + fmt.Fprintln(w, "File not found") + fmt.Fprintln(w, "") + fmt.Fprintln(w, "Sry bro") + return + } + case stat.IsDir() : + // If it's a collection list return the list of the collection + + type Entry struct { + Name string + Size int + } + + var files []Entry + f, err := os.Open(path) + + if err != nil { + w.WriteHeader(http.StatusNotFound) + fmt.Fprintln(w, "File not found") + fmt.Fprintln(w, "") + fmt.Fprintln(w, "Sry bro") + return + } + + fileInfo, err := f.Readdir(-1) + f.Close() + + if err != nil { + w.WriteHeader(http.StatusNotFound) + fmt.Fprintln(w, "File not found") + fmt.Fprintln(w, "") + fmt.Fprintln(w, "Sry bro") + } + + for _, file := range fileInfo { + files = append(files, Entry{file.Name(), 0}) + } + + + type Collection struct { + Name string + ListEntries []Entry + } + tmpl.Execute(w, Collection{ "Title" , files}) + + case stat.Mode().IsRegular(): + http.ServeFile(w, r, r.URL.Path[1:]) + default: + } } func handlePost( w http.ResponseWriter, r *http.Request) { } @@ -36,6 +101,9 @@ func handleMethod( w http.ResponseWriter, r *http.Request) { } func main() { + + tmpl = template.Must(template.ParseFiles("dir.html")) + fmt.Println("Launch server") http.HandleFunc("/", handleMethod) log.Fatal(http.ListenAndServe(":8080", nil)) -- cgit v1.2.3