diff --git a/main.go b/main.go index 61de969..6e51f73 100755 --- a/main.go +++ b/main.go @@ -9,6 +9,7 @@ listing file. package main import ( + "bytes" "errors" "fmt" "io" @@ -16,13 +17,16 @@ import ( "local/gziphttp" "log" "net/http" + "net/http/httptest" "os" "path" + "regexp" "strings" ) const ( ENDPOINT_UPLOAD = "__upload__" + ENDPOINT_DELETE = "__delete__" ) var ( @@ -48,7 +52,7 @@ func main() { } func handler(d string) http.HandlerFunc { - return gzip(endpoints(fserve(d))) + return gzip(endpoints(withDel(fserve(d)))) } func writeMeta(w http.ResponseWriter) { @@ -90,6 +94,10 @@ func endpoints(foo http.HandlerFunc) http.HandlerFunc { if err := upload(w, r); err != nil { fmt.Fprintln(w, err.Error()) } + } else if isDeleted(r) { + if err := del(w, r); err != nil { + fmt.Fprintln(w, err.Error()) + } } else { foo(w, r) } @@ -100,10 +108,51 @@ func isUploaded(r *http.Request) bool { return path.Base(r.URL.Path) == ENDPOINT_UPLOAD } +func isDeleted(r *http.Request) bool { + return path.Base(r.URL.Path) == ENDPOINT_DELETE +} + func isDir(r *http.Request) bool { d := toRealPath(r.URL.Path) fi, err := os.Stat(d) - return err == nil && fi.IsDir() + if err != nil { + return false + } + if !fi.IsDir() { + return false + } + if _, err := os.Stat(path.Join(d, "index.html")); err == nil { + return false + } + return true +} + +func withDel(foo http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !isDir(r) { + foo(w, r) + return + } + fmt.Fprintln(w, ``+"\n") + w2 := httptest.NewRecorder() + foo(w2, r) + b := bytes.Split(w2.Body.Bytes(), []byte("\n")) + buff := bytes.NewBuffer(nil) + for i := range b { + if bytes.Contains(b[i], []byte(" 0 { + match = bytes.Split(match, []byte(`href="`))[1] + match = match[:len(match)-1] + b[i] = []byte(fmt.Sprintf(` %s`, match, ENDPOINT_DELETE, b[i])) + } + } + buff.Write(b[i]) + buff.Write([]byte("\n")) + } + io.Copy(w, buff) + } } func fserve(d string) http.HandlerFunc { @@ -134,6 +183,20 @@ func upload(w http.ResponseWriter, r *http.Request) error { return nil } +func del(w http.ResponseWriter, r *http.Request) error { + p := toRealPath(path.Dir(r.URL.Path)) + _, err := os.Stat(p) + if err != nil { + return err + } + err = os.Remove(p) + if err != nil { + return err + } + http.Redirect(w, r, path.Dir(path.Dir(r.URL.Path))+"/", http.StatusSeeOther) + return nil +} + func toRealPath(p string) string { d := path.Join(fs.Get("d").GetString()) return path.Join(d, p) diff --git a/public/DIR2/d.md b/public/DIR2/d.md new file mode 100644 index 0000000..e69de29 diff --git a/public/DIR2/e.md b/public/DIR2/e.md new file mode 100644 index 0000000..e69de29 diff --git a/public/a.md b/public/a.md new file mode 100644 index 0000000..e69de29 diff --git a/public/b.md b/public/b.md new file mode 100644 index 0000000..e69de29