Skip to content

Instantly share code, notes, and snippets.

@dlresende
Created December 18, 2020 11:52
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 dlresende/bd16731526db6785f8aa9e91ef761def to your computer and use it in GitHub Desktop.
Save dlresende/bd16731526db6785f8aa9e91ef761def to your computer and use it in GitHub Desktop.
goroutine example with logging
package main
import (
"fmt"
"io"
"os"
"os/signal"
"sync"
)
type Logger struct {
write chan string
wg sync.WaitGroup
}
func New(w io.Writer, s int) *Logger {
l := Logger {
write: make(chan string, s),
}
l.wg.Add(1)
go func() {
for d := range l.write {
fmt.Fprintln(w, d)
}
l.wg.Done()
}()
return &l
}
func (l *Logger) Write(d string) {
select {
case l.write<-d:
default:
fmt.Println("dropping logs")
}
}
func (l *Logger) Shutdown() {
close(l.write)
l.wg.Wait()
}
func main() {
l := New(os.Stdout, 10)
for i := 0; i < 10; i++ {
go func(i int) {
l.Write(fmt.Sprintf("logging %d", i+1))
}(i)
}
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
loop:
for {
select {
case <-sc:
fmt.Println("CTRL-C received. Shutting down...")
l.Shutdown()
break loop
}
}
}
func checkError(err error) {
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment