aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAdnan Maolood <[email protected]>2020-10-27 13:32:48 -0400
committerAdnan Maolood <[email protected]>2020-10-27 13:32:48 -0400
commit9079be9019986483148fab16445bcdfc51ce43b3 (patch)
treea240a34d1458bfd8f40de93a5057017ed1acc0f6
parentAdd (*ResponseWriter).WriteStatus function (diff)
downloadarchived-go-gemini-0.1.2.tar.xz
archived-go-gemini-0.1.2.zip
Add ServeFile functionv0.1.2
-rw-r--r--fs.go21
1 files changed, 21 insertions, 0 deletions
diff --git a/fs.go b/fs.go
index 66d08b9..9ed75d1 100644
--- a/fs.go
+++ b/fs.go
@@ -58,6 +58,27 @@ type Dir string
// If the file is a directory, it tries to open the index file in that directory.
func (d Dir) Open(name string) (File, error) {
p := path.Join(string(d), name)
+ return openFile(p)
+}
+
+// ServeFile responds to the request with the contents of the named file
+// or directory.
+// TODO: Use io/fs.FS when available.
+func ServeFile(w *ResponseWriter, fs FS, name string) {
+ f, err := fs.Open(name)
+ if err != nil {
+ w.WriteStatus(StatusNotFound)
+ return
+ }
+ // Detect mimetype
+ ext := filepath.Ext(name)
+ mimetype := mime.TypeByExtension(ext)
+ w.SetMimetype(mimetype)
+ // Copy file to response writer
+ io.Copy(w, f)
+}
+
+func openFile(p string) (File, error) {
f, err := os.OpenFile(p, os.O_RDONLY, 0644)
if err != nil {
return nil, err