首頁  >  文章  >  後端開發  >  Golang如何從nodejs位元組數組建立文件

Golang如何從nodejs位元組數組建立文件

WBOY
WBOY轉載
2024-02-09 11:39:29460瀏覽

Golang如何從nodejs位元組數組建立文件

php小編香蕉將為你介紹如何使用Golang從nodejs位元組陣列建立檔案。在開發過程中,我們經常需要將位元組數組儲存為檔案。使用Golang,我們可以輕鬆地完成這個任務。首先,我們需要將nodejs位元組陣列傳送到Golang服務端。然後,使用Golang的io/ioutil套件中的WriteFile函數將位元組陣列寫入檔案。透過這種簡單的方法,我們可以實現從nodejs位元組數組建立檔案的功能。接下來,我們將詳細解釋這個過程的步驟和程式碼範例。讓我們開始吧!

問題內容

我的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(`file sucessfully saved to "${dir}${body.file_name}"`);
        return res.status(200).json({ 'status': 'ok' });
    });

解決方法

逐行翻譯 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如何從nodejs位元組數組建立文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除