Golang get zip file via HTTP response

Source: Internet
Author: User
Tags sprintf getzip
This is a creation in Article, where the information may have evolved or changed.

I planned to summarize what I learned at least once a week, but it didn't seem to come true.

A look at the time is April 1, one months, always write something

Recently bad luck, out a lot of things, although all are outsiders things, but really affect the mood, I hope everyone can open a happy heart every day

Write a request for a few days ago: Zip file to get user information through a URL

Do not involve too much business content, is to write a small demo, through a given URL, get a zip file

Implement a very simple URL-handling route

Since it's a demo, then it's Golang the simplest listenandserve of the route.

func main() {    http.HandleFunc("/zipdownload", zipHandler)    log.Println("Listening...")    http.ListenAndServe(":9999", nil)}

Complete the Ziphandler function

Complete the Ziphandler function according to Golang's handler function signature invitation

func Ziphandler(RW http. Responsewriter,R*http. Request) {Zipname:="Ziptest.zip"rw.Header().Set("Content-type","Application/zip") RW.Header().Set("Content-disposition"Fmt. Sprintf ("attachment; Filename=\ "%s\" ", zipname)) Err: =Getzip(rw) If err! = Nil {log.Fatal(ERR)}}

Setting the response header information

rw.Header().Set("Content-Type", "application/zip")

Sets the file type in the header information of the response, and for the zip file, it can generally be set to application/zip orapplication/octet-stream
More specifically, it can be obtained in the complete list of MIME types, which I have chosen application/zip to tell the server the exact file type

rw.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", zipName))

Set Content-Disposition to the attachment attachment type, and set the attachment file name to our givenzipName

The response header information Content-Disposition is used to inform the browser that the file it gets to is required to be displayed with the page or to be saved as an attachment to the user locally, if needed to be displayed in the page, set to inline , otherwise set to attachemnt , when set to the attachment additional file name of the attachment can be specified, More specific instructions can be obtained at content-disposition.

After the completion of these two lines of code, the function has actually completed the more than half, at first I was stuck in this place, in the demand for the idea bubble filled with 怎么样才能让HTTP响应得到一个zip文件并且让浏览器将这个文件下载下来而不是试图展示出来 problems

Complete the Getzip function

Here we just need to complete a comparative basis of the zip process, as I said above, the most difficult thing is actually the above HTTP response in the header information understanding

 func getzip(w io. Writer) error {ZIPW: = zip. Newwriter (W)deferZipw.close () forI: =0; I <5; i++ {f, err: = Zipw.create (StrConv. Itoa (i) +". txt")ifErr! =Nil{returnErr} _, Err = F.write ([]byte(FMT. Sprintf ("Hello file%d", i)))ifErr! =Nil{returnERR}}return Nil}

Create a zip. Writer

zipW := zip.NewWriter(w)

The method creates a zip.Writer file that is used to write to the zip file, which is packaged

parameter is io.Writer , then of course we are usinghttp.ResponseWriter

The return value is one zip.Writer , the last zip content is written zip.Writer to this, and of course it is written io.Writer in the parameters, that is, our http.ResponseWriter

Remember to defer zipW.Close() closezip.Writer

to zip. Writing files in writer

f, err := zipW.Create(strconv.Itoa(i) + ".txt")

This method zip.Writer adds a file to the zip file, which means adding a file to the

The parameter is a string that will be used as the file name for writing to the zip

The first return value is one, which is used to write the contents of the file to a io.Writer file that we add to the zip, as shown in the _, err = f.Write([]byte(fmt.Sprintf("Hello file %d", i))) code, and we write a simple string to the file

Run the program

Next, just run the program in the main.go directory where go run main.go you can access it in your browser localhost:9999/zipdownload , and the browser will download a zip file


Download the ziptest and unzip the content

Finally, the code has been uploaded to my github repository to download the test directly

At the end, the last article when I spit trough the next Pinterest always do not let me posted outside the chain of pictures and other articles released, today and try the next, incredibly did not have this problem, such as the picture in this article is outside the chain, happy

Most finally, of course, welcome to my personal blog.

Related Article

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.