亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang如何從nodejs字節數組創建文件

Golang如何從nodejs字節數組創建文件

Go
白豬掌柜的 2023-03-21 10:30:45
我的 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' });    });
查看完整描述

1 回答

?
LEATH

TA貢獻1936條經驗 獲得超7個贊

逐行翻譯 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)

// ...

這將幫助您測試 thandler 和存儲測試 :)


查看完整回答
反對 回復 2023-03-21
  • 1 回答
  • 0 關注
  • 125 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號