Golang:multiple Http.writeheader Calls

Source: Internet
Author: User
Tags sprintf

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.