-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgophermap.go
More file actions
101 lines (89 loc) · 1.75 KB
/
Copy pathgophermap.go
File metadata and controls
101 lines (89 loc) · 1.75 KB
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
package gogofer
import (
"bufio"
"bytes"
"io"
"strconv"
)
type GopherType byte
type GopherMapEntry struct {
Type GopherType
Display []byte
Path []byte
Host []byte
Port []byte
}
type GopherMap struct {
Entries []*GopherMapEntry
DefaultHost []byte
DefaultPort []byte
}
func NewGopherMap(reader io.Reader, host string, port int) *GopherMap {
gm := &GopherMap{
Entries: []*GopherMapEntry{},
DefaultHost: []byte(host),
DefaultPort: []byte(strconv.Itoa(port)),
}
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
tokens := bytes.Split(scanner.Bytes(), []byte{tab})
if len(tokens) == 0 || len(tokens[0]) < 2 {
continue
}
entry := &GopherMapEntry{}
loop:
for i, token := range tokens {
switch i {
// First byte is type, rest of first token is display
case 0:
entry.Type = GopherType(token[0])
entry.Display = token[1:]
// Second token is path
case 1:
entry.Path = token
// Third token is server
case 2:
entry.Host = token
// Fourth token is port
case 3:
entry.Port = token
default:
break loop
}
}
gm.Entries = append(gm.Entries, entry)
}
return gm
}
func (gm *GopherMap) Data() []byte {
buf := &bytes.Buffer{}
for _, g := range gm.Entries {
buf.WriteByte(byte(g.Type))
buf.Write(g.Display)
buf.WriteByte(tab)
switch g.Type {
default:
buf.Write(g.Path)
buf.WriteByte(tab)
if g.Host == nil {
buf.Write(gm.DefaultHost)
} else {
buf.Write(g.Host)
}
buf.WriteByte(tab)
if g.Port == nil {
buf.Write(gm.DefaultPort)
} else {
buf.Write(g.Port)
}
case 'i':
buf.Write(fake)
buf.WriteByte(tab)
buf.Write(fake)
buf.WriteByte(tab)
buf.WriteByte(fakePort)
}
buf.Write(crlf)
}
return buf.Bytes()
}