-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
66 lines (50 loc) · 1.37 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
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"github.com/theodelaune/autocsv/autocsv"
)
var file, separator, searchField, neededFields string
var feed *autocsv.Feed
func init() {
flag.Usage = func() {
fmt.Printf("Usage %s [options]\n", os.Args[0])
flag.PrintDefaults()
}
flag.StringVar(&file, "file", "", "File datasource")
flag.StringVar(&separator, "separator", ";", "csv field separator")
flag.StringVar(&searchField, "search-field", "", "Searchable field")
flag.StringVar(&neededFields, "needed-fields", "", "Expected fields")
flag.Parse()
if file == "" || searchField == "" || neededFields == "" {
fmt.Println("options required !")
flag.PrintDefaults()
os.Exit(2)
}
}
func main() {
feed = autocsv.New(file, separator, searchField, neededFields)
feed.Parse()
http.HandleFunc("/autocomplete", requestHandler)
fmt.Println("Server started on port 8080...")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func requestHandler(w http.ResponseWriter, r *http.Request) {
keyword := r.FormValue("q")
if keyword == "" {
http.Error(w, "Not found", http.StatusUnprocessableEntity)
return
}
results := feed.Search(keyword)
json, err := json.Marshal(results)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
fmt.Fprint(w, string(json))
}