Skip to content

Instantly share code, notes, and snippets.

@Voles
Created March 4, 2019 20:37
Show Gist options
  • Save Voles/3c7e0859ef6434c5bbbafc32bfc8f742 to your computer and use it in GitHub Desktop.
Save Voles/3c7e0859ef6434c5bbbafc32bfc8f742 to your computer and use it in GitHub Desktop.
Go channel experiment
// Directory maps every file from a directory into an API model
func Directory(directory string) ([]models.API, error) {
files, err := ioutil.ReadDir(directory)
workerQueue := make(chan string)
APImodelsChan := make(chan result)
output := []models.API{}
if err != nil {
return output, err
}
go fileReader(workerQueue, APImodelsChan)
for _, file := range files {
path := filepath.Join(directory, file.Name())
workerQueue <- path
}
close(workerQueue)
for i:= 0; i< len(files); i++ {
result := <- APImodelsChan
if result.err != nil {
return output, result.err
} else {
output = append(output, result.api)
}
}
return output, nil
}
type result struct {
api models.API
err error
}
func fileReader(theFilePaths <- chan string, apis chan<- result) {
for path := range theFilePaths {
fmt.Println(path)
api, err := File(path)
go func () {
apis <- result{api, err}
}()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment