/
main.go
121 lines (94 loc) · 2.22 KB
/
main.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 (
"bufio"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"sync"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
var wg sync.WaitGroup
func findInFile(filename string, cChannel chan string, data string) {
defer wg.Done()
f, err := os.Open(filename)
if err != nil {
fmt.Println("cannot able to read the file", err)
return
}
defer f.Close()
scanner := bufio.NewScanner(f)
re := regexp.MustCompile("(?i)" + data)
for i := 1; scanner.Scan(); i++ {
if re.MatchString(scanner.Text()) {
cChannel <- scanner.Text()
//fmt.Println(scanner.Text())
}
}
}
func listFiles() []string {
var filesArray = []string{}
files, err := ioutil.ReadDir("./dbs/")
if err != nil {
log.Fatal(err)
}
for _, file := range files {
filesArray = append(filesArray, file.Name())
}
// In this folder we have .gitkeep, which will always be first in the list
filesArray = filesArray[1:]
fmt.Println(filesArray)
return filesArray
}
func grep(data string, msgType int, conn *websocket.Conn) {
var dbNames = listFiles()
for i := 0; i < len(dbNames); i++ {
dbNames[i] = "./dbs/" + dbNames[i]
}
cChannel := make(chan string)
for _, dbName := range dbNames {
wg.Add(1)
go findInFile(dbName, cChannel, data)
}
go func() {
wg.Wait()
close(cChannel)
}()
for match := range cChannel {
conn.WriteMessage(msgType, []byte(match))
}
}
func handleEcho(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
for {
msgType, msg, err := conn.ReadMessage()
if err != nil {
return
}
fmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg))
conn.WriteMessage(msgType, []byte("Search started!"))
grep(string(msg), msgType, conn)
conn.WriteMessage(msgType, []byte("Search ended"))
fmt.Println("----------------------------------------------------------------")
}
}
func handleRoot(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./templates/submit.html")
}
func main() {
http.HandleFunc("/", handleRoot)
http.HandleFunc("/echo", handleEcho)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}