initial support for directory listing

This commit is contained in:
Hedy Li 2021-07-11 14:28:23 +08:00
parent 22bcec79c5
commit ac16bfccfe
Signed by: hedy
GPG Key ID: B51B5A8D1B176372
3 changed files with 149 additions and 7 deletions

View File

@ -3,7 +3,7 @@ WIP!
## todo
- [x] /folder to /folder/ redirects
- [ ] directory listing
- [x] directory listing
- [ ] ~user directories
- [x] refactor working dir part
- [ ] config

116
dirlist.go Normal file
View File

@ -0,0 +1,116 @@
package main
import (
"bufio"
"fmt"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
)
func generateDirectoryListing(reqPath, path string) ([]byte, error) {
dirSort := "time"
dirReverse := false
var listing string
files, err := ioutil.ReadDir(path)
if err != nil {
return []byte(listing), err
}
listing = "# Directory listing\n\n"
// TODO: custom dirlist header in config
// Do "up" link first
if reqPath != "/" {
if strings.HasSuffix(reqPath, "/") {
reqPath = reqPath[:len(reqPath)-1]
}
up := filepath.Dir(reqPath)
listing += fmt.Sprintf("=> %s %s\n", up, "..")
}
// Sort files
sort.SliceStable(files, func(i, j int) bool {
if dirReverse {
i, j = j, i
}
if dirSort == "name" {
return files[i].Name() < files[j].Name()
} else if dirSort == "size" {
return files[i].Size() < files[j].Size()
} else if dirSort == "time" {
return files[i].ModTime().Before(files[j].ModTime())
}
return false // Should not happen
})
// Format lines
for _, file := range files {
// Skip dotfiles
if strings.HasPrefix(file.Name(), ".") {
continue
}
// Only list world readable files
if uint64(file.Mode().Perm())&0444 != 0444 {
continue
}
// Make sure links to directories have a trailing slash,
// to avoid needless redirects
relativeUrl := url.PathEscape(file.Name())
if file.IsDir() {
relativeUrl += "/"
}
listing += fmt.Sprintf("=> %s %s\n", relativeUrl, generatePrettyFileLabel(file, path))
}
return []byte(listing), nil
}
func generatePrettyFileLabel(info os.FileInfo, path string) string {
dirTitles := true // TODO: config
var size string
if info.IsDir() {
size = " "
} else if info.Size() < 1024 {
size = fmt.Sprintf("%4d B", info.Size())
} else if info.Size() < (1024 << 10) {
size = fmt.Sprintf("%4d KiB", info.Size()>>10)
} else if info.Size() < 1024<<20 {
size = fmt.Sprintf("%4d MiB", info.Size()>>20)
} else if info.Size() < 1024<<30 {
size = fmt.Sprintf("%4d GiB", info.Size()>>30)
} else if info.Size() < 1024<<40 {
size = fmt.Sprintf("%4d TiB", info.Size()>>40)
} else {
size = "GIGANTIC"
}
name := info.Name()
// TODO: hard coded .gmi file ext
if dirTitles && filepath.Ext(name) == ".gmi" {
name = readHeading(path, info)
}
if len(name) > 40 {
name = name[:36] + "..."
}
if info.IsDir() {
name += "/"
}
return fmt.Sprintf("%-40s %s %v", name, size, info.ModTime().Format("Jan _2 2006"))
}
func readHeading(path string, info os.FileInfo) string {
filePath := filepath.Join(path, info.Name())
file, err := os.Open(filePath)
if err != nil {
return info.Name()
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "# ") {
return strings.TrimSpace(line[1:])
}
}
return info.Name()
}

View File

@ -85,10 +85,11 @@ func handleConnection(conn io.ReadWriteCloser) {
}
// serveFile serves opens the requested path and returns the file content
func serveFile(conn io.ReadWriteCloser, path string) {
// default index file for a directory is index.gmi
if strings.HasSuffix(path, "/") || path == "" {
path = filepath.Join(path, "index.gmi")
func serveFile(conn io.ReadWriteCloser, reqPath string) {
// TODO: [config] default index file for a directory is index.gmi
path := reqPath
if strings.HasSuffix(reqPath, "/") || reqPath == "" {
path = filepath.Join(reqPath, "index.gmi")
}
cleanPath := filepath.Clean(path)
@ -102,9 +103,30 @@ func serveFile(conn io.ReadWriteCloser, path string) {
rootDir = http.Dir(prefixDir + strings.Replace(*contentDir, ".", "", -1))
// Open the requested resource.
var content []byte
log.Printf("Fetching: %s", cleanPath)
f, err := rootDir.Open(cleanPath)
if err != nil {
// not putting the /folder to /folder/ redirect here because folder can still
// be opened without errors
// Directory listing
if strings.HasSuffix(cleanPath, "index.gmi") {
fullPath := filepath.Join(fmt.Sprint(rootDir), cleanPath)
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
// If and only if the path is index.gmi AND index.gmi does not exist
fullPath = strings.TrimSuffix(fullPath, "index.gmi")
log.Println("Generating directory listing:", fullPath)
content, err = generateDirectoryListing(reqPath, fullPath)
if err != nil {
log.Println(err)
sendResponseHeader(conn, statusServerError, "Error generating directory listing")
return
}
cleanPath += ".gmi" // OOF, this is just to have the text/gemini meta later lol
serveContent(conn, content, cleanPath)
return
}
}
log.Println(err)
sendResponseHeader(conn, statusClientError, "Not found")
return
@ -112,7 +134,7 @@ func serveFile(conn io.ReadWriteCloser, path string) {
defer f.Close()
// Read da file
content, err := ioutil.ReadAll(f)
content, err = ioutil.ReadAll(f)
if err != nil {
// /folder to /folder/ redirect
// I wish I could check if err is a "path/to/dir" is a directory error
@ -127,10 +149,13 @@ func serveFile(conn io.ReadWriteCloser, path string) {
sendResponseHeader(conn, statusServerError, "Resource could not be read")
return
}
serveContent(conn, content, cleanPath)
}
func serveContent(conn io.ReadWriteCloser, content []byte, path string) {
// MIME
meta := http.DetectContentType(content)
if strings.HasSuffix(cleanPath, ".gmi") {
if strings.HasSuffix(path, ".gmi") {
meta = "text/gemini; lang=en; charset=utf-8" // TODO: configure custom meta string
}
@ -138,6 +163,7 @@ func serveFile(conn io.ReadWriteCloser, path string) {
sendResponseHeader(conn, statusSuccess, meta)
log.Println("Writing content")
sendResponseContent(conn, content)
}
// func echoFunction(conn io.ReadWriteCloser, content string) {