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
    • Helm Chart
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log & Monitor
    • 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

  • 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

[GRPC/Golang] Bắt đầu Project Grpc với golang trên Windows. Coding
[Golang] Note mấy thứ hay ho về golang Coding
[go-git] returned a non-zero code: 1 when building docker Golang
[kubernetes/client-go] Go clients for talking to a kubernetes cluster. Golang
[Goland/Echo Framework/For loop] Return the results twice when using the echo framework and for loop on Goland Golang
[Golang/Container] Build docker/container Golang Coding

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

  • Experiences for IP Addresses Shortage on EKS Clusters March 29, 2023
  • [Talisman] Discover the sensitive information in your code. March 28, 2023
  • [Prometheus/Grafana] Install Prometheus and Grafana on ubuntu. March 27, 2023
  • [Kong Gateway] WebSocket connection failed March 26, 2023
  • [Nextcloud] Can’t download files to have a size bigger than 2Gi on NextCloud – RaspBerry March 24, 2023

Archives

  • 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
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • Golang
    • Jquery & JavaScript
    • Laravel
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
    • Longhorn – Storage
    • MetalLB
    • Vault
    • VictoriaMetrics
  • Log & Monitor
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2023 NimTechnology.