dt97868 2014-11-20 16:15
浏览 17
已采纳

go-通过http中的zip文件提供内容

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条回答 默认 最新

  • dongzhi9192 2014-11-20 18:23
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 解决websocket跟c#客户端通信
  • ¥30 Python调用dll文件输出Nan重置dll状态
  • ¥15 浮动div的高度控制问题。
  • ¥66 换电脑后应用程序报错
  • ¥50 array数据同步问题
  • ¥15 pic16F877a单片机的外部触发中断程序仿真失效
  • ¥15 Matlab插值拟合差分微分规划图论
  • ¥15 keil5 target not created
  • ¥15 C/C++数据与算法请教
  • ¥15 怎么找志同道合的伙伴