Last active
October 15, 2022 17:03
-
-
Save elulcao/fa695e98356851e6b53893e0f25f4295 to your computer and use it in GitHub Desktop.
goroutine and messages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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