我目前正在使用 Go 開發一個圖像處理程序,它旨在拒絕上傳不受支持的文件。我的意圖是讓 Go 程序通過服務器 http.ResponceWritter 返回錯誤,詳細說明拒絕的情況,作為 json,供上傳服務使用。如何在服務器代碼中設置錯誤:type Error struct { ImgHandlerError `json:"error"`}type ImgHandlerError struct { Message string `json:"message"` Code string `json:"code"`}func MakeError(message, code string) *Error { errorMessage := &Error{ ImgHandlerError: ImgHandlerError{ Message: message, Code: code, }, } return errorMessage}func ThrowErr(errorMessage Error, writer http.ResponseWriter) { jData, err := json.Marshal(errorMessage) if err != nil { } writer.Header().Set("Content-Type", "application/json") writer.WriteHeader(http.StatusForbidden) writer.Write(jData) return}如何生成錯誤并將其寫入 HTTP 響應:errorMes := *MakeError("PSD files are not supported", "DEF-IMG-0006")ThrowErr(errorMes, res)目前這按預期工作,例如,當上傳 .psd 時,當前 HTTP 響應返回為 JSON。{"error":{"message":"PSD files are not supported","code":"DEF-IMG-0006"}}我現在的問題是測試這個,因為我力不從心,因為這是我的第一個 Go 程序。我正在使用 Ginko 測試套件。我已經嘗試在測試套件中設置http.ResponseRecorder(因為我認為這就是解決方案所在)但我沒有運氣。此外,我當前在測試套件中的測試僅測試不需要作為writer http.ResponseWriter參數的功能,因此我不確定是否需要在測試套件中啟動服務器才能讀取響應編寫器。任何幫助是極大的贊賞
- 0 回答
- 0 關注
- 154 瀏覽
添加回答
舉報
0/150
提交
取消