From 00c645e329ddbbd203c20d8bb9aa8f5d8493ee4e Mon Sep 17 00:00:00 2001 From: Urban Wallasch Date: Thu, 4 Apr 2019 17:21:04 +0200 Subject: [PATCH] * Added file type guessing. --- gogopherd.go | 41 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/gogopherd.go b/gogopherd.go index 44804c1..934ce7c 100644 --- a/gogopherd.go +++ b/gogopherd.go @@ -23,6 +23,7 @@ import ( "io/ioutil" "log" "net" + "net/http" "os" "path/filepath" "strconv" @@ -120,6 +121,38 @@ func validatePath(relpath string) (string, error) { return path, err } +func guessFiletype(path string) (string, error) { + // Open File + f, err := os.Open(path) + if check(err, "Open "+path) != nil { + return "i", err + } + defer f.Close() + // Get the content + buffer := make([]byte, 512) + _, err = f.Read(buffer) + if check(err, "Read "+path) != nil { + return "i", err + } + contentType := http.DetectContentType(buffer) + //tracer.Print("Content Type " + path + " == "+ contentType) + shortType := strings.Split(contentType, ";")[0] + genType := strings.Split(shortType, "/")[0] + gopherType := "9" + if shortType == "text/html" { + gopherType = "h" + } else if genType == "text" { + gopherType = "0" + } else if shortType == "image/gif" { + gopherType = "g" + } else if genType == "image" { + gopherType = "I" + } else if genType == "audio" { + gopherType = "s" + } + return gopherType, nil +} + func createIndex(selector string) (string, error) { dirname := cfg.docRoot + selector d, err := os.Open(dirname) @@ -142,8 +175,8 @@ func createIndex(selector string) (string, error) { list += "1" + fi.Name() + "\t" + selector + pathSep + fi.Name() + loc } else if fmode.IsRegular() { // create a file reference - // TODO: determine file type - list += "0" + fi.Name() + " (" + strconv.FormatInt(fi.Size(), 10) + ")\t" + selector + pathSep + fi.Name() + loc + ftype, _ := guessFiletype(dirname + pathSep + fi.Name()) + list += ftype + fi.Name() + " (" + strconv.FormatInt(fi.Size(), 10) + ")\t" + selector + pathSep + fi.Name() + loc } else if fmode&os.ModeSymlink != 0 { // create a reference according to link target linktarget, _ := os.Readlink(dirname + pathSep + fi.Name()) @@ -157,8 +190,8 @@ func createIndex(selector string) (string, error) { list += "1" + fi.Name() + " -> " + linktarget + "\t" + selector + pathSep + fi.Name() + loc } else if lfi.Mode().IsRegular() { // link points to a regular file - // TODO: determine file type - list += "0" + fi.Name() + " -> " + linktarget + "\t" + selector + pathSep + fi.Name() + loc + ftype, _ := guessFiletype(dirname + pathSep + fi.Name()) + list += ftype + fi.Name() + " -> " + linktarget + "\t" + selector + pathSep + fi.Name() + loc } } } -- 2.30.2