From b4f84f1cc88152d908ceba1aa1ee0f67bff3db5d Mon Sep 17 00:00:00 2001 From: WeidiDeng Date: Fri, 2 Sep 2022 22:52:55 +0800 Subject: [PATCH] Document caveats with compressed fs.FS (#344) * Document caveats with compressed fs.FS * Update README.md Co-authored-by: Matt Holt --- README.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/README.md b/README.md index 2373814c..4717ecf6 100644 --- a/README.md +++ b/README.md @@ -244,6 +244,31 @@ if err != nil { } ``` +#### Use with `http.FileServer` + +It can be used with http.FileServer to browse archives and directories in a browser. However, due to how http.FileServer works, don't directly use http.FileServer with compressed files; instead wrap it like following: + +```go +fileServer := http.FileServer(http.FS(archiveFS)) +http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { + // disable range request + writer.Header().Set("Accept-Ranges", "none") + request.Header.Del("Range") + + // disable content-type sniffing + ctype := mime.TypeByExtension(filepath.Ext(request.URL.Path)) + writer.Header()["Content-Type"] = nil + if ctype != "" { + writer.Header().Set("Content-Type", ctype) + } + fileServer.ServeHTTP(writer, request) +}) +``` + +http.FileServer will try to sniff the Content-Type by default if it can't be inferred from file name. To do this, the http package will try to read from the file and then Seek back to file start, which the libray can't achieve currently. The same goes with Range requests. Seeking in archives is not currently supported by archiver due to limitations in dependencies. + +If content-type is desirable, you can [register it](https://pkg.go.dev/mime#AddExtensionType) yourself. + ### Compress data Compression formats let you open writers to compress data: