Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example for channels, inspired by vansimke's YouTube tutorial
// 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
You can’t perform that action at this time.