Skip to content

Commit

Permalink
improved: serve zip files as folders
Browse files Browse the repository at this point in the history
  • Loading branch information
yury-egorenkov committed Oct 23, 2023
1 parent 888b281 commit 35bbd64
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
38 changes: 24 additions & 14 deletions srv.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ package srv

import (
"archive/zip"
"errors"
"io"
"io/fs"
"mime"
"net/http"
"os"
"path"
"path/filepath"
"strings"
)
Expand Down Expand Up @@ -66,24 +70,30 @@ func (self FileServer) ServeHTTP(rew http.ResponseWriter, req *http.Request) {
}

if fileExists(zipFile) {
zipFile, _ := zip.OpenReader(zipFile)
defer zipFile.Close()

for _, file := range zipFile.File {
if file.Name == inZipFile {
file, _ := file.Open()
io.Copy(rew, file)
return
}
zipReader, err := zip.OpenReader(zipFile)
if err != nil {
panic(err)
}
defer zipReader.Close()

req.URL.Path = inZipFile

// goto notFound
file, err := zipReader.Open(inZipFile)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
goto notFound
}
panic(err)
}
rew.Header().Set(`Content-Type`, mime.TypeByExtension(filepath.Ext(inZipFile)))
io.Copy(rew, file)
return
}

// Has extension? Don't bother looking for +".html" or +"/index.html".
// if path.Ext(reqPath) != "" {
// goto notFound
// }
if path.Ext(reqPath) != "" {
goto notFound
}

// Try +".html".
{
Expand All @@ -103,7 +113,7 @@ func (self FileServer) ServeHTTP(rew http.ResponseWriter, req *http.Request) {
}
}

// notFound:
notFound:
// Minor issue: sends code 200 instead of 404 if "404.html" is found; not
// worth fixing for local development.
http.ServeFile(rew, req, fpj(dir, "404.html"))
Expand Down
1 change: 1 addition & 0 deletions srv/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Usage:
srv -p <port>
srv -h <host>
srv -c
srv -zip
Settings:
Expand Down

0 comments on commit 35bbd64

Please sign in to comment.