Table of Contents
Question content
Solution
Home Backend Development Golang Use new io.FS to fs.WalkDir and list files across file system types

Use new io.FS to fs.WalkDir and list files across file system types

Feb 10, 2024 am 10:09 AM

使用新的 io.FS 到 fs.WalkDir 并列出跨文件系统类型的文件

php editor Strawberry recommends using the new io.FS to operate the file system, especially when using fs.WalkDir and listing files across file system types. This new feature can handle file operations more flexibly, allowing users to more easily obtain the file information they need. Whether in the development or maintenance process, this function can greatly improve efficiency and reduce tedious operations. If you want to know more about how to use this function, you may wish to continue reading and we will introduce you to the detailed steps and precautions.

Question content

I am using the new io.FS abstraction to traverse the file system and read the first 128 bytes of each file that matches our internal file extension.

These files are located in local file systems and archive files etc. (ZIP and Tar I thunk).

I'm using fs.WalkDir, passing in fs.FS (os.DIR and fstest.MapFS in my tests). When walking, I return a set of "files" (actually they are *.pzix and *.pzi files, which are our proprietary formats). I can't find a suitable way to use the FS interface to get some information about the file I'm working on.

I want:

  • Get file name
  • Get file size
  • Get openfile method

I find the interfaces from Java/C# in Go a bit confusing. I wish to operate on the abstraction, but I don't know how to get the other implementations of the file itself (e.g. the file interface has Stat() and read).

The easiest thing I've found is to store the path and filename in an array, then when I iterate over the array, determine if it's os.Dir or fstest.MapFS, but this seems rather counterintuitive:

func collectFiles(f fs.FS, root string) []string {
 var files []string
 fs.WalkDir(f, ".", func(p string, d fs.DirEntry, err error) error {
  if !d.IsDir() { // we also check a few other things in the filename here
   f = filepath.Abs(path.Join(root, p))
   files = append(files, f)
  }
 }
 return files
}
Copy after login

This gives me:

root = "m://" // mapfs
files = { "m://id-198271.pzi", "m://id-7125-092581.pzix"}
Copy after login

Is there a smarter way for me to handle the abstraction without doing these things? Because after returning the array, I have to "open" the file, read the first 128 bytes (the signature) and hash the rest of the file to make sure it's "valid".

Edit: To clarify, the collectFiles method is creating our main file hit list to be processed in another method. I want to pass local system files, zip files, and tar files into the method so that it can iterate over the files in the archive and add them to an array.

Wish there was a File interface that I could store in an array instead of a string so that subsequent callers could do f.open() without knowing what the underlying was.

Solution

p is the name in the file system.

Get the size by calling fs.Stat(f, p)

Use

f.Open(p) to open the file

Example:

f := os.DirFS("/etc")
fs.WalkDir(f, ".", func(p string, d fs.DirEntry, err error) error {
    if !d.IsDir() {
        st, _ := fs.Stat(f, p)
        r, _ := f.Open(p)
        defer r.Close()

        // Read prefix
        var buf [md5.Size]byte
        n, _ := io.ReadFull(r, buf[:])

        // Hash remainder
        h := md5.New()
        _, _ = io.Copy(h, r)
        s := h.Sum(nil)

        fmt.Printf("%s %d %x %x\n", p, st.Size(), buf[:n], s)
    }
    return nil
})
Copy after login

For the sake of brevity, this example ignores errors. Don't do this in real code.

https://www.php.cn/link/b599e8250e4481aaa405a715419c8179

The above is the detailed content of Use new io.FS to fs.WalkDir and list files across file system types. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

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. �...

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...

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...

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...

See all articles