Skip to content

Instantly share code, notes, and snippets.

@elulcao
Last active October 15, 2022 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elulcao/fa695e98356851e6b53893e0f25f4295 to your computer and use it in GitHub Desktop.
Save elulcao/fa695e98356851e6b53893e0f25f4295 to your computer and use it in GitHub Desktop.
goroutine and messages
package listfiles
import (
"fmt"
"os"
"regexp"
"strings"
"sync"
)
type Errors struct {
Message string
Error error
}
var wg sync.WaitGroup
func main() {
var wg sync.WaitGroup
var sliceFiles []string
var chErr []string
ch := make(chan Errors, 0)
filesInDir, err := os.ReadDir("/Users/elulcao/")
if err != nil {
fmt.Println("No files in dir" + err.Error())
return
}
for _, f := range filesInDir {
fName := string(f.Name())
re := regexp.MustCompile(`(.*).txt$`)
match := re.MatchString(fName)
if !match {
continue
}
sliceFiles = append(sliceFiles, fName)
}
for _, f := range sliceFiles {
fmt.Println("File: " + f)
go listFilesWithExt(f, ch, &wg)
}
fmt.Println("Finished the process")
for _ = range sliceFiles {
c := <-ch
if c.Error != nil {
chErr = append(chErr, c.Error.Error())
}
}
wg.Wait()
for _, c := range chErr {
fmt.Println(c)
}
}
func listFilesWithExt(file string, ch chan Errors, wg *sync.WaitGroup) {
wg.Add(1)
defer wg.Done()
if strings.Contains(file, "BadWord") {
ch <- Errors{"NOK:", fmt.Errorf("File with BadWord " + file)}
return
}
fmt.Println(file)
ch <- Errors{"OK:", nil}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment