3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-12-22 18:52:41 +01:00
ergo/irc/net.go

82 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() {
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() {
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-10 06:04:37 +01:00
names, err := net.LookupAddr(ipaddr)
if err != nil {
return ipaddr
}
2014-02-10 06:10:36 +01:00
return names[0][0 : len(names[0])-1]
}