Skip to content

Instantly share code, notes, and snippets.

@pomkine
Created April 1, 2020 07:01
Show Gist options
  • Save pomkine/bc1bf8257382f2b7ab68642689fda00c to your computer and use it in GitHub Desktop.
Save pomkine/bc1bf8257382f2b7ab68642689fda00c to your computer and use it in GitHub Desktop.
Using Go first class functions with channels
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