linx-server/display.go

55 lines
1.1 KiB
Go
Raw Normal View History

2015-09-24 01:44:49 -04:00
package main
import (
"net/http"
"os"
"path"
"strings"
2015-09-28 21:41:07 -04:00
"bitbucket.org/taruti/mimemagic"
2015-09-24 01:44:49 -04:00
"github.com/flosch/pongo2"
"github.com/zenazn/goji/web"
)
func fileDisplayHandler(c web.C, w http.ResponseWriter, r *http.Request) {
fileName := c.URLParams["name"]
filePath := path.Join(Config.filesDir, fileName)
fileInfo, err := os.Stat(filePath)
2015-09-24 01:44:49 -04:00
if !fileExistsAndNotExpired(fileName) {
notFoundHandler(c, w, r)
2015-09-24 01:44:49 -04:00
return
}
2015-09-28 21:41:07 -04:00
file, _ := os.Open(filePath)
header := make([]byte, 512)
file.Read(header)
file.Close()
2015-09-24 01:44:49 -04:00
2015-09-28 21:41:07 -04:00
mimetype := mimemagic.Match("", header)
2015-09-24 01:44:49 -04:00
var tpl *pongo2.Template
if strings.HasPrefix(mimetype, "image/") {
tpl = Templates["display/image.html"]
} else if strings.HasPrefix(mimetype, "video/") {
tpl = Templates["display/video.html"]
2015-09-27 23:07:15 -04:00
} else if strings.HasPrefix(mimetype, "audio/") {
tpl = Templates["display/audio.html"]
2015-09-27 23:07:15 -04:00
} else if mimetype == "application/pdf" {
tpl = Templates["display/pdf.html"]
2015-09-24 01:44:49 -04:00
} else {
tpl = Templates["display/file.html"]
2015-09-24 01:44:49 -04:00
}
err = tpl.ExecuteWriter(pongo2.Context{
"mime": mimetype,
"filename": fileName,
2015-09-24 01:44:49 -04:00
"size": fileInfo.Size(),
}, w)
if err != nil {
oopsHandler(c, w, r)
2015-09-24 01:44:49 -04:00
}
}