summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorShulhan <ms@kilabit.info>2022-08-03 20:44:11 +0700
committerShulhan <ms@kilabit.info>2022-08-03 20:44:11 +0700
commitea17dae687ab24d3d73c3dfc3bd3f71ea9c94c96 (patch)
tree8dbe4d47cbc57b2abe4691389f941926340eabf5
parente87e437cd3a4fc043c2642a7211b2631f767f80c (diff)
downloadpakakeh.go-ea17dae687ab24d3d73c3dfc3bd3f71ea9c94c96.tar.xz
lib/memfs: add method to generate index.html in Node's Content
The GenerateIndexHtml generate simple directory listing as HTML for all child in the node. This method is only applicable if node is a directory.
-rw-r--r--lib/memfs/node.go51
1 files changed, 51 insertions, 0 deletions
diff --git a/lib/memfs/node.go b/lib/memfs/node.go
index bf436fc1..0520a044 100644
--- a/lib/memfs/node.go
+++ b/lib/memfs/node.go
@@ -21,6 +21,17 @@ import (
libbytes "github.com/shuLhan/share/lib/bytes"
)
+const (
+ templateIndexHtmlHeader = `<!DOCTYPE html><html>
+<head>
+<meta name="viewport" content="width=device-width">
+<style>
+body{font-family:monospace; white-space:pre;}
+</style>
+</head>
+<body>`
+)
+
var (
errOffset = errors.New("Seek: invalid offset")
errWhence = errors.New("Seek: invalid whence")
@@ -139,6 +150,46 @@ func (node *Node) Close() error {
return nil
}
+// GenerateIndexHtml generate simple directory listing as HTML for all childs
+// in this node.
+// This method is only applicable if node is a directory.
+func (node *Node) GenerateIndexHtml() {
+ if !node.IsDir() {
+ return
+ }
+ if len(node.Content) != 0 {
+ // Either the index has been generated or the node is not
+ // empty.
+ node.size = int64(len(node.Content))
+ return
+ }
+
+ var (
+ buf bytes.Buffer
+ child *Node
+ )
+
+ buf.WriteString(templateIndexHtmlHeader)
+
+ fmt.Fprintf(&buf, `<h3>Index of %s</h3>`, node.name)
+
+ if node.Parent != nil {
+ buf.WriteString(`<div><a href="..">..</a></div><br/>`)
+ }
+
+ for _, child = range node.Childs {
+ fmt.Fprintf(&buf, `<div>%s <tt>%12d</tt> %s <a href=%q>%s</a></div><br/>`,
+ child.mode, child.size, child.modTime.Format(time.RFC3339),
+ child.Path, child.name)
+ }
+
+ buf.WriteString(`</body></html>`)
+
+ node.ContentType = `text/html; charset=utf-8`
+ node.size = int64(buf.Len())
+ node.Content = libbytes.Copy(buf.Bytes())
+}
+
func (node *Node) IsDir() bool {
return node.mode.IsDir()
}