Home > database >  Golang how to create file from nodejs array of bytes
Golang how to create file from nodejs array of bytes

Time:11-28

My go server recieves a JS array by post request, getting data like this screenshot

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' });
    });

CodePudding user response:

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 :)

  • Related