使用Golang如何从Node.js字节数组创建文件

huangapple go评论95阅读模式
英文:

Golang how to create file from nodejs array of bytes

问题

我的go服务器通过post请求接收到一个JS数组,数据如下所示:

使用Golang如何从Node.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
使用Golang如何从Node.js字节数组创建文件

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)
		// ...
	}
}

这将有助于测试处理程序和存储测试 使用Golang如何从Node.js字节数组创建文件

英文:

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 使用Golang如何从Node.js字节数组创建文件

huangapple
  • 本文由 发表于 2022年11月27日 07:43:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/74586448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定