dongsi3826 2018-06-05 11:22
浏览 254
已采纳

如何使用Golang从MongoDB提供文件

I am working on a go project where I need to serve files stored in mongodb. The files are stored in a GridFs. I use gopkg.in/mgo.v2 as package to connect and query the db.

I can retrieve the file from the db, that is not hard.

f, err := s.files.OpenId(id)

But how can I serve that file with http? I work with the JulienSchmidt router to handle all the other restfull requests. The solutions I find always use static files, not files from a db.

Thanks in advance

  • 写回答

1条回答 默认 最新

  • duanbishai5271 2018-06-05 11:32
    关注

    Tip: Recommended to use github.com/globalsign/mgo instead of gopkg.in/mgo.v2 (the latter is not maintained anymore).


    The mgo.GridFile type implements io.Reader, so you could use io.Copy() to copy its content into the http.ResponseWriter.

    But since mgo.GridFile also implements io.Seeker, you may take advantage of http.ServeContent(). Quoting its doc:

    The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests.

    Example handler serving a file:

    func serveFromDB(w http.ResponseWriter, r *http.Request) {
        var gridfs *mgo.GridFS // Obtain GridFS via Database.GridFS(prefix)
    
        name := "somefile.pdf"
        f, err := gridfs.Open(name)
        if err != nil {
            log.Printf("Failed to open %s: %v", name, err)
            http.Error(w, "something went wrong", http.StatusInternalServerError)
            return
        }
        defer f.Close()
    
        http.ServeContent(w, r, name, time.Now(), f) // Use proper last mod time
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵