Created
April 1, 2020 07:01
-
-
Save pomkine/bc1bf8257382f2b7ab68642689fda00c to your computer and use it in GitHub Desktop.
Using Go first class functions with channels
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
import ( | |
"io" | |
"net" | |
) | |
type Mux struct { | |
ops chan func(map[net.Addr]net.Conn) | |
} | |
func (m *Mux) Add(conn net.Conn) { | |
m.ops <- func(m map[net.Addr]net.Conn) { | |
m[conn.RemoteAddr()] = conn | |
} | |
} | |
func (m *Mux) Remove(addr net.Addr) { | |
m.ops <- func(m map[net.Addr]net.Conn) { | |
delete(m, addr) | |
} | |
} | |
func (m *Mux) SendMessage(msg string) error { | |
result := make(chan error, 1) | |
m.ops <- func(m map[net.Addr]net.Conn) { | |
for _, conn := range m { | |
_, err := io.WriteString(conn, msg) | |
if err != nil { | |
result <- err | |
return | |
} | |
} | |
result <- nil | |
} | |
return <-result | |
} | |
func (m *Mux) loop() { | |
var conns map[net.Addr]net.Conn | |
for op := range m.ops { | |
op(conns) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment