go: Add writers to io.writer using multiWriter -


i'm new go. have map indicates writers active:

var writers map[int]bool 

i want iterate on map, , create writer represents active writers using multiwriter()

i using following code snippet:

func setupmultiloggers() { var mw io.writer k, v := range writers {     if v != true {         continue     }     switch k {     case 0:         if mw == nil {             mw = writer0         } else {             mw = io.multiwriter(mw, writer0)         }     case 1:         if mw == nil {             mw = os.stdout         } else {             mw = io.multiwriter(mw, os.stdout)         }     case 2:         if mw == nil {             mw = writer2         } else {             io.multiwriter(mw, writer2)         }     default:     } } log.setoutput(mw) 

}

when initializing 3 values of map true , testing writer2, works , doesn't (code in case 2 executes)

if use

log.setoutput(io.multiwriter(writer0, os.stdout, writer2)) 

it works expected.

i cannot seem understand why original code doesn't reliably work. have feeling there more clean way "concatenate" writers

edit: i've found (stupid) bug. assignment mw missing in third case. still looking more clean way "concatenate" writers.

you don't seem have map of writers, have map of ints bools. presumably, ints represent file descriptor.

the easiest way change map[int]bool map[io.writer]bool, can iterate through them , add them slice append.

ws := make([]io.writer, 0) k, v : = range(writers) {     if v != true {         continue     }     ws = append(ws, k) } 

after that, can create multiwriter directly giving slice multiwriter call.

w := io.multiwriter(ws...) log.setoutput(w) 

(the ... in function parameter after slice means expand slice arguments function call)

you can same thing while keeping map[int]bool, you'll need switch similar have convert int io.writer


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -