-
Notifications
You must be signed in to change notification settings - Fork 2
/
nntp.go
60 lines (54 loc) · 1.17 KB
/
nntp.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
package main
import (
"fmt"
"strconv"
"sync"
"github.com/Tensai75/nntp"
)
type safeConn struct {
mutex sync.Mutex
closed bool
*nntp.Conn
}
var (
initConnGuard sync.Once
connectionGuard chan struct{}
)
func ConnectNNTP() (*safeConn, error) {
initConnGuard.Do(func() {
connectionGuard = make(chan struct{}, conf.Connections)
})
connectionGuard <- struct{}{} // will block if guard channel is already filled
var conn *nntp.Conn
var err error
if conf.SSL {
conn, err = nntp.DialTLS("tcp", conf.Host+":"+strconv.Itoa(conf.Port), nil)
} else {
conn, err = nntp.Dial("tcp", conf.Host+":"+strconv.Itoa(conf.Port))
}
safeConn := safeConn{
Conn: conn,
}
if err != nil {
safeConn.Close()
return nil, fmt.Errorf("Connection to usenet server failed: %v\r\n", err)
}
if err = safeConn.Authenticate(conf.NntpUser, conf.NntpPass); err != nil {
safeConn.Close()
return nil, fmt.Errorf("Authentication with usenet server failed: %v\r\n", err)
}
return &safeConn, nil
}
func (c *safeConn) Close() {
c.mutex.Lock()
defer c.mutex.Unlock()
if !c.closed {
if c.Conn != nil {
c.Quit()
}
if len(connectionGuard) > 0 {
<-connectionGuard
}
c.closed = true
}
}