summaryrefslogtreecommitdiff
path: root/main.go
blob: a41f774d3704844e7c2a89235a6d01cc3ed590ac (plain)
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
194
195
196
197
198
199
200
201
202
203
204
205
206
package main

import (
	"fmt"
	"html/template"
	"math"
	"net/http"
	"os"
	"strconv"

	"github.com/joho/godotenv"
	"github.com/meilisearch/meilisearch-go"
)

type SearchQuery struct {
	Query      string
	MaxResults int64
	Offset     int64
}

type SearchResponse struct {
	Success       bool
	SearchResults []interface{}
	NumResults    int
	TotalResults  int64
	MoreResults   bool
	OriginalQuery SearchQuery
	Offset        int64
	LastOffset    int64
	NumPages      int
}

func pageCount(total int, perPage int) int {
	return int(math.Ceil(float64(total) / float64(perPage)))
}

func main() {
	err := godotenv.Load(".env")
	if err != nil {
		fmt.Println("Error loading .env file")
		os.Exit(1)
	}
	meili_host, ok := os.LookupEnv("MEILI_HOST")
	if !ok {
		fmt.Println("Error loading MEILI_HOST from .env file")
		os.Exit(1)
	}

	client := meilisearch.NewClient(meilisearch.ClientConfig{
		Host: meili_host,
	})

	index := client.Index("fda510k")

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		t, _ := template.ParseFiles("search.gtpl")
		t.Execute(w, nil)
	})

	http.HandleFunc("/2.0/", func(w http.ResponseWriter, r *http.Request) {
		t, _ := template.ParseFiles("templates/home.html")
		t.Execute(w, nil)
	})

	funcMap := template.FuncMap{
		"unescapeHTML": func(s string) template.HTML {
			return template.HTML(s)
		},
	}

	//searchResTemplate := template.Must(template.ParseFiles("results.gtpl"))
	searchResTemplate := template.Must(template.New("results.gtpl").Funcs(funcMap).ParseFiles("results.gtpl"))

	// v2.0 UI
	searchResultsTemplate2 := template.Must(template.New("search_results.html").Funcs(funcMap).ParseFiles("templates/search_results.html"))

	if err != nil {
		fmt.Println("Error parsing template")
		os.Exit(1)
	}

	http.HandleFunc("/2.0/search", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		fmt.Println(r.Form)
		if r.Form["query"] != nil || r.FormValue("query") != "" {
			fmt.Println("query:", r.Form["query"])
			var myOffset int64
			if r.Form["offset"] != nil {
				offset, _ := strconv.ParseInt(r.FormValue("offset"), 10, 64)
				myOffset = offset
				if offset < 0 {
					myOffset = 0
				}
			} else {
				offset := int64(0)
				myOffset = offset
			}
			query := SearchQuery{
				Query:      r.FormValue("query"),
				MaxResults: 100,
				Offset:     myOffset,
			}

			res, err := index.Search(query.Query, &meilisearch.SearchRequest{
				Limit:  query.MaxResults,
				Offset: query.Offset,
				AttributesToRetrieve: []string{
					"title",
					"applicant",
					"submission_date",
					"predicates",
					"id",
				},
				AttributesToCrop:      []string{"full_text"},
				AttributesToHighlight: []string{"full_text"},
				HighlightPreTag:       "<mark>",
				HighlightPostTag:      "</mark>",
			})

			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			numPages := pageCount(int(res.EstimatedTotalHits), int(query.MaxResults))

			searchResultsTemplate2.Execute(w, SearchResponse{
				Success:       true,
				SearchResults: res.Hits,
				NumResults:    len(res.Hits) + int(query.Offset),
				TotalResults:  res.EstimatedTotalHits,
				MoreResults:   res.EstimatedTotalHits > query.MaxResults,
				OriginalQuery: query,
				Offset:        query.Offset + query.MaxResults,
				LastOffset:    query.Offset - query.MaxResults,
				NumPages:      numPages,
			})
		} else {
			fmt.Println("query is empty")
		}
	})

	http.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		fmt.Println(r.Form)
		if r.Form["query"] != nil || r.FormValue("query") != "" {
			fmt.Println("query:", r.Form["query"])
			var myOffset int64
			if r.Form["offset"] != nil {
				offset, _ := strconv.ParseInt(r.FormValue("offset"), 10, 64)
				myOffset = offset
				if offset < 0 {
					myOffset = 0
				}
			} else {
				offset := int64(0)
				myOffset = offset
			}
			query := SearchQuery{
				Query:      r.FormValue("query"),
				MaxResults: 100,
				Offset:     myOffset,
			}

			res, err := index.Search(query.Query, &meilisearch.SearchRequest{
				Limit:  query.MaxResults,
				Offset: query.Offset,
				AttributesToRetrieve: []string{
					"title",
					"applicant",
					"submission_date",
					"predicates",
					"id",
				},
				AttributesToCrop:      []string{"full_text"},
				AttributesToHighlight: []string{"full_text"},
				HighlightPreTag:       "<mark>",
				HighlightPostTag:      "</mark>",
			})

			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			numPages := pageCount(int(res.EstimatedTotalHits), int(query.MaxResults))

			searchResTemplate.Execute(w, SearchResponse{
				Success:       true,
				SearchResults: res.Hits,
				NumResults:    len(res.Hits) + int(query.Offset),
				TotalResults:  res.EstimatedTotalHits,
				MoreResults:   res.EstimatedTotalHits > query.MaxResults,
				OriginalQuery: query,
				Offset:        query.Offset + query.MaxResults,
				LastOffset:    query.Offset - query.MaxResults,
				NumPages:      numPages,
			})
		} else {
			fmt.Println("query is empty")
		}
	})

	fmt.Println("Listening on port 8080")
	http.ListenAndServe(":8080", nil)
}