Skip to content

Instantly share code, notes, and snippets.

@muety
Created May 16, 2017 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muety/08ea6b8f5940d96cb3b47dd5afb27e7f to your computer and use it in GitHub Desktop.
Save muety/08ea6b8f5940d96cb3b47dd5afb27e7f to your computer and use it in GitHub Desktop.
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