3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-12-01 16:39:26 +01:00
ergo/irc/net.go

84 lines
1.6 KiB
Go
Raw Normal View History

2012-04-07 20:44:59 +02:00
package irc
import (
"bufio"
"io"
"log"
2012-04-07 20:44:59 +02:00
"net"
"strings"
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 close(ch)
2012-04-07 20:44:59 +02:00
for {
line, err := reader.ReadString('\n')
2012-04-07 20:44:59 +02:00
if err != nil {
if err != io.EOF {
log.Printf("%s → %s error: %s", conn.RemoteAddr(), conn.LocalAddr(), err)
}
2012-04-07 20:44:59 +02:00
break
}
if DEBUG_NET {
2014-02-09 02:43:59 +01:00
log.Printf("%s → %s %s", conn.RemoteAddr(), conn.LocalAddr(), line)
}
ch <- strings.TrimSpace(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 maybeLogWriteError(conn net.Conn, err error) bool {
if err != nil {
if err != io.EOF {
log.Printf("%s ← %s error: %s", conn.RemoteAddr(), conn.LocalAddr(), err)
}
return true
}
return false
}
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 close(ch)
2012-04-07 20:44:59 +02:00
for str := range ch {
if DEBUG_NET {
2014-02-09 02:43:59 +01:00
log.Printf("%s ← %s %s", conn.RemoteAddr(), conn.LocalAddr(), str)
}
if _, err := writer.WriteString(str); maybeLogWriteError(conn, err) {
break
}
if _, err := writer.WriteString(CRLF); maybeLogWriteError(conn, err) {
break
}
if err := writer.Flush(); maybeLogWriteError(conn, err) {
2012-04-07 20:44:59 +02:00
break
}
}
}()
return ch
}
func LookupHostname(addr net.Addr) string {
addrStr := addr.String()
ipaddr, _, err := net.SplitHostPort(addrStr)
if err != nil {
return addrStr
}
2014-02-10 00:14:53 +01:00
switch ipaddr {
case "127.0.0.1", "::1":
return "localhost"
}
2014-02-05 04:28:24 +01:00
names, err := net.LookupHost(ipaddr)
if err != nil {
return ipaddr
}
return names[0]
}