I wrote a small REST api in Go and I use the same functions to return http.Response with a status code and a message:
type apiResponse struct {
Status int `json:"status"`
Message string `json:"message"`
}
I collect this in a json string and using w.Write()to put it in the response.
The API has three endpoints, one of which allows the user to upload a file. Two work fine, and I get the answer I expect. The download endpoint returns a valid response with Content-Lengththat matches the expected message, but when I read it (using ioutil.ReadAll) it is empty!
What am I doing wrong?
This is the body read function:
func readResponseContent(resp *http.Response) string {
defer resp.Body.Close()
fmt.Println(resp)
fmt.Println(resp.ContentLength)
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error in response: %s", err.Error())
os.Exit(1)
}
bodyString := string(bodyBytes)
return bodyString
}
and this is the handler:
func handleSubmission(w http.ResponseWriter, r *http.Request) {
var Buf bytes.Buffer
file, header, err := r.FormFile(audioUploadKey)
if err != nil {
log.Printf("Error uploading file: %s\n", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer file.Close()
jobID, _ := uuid.NewUUID()
_ = os.MkdirAll(path.Join(jobsPath, jobID.String()), 0750)
log.Printf("Received file %s\n", header.Filename)
io.Copy(&Buf, file)
fileOut, _ := os.Create(path.Join(jobsPath, jobID.String(),
Buf.WriteTo(fileOut)
Buf.Reset()
apiResp := apiResponse{Status:http.StatusCreated, Message:jobID.String()}
jsonResp, _ := json.Marshal(apiResp)
writeJSONResponse(w, jsonResp)
return}