Go comes with many packages. This example uses THE IO package and NET package apis to simply upload and download files based on HTTP (demo only).

Define file store file

// Assuming file upload is local server, base path of upload
const BaseUploadPath = "/var/file"
Copy the code

The main function listens for HTTP services

func main(a) {
	http.HandleFunc("/upload", handleUpload)
	http.HandleFunc("/download", handleDownload)

	err := http.ListenAndServe(": 3000".nil)
	iferr ! =nil  {
		log.Fatal("Server run fail")}}Copy the code

File upload processor

func handleUpload (w http.ResponseWriter, request *http.Request)  {
	// Only POST method is allowed for file upload
	ifrequest.Method ! = http.MethodPost { w.WriteHeader(http.StatusMethodNotAllowed) _, _ = w.Write([]byte("Method not allowed"))
		return
	}

	// Read the file from the form
	file, fileHeader, err := request.FormFile("file")
	iferr ! =nil {
		_, _ = io.WriteString(w, "Read file error")
		return
	}
	//defer closes the file at the end
	defer file.Close()
	log.Println("filename: " + fileHeader.Filename)

	// Create a file
	newFile, err := os.Create(BaseUploadPath + "/" + fileHeader.Filename)
	iferr ! =nil {
		_, _ = io.WriteString(w, "Create file error")
		return
	}
	//defer closes the file at the end
	defer newFile.Close()

	// Write the file locally
	_, err = io.Copy(newFile, file)
	iferr ! =nil {
		_, _ = io.WriteString(w, "Write file error")
		return
	}
	_,_ = io.WriteString(w, "Upload success")}Copy the code

File download processor

func handleDownload (w http.ResponseWriter, request *http.Request) {
	// Only GET method is allowed for file upload
	ifrequest.Method ! = http.MethodGet { w.WriteHeader(http.StatusMethodNotAllowed) _, _ = w.Write([]byte("Method not allowed"))
		return
	}
	/ / file name
	filename := request.FormValue("filename")
	if filename == "" {
		w.WriteHeader(http.StatusBadRequest)
		_, _ = io.WriteString(w, "Bad request")
		return
	}
	log.Println("filename: " + filename)
	// Open the file
	file, err := os.Open(BaseUploadPath + "/" + filename)
	iferr ! =nil {
		w.WriteHeader(http.StatusBadRequest)
		_, _ = io.WriteString(w, "Bad request")
		return
	}
	// Close the file
	defer file.Close()

	// Set the header for the response
	w.Header().Add("Content-type"."application/octet-stream")
	w.Header().Add("content-disposition"."attachment; filename=\""+filename+"\" ")
	// Write the file to responseBody
	_, err = io.Copy(w, file)
	iferr ! =nil {
		w.WriteHeader(http.StatusBadRequest)
		_, _ = io.WriteString(w, "Bad request")
		return}}Copy the code

Resources: golang.org/pkg/