Home  >  Article  >  Backend Development  >  Golang how to create file from nodejs byte array

Golang how to create file from nodejs byte array

WBOY
WBOYforward
2024-02-09 11:39:29458browse

Golang how to create file from nodejs byte array

php editor Banana will introduce you how to use Golang to create files from nodejs byte arrays. During development, we often need to save byte arrays as files. Using Golang, we can accomplish this task easily. First, we need to transfer the nodejs byte array to the Golang server. Then, use the WriteFile function in Golang's io/ioutil package to write the byte array to the file. With this simple method, we can implement the function of creating files from nodejs byte array. Next, we explain the steps and code examples of this process in detail. let's start!

Question content

My go server receives a js array through a post request, and the data obtained is like this

How to write it to a file?

In node.js I can do 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' });
    });

Solution

Line-by-line translation go will produce the following results:

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 codes depending on the error context, and that there are missing checks, such as whether the file already exists.

Additionally, I recommend injecting the storage service into 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 test handlers and storage tests :)

The above is the detailed content of Golang how to create file from nodejs byte array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete