Home Backend Development Golang 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

Jul 29, 2023 pm 10:37 PM
go language File operations Encrypted compression

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
Copy after login

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)
}
Copy after login

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)
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

See all articles