Background: Golang HTTP service, read files, provided to the client when downloading. Multiple Http.writeheader calls error occurred.
Func DownloadFile (w http. Responsewriter, R *http. Request, Sequence UInt64, UserIDstring) {userkey:=userid FileName:= R.formvalue ("filename") ifLen (UserKey) <=0|| Len (filename) <=0 { //........} fp:= Fmt. Sprintf ("%s%s/%s", G_sc. RootDir, userkey, filename) fd, err:=OS. Open (FP)ifErr = =Nil {defer FD. Close () buf, err:=Ioutil. ReadAll (FD)ifErr! =Nil {//.........}Else{size:=Len (BUF) W.header (). ADD ("Content-length"Fmt. Sprintf ("%d", size)) Fmt. Fprint (W,string(BUF))} }}
The problem occurs in these lines of code:
Size: = Len (BUF)
W.header (). ADD ("Content-length", FMT. Sprintf ("%d", size))
Fmt. Fprint (W, String (BUF))
The following modifications can be made:
buf: = new (bytes. Buffer) buf. Write (...) if err { // HTTP. Error (W, err. String, http. Statusinternalservererror) return } if err: = buf. WriteTo (w); Err!= nil {log. Printf ( writeto:%v " , err) // You can not use HTTP. Error here anymore. So just log the message (e.g. "broken pipe ...") }
or comment the two lines of codeSize: = Len (BUF)
W.header (). ADD ("Content-length", FMT. Sprintf ("%d", size))
Fmt. Fprint (W, String (BUF))
Golang:multiple Http.writeheader Calls