// @router /test/file/download [get] func (c *TestController) Download() { filename := c.GetString("name") if filename == "" { http.Error(c.Ctx.ResponseWriter, "Not Found", 404) return } filename = fileDir + filename _, err := os.Stat(filename) if os.IsNotExist(err) { http.Error(c.Ctx.ResponseWriter, "Not Found", 404) return } ctype := mime.TypeByExtension(filepath.Ext(filename)) if ctype == "" { ctype = "application/oct-stream" } en := context.ParseEncoding(c.Ctx.Request) if en != "" { c.Ctx.ResponseWriter.Header().Set("Content-Encoding", en) } c.Ctx.ResponseWriter.Header().Set("Content-Type", ctype) f, err := os.Open(filename) context.WriteFile(en, c.Ctx.ResponseWriter, f) }
func openFile(filePath string, fi os.FileInfo, acceptEncoding string) (bool, string, *serveContentHolder, error) { mapKey := acceptEncoding + ":" + filePath mapLock.RLock() mapFile, _ := staticFileMap[mapKey] mapLock.RUnlock() if isOk(mapFile, fi) { return mapFile.encoding != "", mapFile.encoding, mapFile, nil } mapLock.Lock() defer mapLock.Unlock() if mapFile, _ = staticFileMap[mapKey]; !isOk(mapFile, fi) { file, err := os.Open(filePath) if err != nil { return false, "", nil, err } defer file.Close() var bufferWriter bytes.Buffer _, n, err := context.WriteFile(acceptEncoding, &bufferWriter, file) if err != nil { return false, "", nil, err } mapFile = &serveContentHolder{Reader: bytes.NewReader(bufferWriter.Bytes()), modTime: fi.ModTime(), size: int64(bufferWriter.Len()), encoding: n} staticFileMap[mapKey] = mapFile } return mapFile.encoding != "", mapFile.encoding, mapFile, nil }