-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqotd-server.go
55 lines (44 loc) · 986 Bytes
/
qotd-server.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
package main
import "bufio"
import "fmt"
import "net"
import "os"
import "math/rand"
func checkError(e error) {
if e != nil {
panic(e)
}
}
func loadQuotes() []string {
f, err := os.Open("quotes")
checkError(err)
defer f.Close()
var quotes []string
quotes = make([]string, 0, 5)
s := bufio.NewScanner(bufio.NewReader(f))
for s.Scan() {
quotes = append(quotes, s.Text())
}
return quotes
}
func handleConnection(c net.Conn, quotes []string) {
// select a random quote; a quote of the moment, instead of the day
q := quotes[rand.Intn(len(quotes))]
// write the quote to the connection
c.Write([]byte(q))
c.Close()
}
func main() {
l, err := net.Listen("tcp", ":17")
checkError(err)
defer l.Close()
fmt.Println("port connected")
quotes := loadQuotes()
fmt.Println("quotes loaded; count =", len(quotes))
fmt.Println("server started")
for {
c, err := l.Accept()
checkError(err)
go handleConnection(c, quotes)
}
}