diff options
| author | Adnan Maolood <[email protected]> | 2020-10-27 13:32:48 -0400 |
|---|---|---|
| committer | Adnan Maolood <[email protected]> | 2020-10-27 13:32:48 -0400 |
| commit | 9079be9019986483148fab16445bcdfc51ce43b3 (patch) | |
| tree | a240a34d1458bfd8f40de93a5057017ed1acc0f6 | |
| parent | Add (*ResponseWriter).WriteStatus function (diff) | |
| download | archived-go-gemini-0.1.2.tar.xz archived-go-gemini-0.1.2.zip | |
Add ServeFile functionv0.1.2
| -rw-r--r-- | fs.go | 21 |
1 files changed, 21 insertions, 0 deletions
@@ -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 |