Created
March 4, 2019 20:37
-
-
Save Voles/3c7e0859ef6434c5bbbafc32bfc8f742 to your computer and use it in GitHub Desktop.
Go channel experiment
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
// 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