-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathirc.go
139 lines (105 loc) · 2.08 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
//Package irc provides an IRC client
package irc
import (
"bufio"
"fmt"
"io"
"log"
"net"
"os"
"strings"
"sync"
)
type Client struct {
sync.WaitGroup
Server string
Port int32
Nick string
User string
Fullname string
conn *net.Conn
Inbound chan Message
Outbound chan Message
}
type Message struct {
Source string
Command string
Args []string
}
func (c *Client) Join(channel string) *Channel {
return NewChannel(c)
}
func (c *Client) Quit() {
c.send("QUIT :Leaving")
}
func (c *Client) send(cmd string, args ...string) {
w := bufio.NewWriter(*c.conn)
w.WriteString(":" + c.User + " " + cmd + " " + strings.Join(args, " ") + "\n")
w.Flush()
}
func ParseMessage(s string) *Message {
parts := strings.SplitN(s, " ", 3)
sp := strings.SplitN(parts[2], ":", 2)
params := strings.Split(strings.Trim(sp[0], " "), " ")
fmt.Println(len(params))
trailing := sp[1]
m := &Message{
Source: parts[0][1:],
Command: parts[1],
Args: append(params, trailing),
}
return m
}
func (c *Client) handleIncoming() {
r := bufio.NewReader(*c.conn)
for {
rawline, _, err := r.ReadLine()
line := string(rawline)
if err != nil {
if err == io.EOF {
fmt.Println(line)
log.Fatal("connection closed")
}
break
}
fmt.Println(line)
}
c.Done()
}
func (c *Client) Connect() error {
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", c.Server, c.Port))
if err != nil {
return err
}
defer conn.Close()
c.conn = &conn
c.Add(1)
go c.handleIncoming()
c.send("USER", c.User, "0", "*", c.User)
c.send("NICK", c.Nick)
r := bufio.NewReader(os.Stdin)
var cmd string
var args []string
for {
fmt.Print("> ")
rawline, _, _ := r.ReadLine()
args = strings.Split(string(rawline), " ")
cmd = args[0]
args = args[1:]
c.send(strings.ToUpper(cmd), args...)
fmt.Println(cmd, args)
}
c.Wait()
return nil
}
func NewClient(server, nick, user string, initialChannels ...string) *Client {
c := &Client{
Server: server,
Nick: nick,
User: user,
}
// for i, channel := range initialChannels {
// c.Join(channel)
// }
return c
}