-
Notifications
You must be signed in to change notification settings - Fork 0
/
GoSquared.go
122 lines (95 loc) · 1.98 KB
/
GoSquared.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
package main
import (
"sync"
"net"
"bufio"
"log"
"fmt"
"io/ioutil"
"os"
)
var (
hostname = "localhost"
port = "7070"
defaultDir = "."
)
var wg sync.WaitGroup
var CRLF = []byte("\n")
func printFile(workingDirectory string, writer *bufio.Writer, path string) {
bytes, err := ioutil.ReadFile(workingDirectory+path)
if err != nil{
log.Fatal(err)
return
}
writer.Write(bytes)
}
func listDirectory(writer *bufio.Writer, dir *directory) {
dir.iterate(func(name string, locType string) {
resource := dir.path+"/"+name
if dir.path == "/" {
resource = dir.path[1:] + "/" + name
}
directoryString := fmt.Sprintf("%s%s\t%s\t%s\t%s\r\n", locType, name, resource, hostname, port)
writer.Write([]byte(directoryString))
})
}
func handleConnection(conn net.Conn) {
reader := bufio.NewReader(conn)
writer := bufio.NewWriter(conn)
defer conn.Close()
defer wg.Done()
t, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
providedPath := t[:len(t)-2]
providedDirectory := GetDirectoryAtPath(defaultDir, providedPath)
if providedDirectory == nil {
printFile(defaultDir, writer, providedPath)
} else {
index, err := providedDirectory.getIndex(defaultDir)
if err == nil {
if index[len(index)-1] != '\n' {
index = append(index, CRLF...)
}
writer.Write(index)
}
listDirectory(writer, providedDirectory)
}
writer.Flush()
}
func main() {
argsError := "Your arguments should look something like: <working dir> <hostname> <port>"
if len(os.Args) != 4 {
log.Fatal(argsError)
}
if os.Args[1] != "" {
hostname = os.Args[1]
} else {
log.Fatal(argsError)
}
if os.Args[2] != "" {
hostname = os.Args[2]
} else {
log.Fatal(argsError)
}
if os.Args[3] != "" {
port = os.Args[3]
} else {
log.Fatal(argsError)
}
ln, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Fatal(err)
}
for {
conn, err := ln.Accept()
if err != nil {
log.Fatal(err)
break
}
wg.Add(1)
go handleConnection(conn)
}
wg.Wait()
}