From 91469fdebf57ff683cc2a7d9373cdee554ed3aba Mon Sep 17 00:00:00 2001 From: clsr Date: Fri, 18 Aug 2017 13:47:07 +0200 Subject: Initial commit --- fileserver.go | 231 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 231 insertions(+) create mode 100644 fileserver.go (limited to 'fileserver.go') diff --git a/fileserver.go b/fileserver.go new file mode 100644 index 0000000..e1754a1 --- /dev/null +++ b/fileserver.go @@ -0,0 +1,231 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "mime" + "os" + "path" + "path/filepath" + "sort" + "strings" + "time" + + "contnet.org/lib/cnm-go" + "contnet.org/lib/cnm-go/cnmfmt" + "contnet.org/lib/cnp-go" +) + +func init() { + mime.AddExtensionType(".cnm", "text/cnm") +} + +func listdir(w cnp.ResponseWriter, r *cnp.Request, root string, f *os.File, stat os.FileInfo) { + if p := r.Path(); !strings.HasSuffix(p, "/") { + w.Response().SetIntent(cnp.IntentRedirect) + w.Response().SetLocation("", p+"/") + return + } + + files, err := f.Readdir(-1) + if err != nil { + panic(cnp.ErrorServerError{Reason: err.Error()}) + } + + sort.Slice(files, func(i, j int) bool { + d1, d2 := files[i].IsDir(), files[j].IsDir() + if !d1 && d2 { + return false + } + if d1 && !d2 { + return true + } + return files[i].Name() < files[j].Name() + }) + + relpath, err := filepath.Rel(root, f.Name()) + if err != nil { + panic(cnp.ErrorServerError{Reason: err.Error()}) + } + dirpath := filepath.ToSlash(relpath) + site := cnm.Site{Path: dirpath} + dirname := path.Clean("/" + dirpath) + if !strings.HasSuffix(dirname, "/") { + dirname += "/" + } + + var par []cnmfmt.Text + var links []cnm.Link + + if dirname != "/" { + links = []cnm.Link{cnm.Link{ + URL: "../", + Name: "..", + Description: "Go to the parent directory", + }} + par = append(par, cnmfmt.Text{Spans: []cnmfmt.Span{cnmfmt.Span{ + //Format: cnmfmt.Format{Link: path.Dir(dirname)}, + Format: cnmfmt.Format{Link: "../"}, + Text: "..", + }}}) + } + + for _, file := range files { + name := file.Name() + if name[0] == '.' { + continue + } + if file.IsDir() { + name += "/" + } + //site.Children = append(site.Children, cnm.Site{Path: name, Name: name}) + par = append(par, cnmfmt.Text{Spans: []cnmfmt.Span{cnmfmt.Span{ + Format: cnmfmt.Format{Link: dirname + name}, + Text: name, + }}}) + } + + content := cnm.NewContentBlock("content") + content.AppendChild(cnmfmt.NewTextFmtBlock(par)) + + if site.Path != "." { + site = cnm.Site{Children: []cnm.Site{site}} + } + + doc := &cnm.Document{ + Title: dirname, + Content: content, + Site: site, + Links: links, + } + + var buf bytes.Buffer + if err = doc.Write(&buf); err != nil { + panic(cnp.ErrorServerError{Reason: err.Error()}) + } + + w.Response().SetType("text/cnm") + w.Response().SetLength(int64(buf.Len())) + + if _, err = io.Copy(w, &buf); err != nil { + panic(cnp.ErrorServerError{Reason: err.Error()}) + } +} + +func guessType(fname string) string { + typ := mime.TypeByExtension(path.Ext(fname)) + if typ == "" { + typ, _ = GetMimeType(fname) + } + t, _, _ := mime.ParseMediaType(typ) + return t +} + +func open(dir, fpath string) (*os.File, error) { + if dir == "" { + dir = "." + } + if filepath.Separator != '/' && strings.ContainsRune(fpath, filepath.Separator) { + // prevent exiting root dir on e.g. Windows + // TODO: maybe filepath.Clean instead? + return nil, cnp.ErrorRejected{Reason: "invalid filepath"} + } + return os.Open(filepath.Join(dir, filepath.FromSlash(path.Clean("/"+fpath)))) +} + +func getfile(dir, pth string, strict bool) (*os.File, os.FileInfo) { + var f *os.File + var err error + fnames := []string{pth} + if !strings.HasSuffix(pth, ".cnm") { + fnames = []string{pth, pth + ".cnm"} + } + var firstErr error + for _, fname := range fnames { + f, err = open(dir, fname) + if firstErr == nil { + firstErr = err + } + if os.IsNotExist(err) { + //panic(cnp.ErrorNotFound{Reason: err.Error()}) + continue + } else if _, ok := err.(cnp.Error); ok { + panic(err) + } else if err != nil { + panic(cnp.ErrorServerError{Reason: err.Error()}) + } + break + } + var stat os.FileInfo + if err != nil { + if strict { + return nil, stat + } + panic(cnp.ErrorNotFound{Reason: firstErr.Error()}) + } + stat, err = f.Stat() + if err != nil { + panic(cnp.ErrorServerError{Reason: err.Error()}) + } + if stat.IsDir() { + if !strings.HasSuffix(pth, "/") { + return nil, stat + } + f2, st2 := getfile(dir, pth+"index.cnm", true) + if f2 != nil { + return f2, st2 + } + } + return f, stat +} + +func server(addr, dir string) { + fmt.Printf("listening on %q, serving dir %q\n", addr, dir) + panic(cnp.ListenAndServe(addr, cnp.HandlerFunc(func(w cnp.ResponseWriter, r *cnp.Request) { + f, stat := getfile(dir, r.Path(), false) + defer f.Close() + + mtime := stat.ModTime().Truncate(time.Second) + + w.Response().SetModified(mtime) + w.Response().SetTime(time.Now()) + if stat.IsDir() { + listdir(w, r, dir, f, stat) + return + } + + if ifmod := r.IfModified(); !ifmod.IsZero() && (ifmod.Equal(mtime) || ifmod.After(mtime)) { + w.Response().SetIntent(cnp.IntentNotModified) + if err := w.WriteHeader(); err != nil { + panic(err) + } + return + } + + w.Response().SetLength(stat.Size()) + w.Response().SetName(stat.Name()) + w.Response().SetType(guessType(f.Name())) + + if _, err := io.Copy(w, f); err != nil { + panic(err) + } + }))) +} + +func main() { + if len(os.Args) > 3 { + prog := path.Base(os.Args[0]) + fmt.Fprintf(os.Stderr, "%s: usage: %s [HOST[:PORT]] [DIR]", prog, prog) + os.Exit(2) + } + addr := "localhost" + dir := "." + if len(os.Args) >= 2 { + addr = os.Args[1] + } + if len(os.Args) >= 3 { + dir = os.Args[2] + } + server(addr, dir) +} -- cgit