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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?