英文:
Golang how to create file from nodejs array of bytes
问题
我的go服务器通过post请求接收到一个JS数组,数据如下所示:
如何将这些数据写入文件?
在Node.js中,可以像这样实现:
fs.writeFile(`${dir}/${body.file_name}`, Buffer.from(body.file), { flag: "w" }, function (err) {
if (err) {
console.log(err);
return res.status(200).json({ 'status': 'error' });
}
console.log(`文件成功保存到"${dir}${body.file_name}"`);
return res.status(200).json({ 'status': 'ok' });
});
英文:
My go server recieves a JS array by post request, getting data like this
How do I write this to an a file?
In node.js I can do it like this:
fs.writeFile(`${dir}/${body.file_name}`, Buffer.from(body.file), { flag: "w" }, function (err) {
if (err) {
console.log(err);
return res.status(200).json({ 'status': 'error' });
}
console.log(`file sucessfully saved to "${dir}${body.file_name}"`);
return res.status(200).json({ 'status': 'ok' });
});
答案1
得分: 1
逐行翻译成Go语言的代码如下:
func handleIncommingFile() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Body == nil {
log.Println("body is empty")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{ 'status': 'error' }`))
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
log.Printf("reading body: %v", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{ 'status': 'error' }`))
return
}
defer r.Body.Close()
if err := os.WriteFile("path/to/filename.ext", body, 0644); err != nil {
log.Printf("writting content: %v", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{ 'status': 'error' }`))
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{ 'status': 'ok' }`))
}
}
请注意,根据错误的上下文,我返回了不同的HTTP状态码,并且有一些缺少的检查,例如,如果文件已经存在。
另外,我建议将存储服务注入到处理程序中,以简化处理程序并将文件创建逻辑移动到另一个包中。
func handleIncommingFile(store storage.Manager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := store.Save(r.Body); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
// ...
}
}
这将有助于测试处理程序和存储测试
英文:
Translating line by line to go would result into something like this:
func handleIncommingFile() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Body == nil {
log.Println("body is empty")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{ 'status': 'error' }`))
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
log.Printf("reading body: %v", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{ 'status': 'error' }`))
return
}
defer r.Body.Close()
if err := os.WriteFile("path/to/filename.ext", body, 0644); err != nil {
log.Printf("writting content: %v", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{ 'status': 'error' }`))
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{ 'status': 'ok' }`))
}
}
Note that I'm returning different HTTP Status Code depending on the error context and that there are missing checks, for example, if the file already exist.
Also I would recommend to inject an storage service to the handler to simplify it and move the file creation logic to another package.
func handleIncommingFile(store storage.Manager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := store.Save(r.Body); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
// ...
This will help you to test thandler and storage testing
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论