summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorache <ache@ache.one>2019-02-12 06:25:54 +0100
committerache <ache@ache.one>2019-02-12 06:25:54 +0100
commite187a3e94c9f381b58854cc5429d40cac14e6800 (patch)
treed83bd0856ce49e69b0e16c169f71ddcf11da8c01
parentHandle Method (diff)
Manage GET (the base)
-rw-r--r--dir.html11
-rw-r--r--server.go70
2 files changed, 80 insertions, 1 deletions
diff --git a/dir.html b/dir.html
new file mode 100644
index 0000000..b570d3e
--- /dev/null
+++ b/dir.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ {{if .Name}}<title>{{ .Name }}</title>{{end}}
+ </head>
+ <body>
+<pre>{{range .ListEntries}}
+<a href="{{ .Name }}">{{ .Name }}</a> {{ .Size }}{{end}}
+</pre>
+ </body>
+</html>
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))