noob Golang 和 Sinatra 人在这里。我破解了一个 Sinatra 应用程序,以接受从 HTML 表单发布的上传文件,并通过 GridFS 将其保存到托管的 MongoDB 数据库中。这似乎工作正常。我正在使用 mgo 驱动程序在 Golang 中编写相同的应用程序。
从功能上讲,它工作正常。但是在我的 Golang 代码中,我将文件读入内存,然后使用 mgo 将文件从内存写入 MongoDB。这似乎比我的同等 Sinatra 应用程序慢得多。我觉得 Rack 和 Sinatra 之间的交互不会执行这个“中间”或“中间”步骤。
这是我的 Go 代码片段:
func uploadfilePageHandler(w http.ResponseWriter, req *http.Request) {
// Capture multipart form file information
file, handler, err := req.FormFile("filename")
if err != nil {
fmt.Println(err)
}
// Read the file into memory
data, err := ioutil.ReadAll(file)
// ... check err value for nil
// Specify the Mongodb database
my_db := mongo_session.DB("... database name...")
// Create the file in the Mongodb Gridfs instance
my_file, err := my_db.GridFS("fs").Create(unique_filename)
// ... check err value for nil
// Write the file to the Mongodb Gridfs instance
n, err := my_file.Write(data)
// ... check err value for nil
// Close the file
err = my_file.Close()
// ... check err value for nil
// Write a log type message
fmt.Printf("%d bytes written to the Mongodb instance\n", n)
// ... other statements redirecting to rest of user flow...
}
问题:
- 是否需要这个“临时”步骤(
data, err := ioutil.ReadAll(file)
)? - 如果是这样,我可以更有效地执行此步骤吗?
- 我应该考虑其他公认的做法或方法吗?
谢谢...