英文:
go - serve contents from a zip file in http
问题
我正在查看github.com/remyoudompheng/go-misc/zipfs
来从zip文件中提供内容的http服务。
这个简单的示例可以工作,我可以获取files/archives.zip中包含的{FILE}:
http://localhost:8080/zip/{FILE}
package main
import (
"archive/zip"
"github.com/remyoudompheng/go-misc/zipfs"
"log"
"net/http"
)
func main() {
z, err := zip.OpenReader("files/archive.zip")
if err != nil {
log.Fatal(err)
}
defer z.Close()
http.Handle("/zip/", http.StripPrefix("/zip/", http.FileServer(zipfs.NewZipFS(&z.Reader))))
log.Fatal(http.ListenAndServe(":8080", nil))
}
现在,假设我想要像**http://localhost:8080/zip/{ZIPFILE}/{FILE}
**这样的东西。
我尝试注册一个函数,但不起作用。
package main
import (
"archive/zip"
"github.com/remyoudompheng/go-misc/zipfs"
"html"
"log"
"net/http"
"strings"
)
func servezip(res http.ResponseWriter, req *http.Request) {
zippath := "files/" + strings.Split(html.EscapeString(req.URL.Path), "/")[2] + ".zip"
z, err := zip.OpenReader(zippath)
if err != nil {
http.Error(res, err.Error(), 404)
return
}
defer z.Close()
http.StripPrefix("/zip/", http.FileServer(zipfs.NewZipFS(&z.Reader)))
}
func main() {
http.HandleFunc("/zip/", servezip)
log.Fatal(http.ListenAndServe(":8080", nil))
}
我漏掉了什么?handleFunc
能返回http.FileServer
吗?
英文:
i'm looking at github.com/remyoudompheng/go-misc/zipfs
to serve content from a zip file in http.
this minimal example works, i can get a {FILE} contained in files/archives.zip:
http://localhost:8080/zip/{FILE}
package main
import (
"archive/zip"
"github.com/remyoudompheng/go-misc/zipfs"
"log"
"net/http"
)
func main() {
z, err := zip.OpenReader("files/archive.zip")
if err != nil {
log.Fatal(err)
}
defer z.Close()
http.Handle("/zip/", http.StripPrefix("/zip/", http.FileServer(zipfs.NewZipFS(&z.Reader))))
log.Fatal(http.ListenAndServe(":8080", nil))
}
now, suppose that i want something like http://localhost:8080/zip/{ZIPFILE}/{FILE}
i'm trying registering a func but doesn't work
package main
import (
"archive/zip"
"github.com/remyoudompheng/go-misc/zipfs"
"html"
"log"
"net/http"
"strings"
)
func servezip(res http.ResponseWriter, req *http.Request) {
zippath := "files/" + strings.Split(html.EscapeString(req.URL.Path), "/")[2] + ".zip"
z, err := zip.OpenReader(zippath)
if err != nil {
http.Error(res, err.Error(), 404)
return
}
defer z.Close()
http.StripPrefix("/zip/", http.FileServer(zipfs.NewZipFS(&z.Reader)))
}
func main() {
http.HandleFunc("/zip/", servezip)
log.Fatal(http.ListenAndServe(":8080", nil))
}
what i'm missing? can an handlefunc return an http.fileserver?
答案1
得分: 1
你需要调用你创建的处理程序。尝试将servezip中的最后一行更改为:
http.StripPrefix("/zip/", http.FileServer(zipfs.NewZipFS(&z.Reader))).ServeHTTP(res, req)
英文:
You need to call the handler that you create. Try changing the last line in servezip to
http.StripPrefix("/zip/", http.FileServer(zipfs.NewZipFS(&z.Reader))).ServeHTTP(res, req)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论