-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
193 lines (160 loc) · 4.35 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package main
import (
/* Standard library packages */
/* Third party */
// imports as "cli", pinned to v1; cliv2 is going to be drastically
// different and pinning to v1 avoids issues with unstable API changes
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
cli "gopkg.in/urfave/cli.v1"
/* Local packages */
"github.com/gorilla/mux"
"github.com/keeferrourke/imgrep/files"
"github.com/keeferrourke/imgrep/storage"
)
var (
PORT string
TPLDIR string
ASSETS string
)
type ResultRow struct {
Filename string `json:"filename"`
Bytes []byte `json:"bytes"`
}
// reliably serve files even when binary is installed and run from arbitrary
// working directory
// this is horrible though so try to find a better way to this? :(
func setPath(dir string) string {
basePath := "src" + string(os.PathSeparator) + "github.com" + string(os.PathSeparator) + "keeferrourke" + string(os.PathSeparator) + "imgrep-web"
p := os.Getenv("GOPATH") + string(os.PathSeparator) + basePath + string(os.PathSeparator) + dir
if _, err := os.Stat(p); os.IsNotExist(err) {
p = os.Getenv("GOROOT") + string(os.PathSeparator) + dir
if _, err := os.Stat(p); os.IsNotExist(err) {
log.Fatal("path error: can not stat directory " + p)
}
}
return p
}
func StartServer(c *cli.Context) error {
r := mux.NewRouter()
go files.InitFromPath(false)
r.HandleFunc("/imgrep/search", func(w http.ResponseWriter, r *http.Request) {
keyword := r.FormValue("keyword")
keyword = strings.TrimSpace(keyword)
keywordList := strings.Split(keyword, " ")
results := []*ResultRow{}
for _, kw := range keywordList {
filenames, err := storage.Get(kw, true) // case insensitive search
if err != nil {
log.Printf(err.Error())
}
for _, file := range filenames {
found := false
for _, rr := range results {
if rr.Filename == file {
found = true
}
}
if found {
continue
}
// remove non-existing files from database
if _, err := os.Stat(file); os.IsNotExist(err) {
storage.Delete(file)
continue
}
f, err := ioutil.ReadFile(file)
if err != nil {
log.Printf(err.Error())
}
results = append(results, &ResultRow{
Filename: file,
Bytes: f,
})
}
}
resp := map[string][]*ResultRow{}
resp["files"] = results
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
index := TPLDIR + string(os.PathSeparator) + "index.html"
templates, err := template.ParseFiles(index)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
if err := templates.ExecuteTemplate(w, "index.html", nil); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
s := http.StripPrefix("/assets/", http.FileServer(http.Dir(ASSETS)))
r.PathPrefix("/assets").Handler(s)
fmt.Println("Started server on localhost:" + PORT)
http.ListenAndServe(":"+PORT, r)
return nil
}
var Server = cli.Command{
Name: "run",
Aliases: []string{"start"},
Usage: "initialize gui server",
Action: StartServer,
Flags: []cli.Flag{
cli.StringFlag{
Name: "port, p",
Value: "1337",
Usage: "configure port",
Destination: &PORT,
},
},
}
func init() {
TPLDIR = setPath("tpl")
ASSETS = setPath("assets")
}
func main() {
// customize cli
cli.VersionPrinter = func(c *cli.Context) {
fmt.Fprintf(c.App.Writer, "%s %s - %s\n",
c.App.Name, c.App.Version, c.App.Description)
}
// set up the application
app := cli.NewApp()
app.Authors = []cli.Author{
cli.Author{
Name: "Keefer Rourke",
Email: "[email protected]",
},
cli.Author{
Name: "Ivan Zhang",
Email: "[email protected]",
},
}
app.Copyright = "(c) 2017 under the MIT License"
app.EnableBashCompletion = true
app.Name = "imgrep-web"
app.Description = "web interface for using imgrep"
app.Usage = "grep image files for words"
app.Version = "v0"
app.Commands = []cli.Command{
Server,
}
app.CommandNotFound = func(c *cli.Context, command string) {
fmt.Fprintf(c.App.Writer, "Did you read the manual?\n")
}
// connect to local sqlite
storage.InitDB(files.DBFILE)
app.Run(os.Args)
return
}