3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-11-10 22:19:31 +01:00
ergo/src/irc/net.go

53 lines
926 B
Go
Raw Normal View History

2012-04-07 20:44:59 +02:00
package irc
import (
"bufio"
"log"
2012-04-08 08:32:08 +02:00
"strings"
2012-04-07 20:44:59 +02:00
"net"
)
func readTrimmedLine(reader *bufio.Reader) (string, error) {
line, err := reader.ReadString('\n')
return strings.TrimSpace(line), err
}
2012-04-07 20:44:59 +02:00
// Adapt `net.Conn` to a `chan string`.
func StringReadChan(conn net.Conn) <-chan string {
2012-04-07 20:44:59 +02:00
ch := make(chan string)
2012-04-08 08:32:08 +02:00
reader := bufio.NewReader(conn)
2012-04-18 05:24:26 +02:00
addr := conn.RemoteAddr()
2012-04-07 20:44:59 +02:00
go func() {
for {
line, err := readTrimmedLine(reader)
2012-04-08 08:32:08 +02:00
if (line != "") {
ch <- line
2012-04-18 05:24:26 +02:00
log.Printf("%s -> %s", addr, line)
2012-04-08 08:32:08 +02:00
}
2012-04-07 20:44:59 +02:00
if err != nil {
break
}
}
2012-04-08 08:32:08 +02:00
close(ch)
2012-04-07 20:44:59 +02:00
}()
2012-04-08 08:32:08 +02:00
return ch
}
2012-04-07 20:44:59 +02:00
func StringWriteChan(conn net.Conn) chan<- string {
2012-04-08 08:32:08 +02:00
ch := make(chan string)
writer := bufio.NewWriter(conn)
2012-04-18 05:24:26 +02:00
addr := conn.RemoteAddr()
2012-04-07 20:44:59 +02:00
go func() {
for str := range ch {
2012-04-08 08:32:08 +02:00
if _, err := writer.WriteString(str + "\r\n"); err != nil {
2012-04-07 20:44:59 +02:00
break
}
2012-04-08 08:32:08 +02:00
writer.Flush()
2012-04-18 05:24:26 +02:00
log.Printf("%s <- %s", addr, str)
2012-04-07 20:44:59 +02:00
}
2012-04-08 08:32:08 +02:00
close(ch)
2012-04-07 20:44:59 +02:00
}()
return ch
}