Upload and download HTTP files using the Go language

Source: Internet
Author: User
Tags html form
This is a creation in Article, where the information may have evolved or changed. I recently completed a formal Web application using the Go language, and there are some aspects that are important in the process of using go to develop Web applications. In the past, I used web development as a profession and developed Web applications using different languages and paradigms as a hobby, so I had some experience in web development. In general, I like to use the Go language for web development, although it begins to take some time to adapt. The go language has some pits, but as the file upload and download to be discussed in this article, the standard library of the Go language and built-in functions make development a pleasant experience. In the next few articles, I'll focus on some of the issues I encountered when writing a production-level WEB application in Go, especially with regard to authentication/authorization. This article will show a basic example of HTTP file uploads and downloads. We use an HTML form with a ' type ' text box and a ' uploadfile ' upload box as the client. Let's look at how the Go language solves this problem that is ubiquitous in web development. # # code example first, we set two routes on the server side, '/upload ' for file uploads, '/files/* ' for file downloads. "' Goconst maxuploadsize = 2 * 1024x768 *//2 MB Const UPLOADPATH ="./tmp "Func main () {http. Handlefunc ("/upload", Uploadfilehandler ()) FS: = http. Fileserver (http. Dir (Uploadpath)) http. Handle ("/files/", http. Stripprefix ("/files", FS)) log. Print ("Server started on localhost:8080, use/upload-Uploading files And/files/{filename} for downloading files.") Log. Fatal (http. Listenandserve (": 8080", nil)} "We also want to upload the target directory, and we accept the maximum file size defined as constants." Note here that the concept of the entire file service is so simple-we use only the tools in the standard library, using ' http '. Fileserve ' Creates an HTTP handler that willUse ' http '. Dir (Uploadpath) ' provides a directory to upload files. Now we just need to implement ' Uploadfilehandler '. This handler will contain the following features:-Verify file maximum-from request verification file and POST parameters-check the provided file type (we only accept images and PDFs)-Create a random filename-write file to hard disk-handle all errors if everything goes smoothly back to success message first step, We define handlers: "' gofunc uploadfilehandler () http. Handlerfunc {return HTTP. Handlerfunc (Func (w http. Responsewriter, R *http. Request) {"' Then we use ' http '. Maxbytesreader ' validates the file size and returns an error when the file size is greater than the set value. The error will be handled by an assistant program ' Rendererror ', which returns the error message and the corresponding HTTP status code. "' Gor. Body = http. Maxbytesreader (W, r.body, maxuploadsize) If err: = R.parsemultipartform (maxuploadsize); Err! = Nil {rendererror (W, "File_too_big", http. statusbadrequest) Return} "if the file size verification is passed, we will examine and parse the form parameter type and upload the file and read the file. In this case, for clarity, we don't use fancy ' io. Reader ' and ' IO. Writer ' interface, we simply read the file into a byte array, which we'll write later. "' Gofiletype: = R.postformvalue (" type ") file, _, Err: = R.formfile (" UploadFile ") if err! = Nil {rendererror (W," Invalid_fi LE ", http. statusbadrequest) Return}defer file. Close () filebytes, err: = Ioutil. ReadAll (file) if err! = Nil {rendererror (W, "Invalid_file", http. Statusbadrequest) RetuRN} "Now that we have successfully verified the size of the file and read the file, then we have to verify the file type." A cheap but insecure way to check only the file name extension and trust that the user hasn't changed it, but not for a formal project. Fortunately, the Go Standard library provides us with an ' HTTP. Detectcontenttype ' function, which is based on the ' Mimesniff ' algorithm, which only needs to read the first 512 bytes of a file to determine the file type. "' Gofiletype: = http. Detectcontenttype (filebytes) if filetype! = "Image/jpeg" && filetype! = "Image/jpg" &&filetype! = "image/ GIF "&& filetype! =" Image/png "&&filetype! =" Application/pdf "{rendererror (W," Invalid_file_type ", http. statusbadrequest) return} ' in a real application, we might use file metadata to do things like save it to a database or push it to an external service--in any way, we will parse and manipulate the metadata. Here we create a random new name (which may be a UUID in practice) and record the new file name. "' Gofilename: = Randtoken (fileendings), err: = MIME. Extensionsbytype (fileType) if err! = Nil {rendererror (W, "Cant_read_file_type", http. Statusinternalservererror) Return}newpath: = FilePath. Join (Uploadpath, filename+fileendings[0]) fmt. Printf ("FileType:%s, File:%s\n", FileType, NewPath) "is almost done, just one key step-write the file. As mentioned above, we only need to copy the read binary file into a newly created file handler named ' NewFile '. If all the parts are okay, we return a ' SUCCESS ' message to the user. "' GOnewfile, err: = OS. Create (NewPath) if err! = Nil {rendererror (W, "Cant_write_file", http. Statusinternalservererror) Return}defer Newfile.close () If _, Err: = Newfile.write (filebytes); Err! = Nil {rendererror (W, "Cant_write_file", http. Statusinternalservererror) Return}w.write ([]byte ("SUCCESS")) ' That's OK. You can test this simple example by using a virtual file to upload an HTML page, CURL, or a tool such as [Postman] (https://www.getpostman.com/). Here is the complete code example [here] (https://github.com/zupzup/golang-http-file-upload-download) # # # Conclusion This is yet another testament to how Go allows users to write simple and powerful software for the web, Instead of dealing with the myriad layers of abstraction inherent in other languages and ecosystems. For the rest of the space, I'll show you some of the other details in the first time I've written a formal web app using the Go language. ;)//Modify part of the code according to Reddit user ' Lstokeworth ' feedback. Thank you:) # # # resources [FULL code example] (https://github.com/zupzup/golang-http-file-upload-download)

via:https://zupzup.org/go-http-file-upload-download/

Author: zupzup Translator: Fengchunsgit proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

3,316 reads ∙1 likes
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.