3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-11-13 07:29:30 +01:00
ergo/irc/net.go

72 lines
1.3 KiB
Go
Raw Normal View History

2012-04-07 20:44:59 +02:00
package irc
import (
"bufio"
"log"
2012-04-07 20:44:59 +02:00
"net"
"strings"
2012-04-07 20:44:59 +02:00
)
func readTrimmedLine(reader *bufio.Reader) (string, error) {
line, err := reader.ReadString('\n')
if err != nil {
return "", err
}
return strings.TrimSpace(line), nil
}
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-07 20:44:59 +02:00
go func() {
defer conn.Close()
defer close(ch)
2012-04-07 20:44:59 +02:00
for {
line, err := readTrimmedLine(reader)
2012-04-07 20:44:59 +02:00
if err != nil {
log.Print("net: ", err)
2012-04-07 20:44:59 +02:00
break
}
if DEBUG_NET {
2013-05-26 22:28:22 +02:00
log.Printf("%s → %s : %s", conn.RemoteAddr(), conn.LocalAddr(), line)
}
ch <- line
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-07 20:44:59 +02:00
go func() {
defer conn.Close()
defer close(ch)
2012-04-07 20:44:59 +02:00
for str := range ch {
if DEBUG_NET {
2013-05-26 22:28:22 +02:00
log.Printf("%s ← %s : %s", conn.RemoteAddr(), conn.LocalAddr(), str)
}
if _, err := writer.WriteString(str + "\r\n"); err != nil {
log.Print("net: ", err)
2012-04-07 20:44:59 +02:00
break
}
2012-04-08 08:32:08 +02:00
writer.Flush()
2012-04-07 20:44:59 +02:00
}
}()
return ch
}
func LookupHostname(addr net.Addr) string {
addrStr := addr.String()
ipaddr, _, err := net.SplitHostPort(addrStr)
if err != nil {
return addrStr
}
2014-02-05 04:28:24 +01:00
names, err := net.LookupHost(ipaddr)
if err != nil {
return ipaddr
}
return names[0]
}