Created
May 16, 2017 19:07
-
-
Save muety/08ea6b8f5940d96cb3b47dd5afb27e7f to your computer and use it in GitHub Desktop.
Example for channels, inspired by vansimke's YouTube tutorial
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
// https://play.golang.org/p/Y8eaSkYNgG | |
package main | |
import ( | |
"fmt" | |
) | |
const ( | |
logDebug = "DEBUG" | |
logInfo = "INFO" | |
logError = "ERROR" | |
) | |
type logEntry struct { | |
LogLevel string | |
Text string | |
} | |
func main() { | |
logCh := make(chan logEntry) | |
doneCh := make(chan struct{}) | |
go logger(logCh, doneCh) | |
defer func() { | |
doneCh <- struct{}{} | |
close(logCh) | |
close(doneCh) | |
}() | |
logCh <- logEntry{LogLevel: logInfo, Text: "Application starting up."} | |
logCh <- logEntry{LogLevel: logInfo, Text: "Application shutting down."} | |
} | |
func logger(ch <-chan logEntry, doneCh <-chan struct{}) { | |
for { | |
select { | |
case entry := <- ch: | |
fmt.Printf("[%v] %v\n", entry.LogLevel, entry.Text) | |
case <-doneCh: | |
break | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment