1 回答

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 和存儲測試 :)
- 1 回答
- 0 關注
- 125 瀏覽
添加回答
舉報