Home  >  Article  >  Backend Development  >  Learn the file operation functions in Go language and implement the encryption, compression, upload and download functions of files

Learn the file operation functions in Go language and implement the encryption, compression, upload and download functions of files

WBOY
WBOYOriginal
2023-07-29 22:37:091729browse

Learn the file operation functions in Go language and implement the encryption, compression, upload and download functions of files

Go language is an open source statically typed programming language. It is popular in the development field for its efficient performance and concise syntax. Very popular. The standard library of the Go language provides a wealth of file operation functions, making it very simple to read and write files, encrypt and compress them, upload and download them. This article will introduce how to use the file operation functions in the Go language to implement the functions of encrypting, compressing, uploading and downloading files.

First, we need to import the relevant third-party libraries. In the Go language, you can use the archive/zip library to achieve file compression, the crypto/aes library to implement file encryption and decryption, and the io/ioutilLibrary to implement file reading and writing operations. We can use the Go language package management tool go get to obtain these libraries:

go get -u github.com/golang/example/hello/archive/zip
go get -u github.com/golang/example/hello/crypto/aes
go get -u github.com/golang/example/hello/io/ioutil

Let’s write code to implement the file encryption and compression function:

package main

import (
    "archive/zip"
    "crypto/aes"
    "crypto/cipher"
    "io/ioutil"
    "os"
)

func main() {
    // 读取原始文件
    file, _ := os.Open("original.txt")
    defer file.Close()
    data, _ := ioutil.ReadAll(file)

    // 使用AES加密算法对文件进行加密
    key := []byte("thisisaeskey12345")
    block, _ := aes.NewCipher(key)
    ciphertext := make([]byte, len(data))
    block.Encrypt(ciphertext, data)

    // 创建压缩文件
    zipfile, _ := os.Create("encrypted.zip")
    defer zipfile.Close()
    zipWriter := zip.NewWriter(zipfile)

    // 将加密后的文件写入压缩文件
    zipfiledata, _ := zipWriter.Create("encrypted.txt")
    zipfiledata.Write(ciphertext)

    // 关闭压缩文件
    zipWriter.Close()

    // 读取压缩文件
    zipfile, _ = os.Open("encrypted.zip")
    defer zipfile.Close()
    zipReader, _ := zip.NewReader(zipfile, int64(len(ciphertext)))

    // 解压缩文件
    unzipdata, _ := zipReader.File[0].Open()
    defer unzipdata.Close()
    unzipdatacontent, _ := ioutil.ReadAll(unzipdata)

    // 使用AES解密算法对文件进行解密
    decrypter := cipher.NewCFBDecrypter(block, block.iv)
    plainText := make([]byte, len(unzipdatacontent))
    decrypter.XORKeyStream(plainText, unzipdatacontent)

    // 输出解密后的文件内容
    ioutil.WriteFile("decrypted.txt", plainText, 0644)
}

Above In the code, we first read an original file named original.txt and store its contents in the data variable. We then encrypt the file using the AES encryption algorithm and store the encrypted data in ciphertext.

Next, we created a compressed file named encrypted.zip and wrote the encrypted file contents into it. Then, we used the archive/zip library to read the contents of the compressed file and decompressed it into the unzipdatacontent variable.

Finally, we use the AES decryption algorithm to decrypt the decompressed data and write the decrypted content into a file named decrypted.txt.

Through the above steps, we have implemented the function of encrypting and compressing files.

Next, we will implement the file upload and download functions. In order to achieve this function, we can use the net/http library and the os library.

package main

import (
    "io"
    "net/http"
    "os"
)

func uploadFile(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(32 << 20) // 设置最大上传文件大小为32MB

    file, handler, err := r.FormFile("file")
    if err != nil {
        w.WriteHeader(http.StatusBadRequest)
        return
    }
    defer file.Close()

    f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    defer f.Close()
    io.Copy(f, file)

    w.WriteHeader(http.StatusOK)
}

func downloadFile(w http.ResponseWriter, r *http.Request) {
    fileName := r.URL.Query().Get("file")
    if fileName == "" {
        w.WriteHeader(http.StatusBadRequest)
        return
    }

    file, err := os.Open(fileName)
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    defer file.Close()

    fi, err := file.Stat()
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
    w.Header().Set("Content-Type", "application/octet-stream")
    w.Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))

    io.Copy(w, file)
}

func main() {
    http.HandleFunc("/upload", uploadFile)
    http.HandleFunc("/download", downloadFile)
    http.ListenAndServe(":8080", nil)
}

In the above code, we first implemented a uploadFile function to handle the file upload function. In this function, we obtain the uploaded file through the r.FormFile method and save it to the local file system of the server.

Then, we implemented a downloadFile function to handle the file download function. In this function, we open the specified file through the os.Open method and write it to the ResponseWriter through the io.Copy method so that Client Downloads.

Finally, we specify the route to handle uploading and downloading by calling the http.HandleFunc method, and then use http.ListenAndServe to start a local server and listen to port 8080 .

Through the above code, we realize the encryption, compression, upload and download functions of files. You can replace the file name and key yourself for testing. I hope this article will be helpful to you in learning the file operation functions in Go language.

The above is the detailed content of Learn the file operation functions in Go language and implement the encryption, compression, upload and download functions of files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn