- Go Web Development Cookbook
- Arpit Aggarwal
- 362字
- 2021-08-27 19:01:20
How it works…
Once we run the program, the HTTP server will start locally listening on port 8080. Browsing http://localhost:8080 will show us the File Upload Form, as shown in the following screenshot:

Pressing the Submit button after choosing a file will result in the creation of a file on the server with the name as uploadedFile inside the /tmp directory. You can see this by executing the following commands:

Also, the successful upload will display the message on the browser, as shown in the following screenshot:

Let's understand the Go program we have written:
We defined the fileHandler() handler, which gets the file from the request, reads its content, and eventually writes it onto a file on a server. As this handler does a lot of things, let’s go through it in detail:
- file, header, err := r.FormFile("file"): Here we call the FormFile handler on the HTTP request to get the file for the provided form key.
- if err != nil { log.Printf("error getting a file for the provided form key : ", err) return }: Here we check whether there is any problem while getting the file from the request. If there is, then log the error and exit with a status code of 1.
- defer file.Close(): The defer statement closes the file once we return from the function.
- out, pathError := os.Create("/tmp/uploadedFile"): Here we are creating a file named uploadedFile inside a /tmp directory with mode 666, which means the client can read and write but cannot execute the file.
- if pathError != nil { log.Printf("error creating a file for writing : ", pathError) return }: Here we check whether there are any problems with creating a file on the server. If there are, then log the error and exit with a status code of 1.
- _, copyFileError := io.Copy(out, file): Here we copy content from the file we received to the file we created inside the /tmp directory.
- fmt.Fprintf(w, "File uploaded successfully : "+header.Filename): Here we write a message along with a filename to an HTTP response stream.
- Hands-On Full Stack Development with Spring Boot 2 and React(Second Edition)
- 世界互聯(lián)網(wǎng)發(fā)展報(bào)告·2019
- 數(shù)字調(diào)制解調(diào)技術(shù)的MATLAB與FPGA實(shí)現(xiàn):Altera/Verilog版(第2版)
- 圖解手機(jī)元器件維修技巧
- 面向5G-Advanced的關(guān)鍵技術(shù)
- Scala Design Patterns.
- 網(wǎng)絡(luò)利他行為研究:積極心理學(xué)的視角
- 移動物聯(lián)網(wǎng):商業(yè)模式+案例分析+應(yīng)用實(shí)戰(zhàn)
- 物聯(lián)網(wǎng)的機(jī)遇與利用
- Laravel Application Development Cookbook
- 物聯(lián)網(wǎng)
- 智慧城市中的物聯(lián)網(wǎng)技術(shù)
- 物聯(lián)網(wǎng)導(dǎo)論
- Hands-On Microservices:Monitoring and Testing
- 物聯(lián)網(wǎng)系統(tǒng)設(shè)計(jì)