Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[Golang] Looking filepath.Walk to return any file and children folder in the folder

Posted on February 24, 2023February 25, 2023 By nim No Comments on [Golang] Looking filepath.Walk to return any file and children folder in the folder

The filepath.Walk function is used to traverse a directory tree recursively, starting from a given directory path. It walks the directory tree and calls a given function once for each file or directory found, passing in information about that file or directory.

The function signature of filepath.Walk is:

func Walk(root string, walkFn WalkFunc) error

where root is the starting directory path, and walkFn is the function to be called for each file or directory encountered. The WalkFunc signature is:

type WalkFunc func(path string, info os.FileInfo, err error) error

where path is the full path to the file or directory, info is an os.FileInfo object containing information about the file or directory, and err is any error that occurred during the operation.

The WalkFunc function should return an error if the operation failed for some reason. Returning an error will cause filepath.Walk to stop walking the directory tree and return the error.

Here’s an example use of filepath.Walk:

package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    root := "/path/to/directory"

    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }

        if info.IsDir() {
            fmt.Printf("Directory: %s\n", path)
        } else {
            fmt.Printf("File: %s\n", path)
        }

        return nil
    })

    if err != nil {
        fmt.Println("Error:", err)
    }
}

In this example, we start at the directory /path/to/directory and walk the directory tree recursively. For each file or directory found, we print a message to the console indicating whether it is a file or a directory.

If any errors occur during the walk operation, they are returned and printed to the console.

Contents

Toggle
  • Error
    • lstat /xxx/xxx/xxx: no such file or directory
    • Ignored – lstat /xxx/xxx/xxx: no such file or directory

Error

lstat /xxx/xxx/xxx: no such file or directory

you need to first determine why the file or directory is not found. Here are some steps you can take to troubleshoot and fix the issue:

  1. Check if the file or directory exists: Double-check that the file or directory you’re trying to access actually exists in the specified location. You can do this using the os.Stat function to check if the file or directory exists, like this:
if _, err := os.Stat("/app/downloaded/0db75a60ca10ec57ab03f285e268b050e9f8dc10116780de4fd4180a40559317"); os.IsNotExist(err) {
    fmt.Println("File or directory does not exist")
}

2. Check your permissions: Make sure that you have the necessary permissions to access the file or directory. You can use the os.Stat function to check the file or directory permissions, like this:

info, err := os.Stat("/app/downloaded/0db75a60ca10ec57ab03f285e268b050e9f8dc10116780de4fd4180a40559317")
if err != nil {
    fmt.Println("Error:", err)
}

mode := info.Mode()
if mode&os.ModePerm != 0 {
    fmt.Println("File or directory is accessible")
} else {
    fmt.Println("File or directory is not accessible")
}

If the file or directory is not accessible, you may need to adjust the file permissions or run your program with elevated privileges.

  1. Use a lock to prevent race conditions: If you suspect that a race condition is causing the error, you can use a lock to prevent multiple processes or threads from accessing the same file or directory at the same time. You can use the sync package to implement a mutex lock, like this:
var mutex = &sync.Mutex{}

func main() {
    // ...

    // Use a mutex lock to prevent race conditions
    mutex.Lock()
    defer mutex.Unlock()

    // Access the file or directory here
    // ...
}

By using a lock, you can ensure that only one process or thread can access the file or directory at a time, preventing race conditions and potential errors.

If you’re still having trouble, it may be helpful to add more error handling and logging to your program to help you pinpoint exactly where the error is occurring.

Ignored – lstat /xxx/xxx/xxx: no such file or directory

If you want to ignore errors like “lstat … no such file or directory” and continue walking the directory tree, you can simply return nil from the error function, like this:

err := filepath.Walk("/path/to/directory", func(path string, info os.FileInfo, err error) error {
    if err != nil {
        // Ignore "no such file or directory" errors
        if os.IsNotExist(err) {
            return nil
        }

        fmt.Println("Error accessing file or directory:", err)
        return err
    }

    // ...
    return nil
})

if err != nil {
    fmt.Println("Error walking directory:", err)
}

This example checks if the error is a “no such file or directory” error using the os.IsNotExist function. If it is, it simply returns nil to continue walking the directory tree. If it’s any other type of error, it’s printed to the console and returned. Finally, any errors that occur while walking the directory are printed to the console.

Note that ignoring errors like this can be dangerous, as it may cause your program to skip over important files or directories that it should be processing. It’s generally better to handle errors more carefully and avoid ignoring them if possible.

Golang

Post navigation

Previous Post: [Linux] Error when run apt update
Next Post: [aws-sdk-go] Integrate with AWS by golang

More Related Articles

[go-git] returned a non-zero code: 1 when building docker Golang
Hướng Dẫn Nhúng Tệp Tĩnh Vào Go Sử Dụng go:embed Golang
[Golang] List large files in the folder quickly on Golang Golang
[Golang] Thiết kế model trong golang và echo framework. Golang
[Terminal/Huh] Build Terminal Form By golang. Golang
[Golang] Writing a metrics exporter through Golang and Prometheus Golang

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Laravel] Laravel Helpful June 26, 2025
  • [VScode] Hướng dẫn điều chỉnh font cho terminal June 20, 2025
  • [WordPress] Hướng dấn gửi mail trên WordPress thông qua gmail. June 15, 2025
  • [Bitbucket] Git Clone/Pull/Push with Bitbucket through API Token. June 12, 2025
  • [Teamcity] How to transfer the value from pipeline A to pipeline B June 9, 2025

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.