/
irc.go
72 lines (60 loc) · 1.23 KB
/
irc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"log"
"bufio"
"os"
"net"
"fmt"
)
type IRCWriter chan string
type IRCReader chan string
type IRC struct {
Reader IRCReader
Writer IRCWriter
}
func (w IRCWriter) Send(line string) {
w <- line
}
func (w IRCWriter) Printf(format string, a ...interface{}) {
w <- fmt.Sprintf(format, a)
}
func (r IRCReader) ReadLine() string {
return <- r
}
func newIRC(c net.Conn) (irc *IRC) {
irc = &IRC{ Reader: make(chan string, 10), Writer: make(chan string, 10) }
// start reader
go func(r *bufio.Reader) {
for {
line, err := r.ReadString('\n')
if err != nil {
log.Exit("Unable to read from channel", err)
}
log.Stdoutf("Read: %#v", line)
irc.Reader <- line
}
}(bufio.NewReader(c))
// start writer
go func(w *bufio.Writer) {
for {
line := <- irc.Writer
_, err := w.WriteString(line)
if err != nil {
log.Exit("Unable to write to channel", err)
}
err = w.Flush()
if err != nil {
log.Exit("Unable to write to channel", err)
}
log.Stdoutf("Wrote: %#v", line)
}
}(bufio.NewWriter(c))
return irc
}
func connectTLS(host string, port int) (irc *IRC,err os.Error) {
conn, err := dialIRCTLS(host, port)
if err != nil {
return nil, err
}
return newIRC(conn), nil
}