-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
253 lines (218 loc) · 5.82 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// package main connects to the archaia database and serves a search page
// over HTTP allowing a user search for places by country name
package main
import (
"database/sql"
"html/template"
"io"
"log"
"math"
"net/http"
"os"
"strconv"
"github.com/labstack/echo/v4"
_ "github.com/lib/pq"
"golang.org/x/text/message"
)
var db *sql.DB
const pageSize = 200
type countryListing struct {
Name string
PlaceCount int
}
type pageData struct {
PageTitle string
Data interface{}
}
type resultsPage struct {
SearchString string `json:"searchString"`
Count int `json:"count"`
PageNo int `json:"pageNo"`
NextPage int `json:"nextPage"`
DispThisPage int `json:"dispThisPage"`
DispTotalPages int `json:"dispTotalpages"`
FmtCount string `json:"fmtCount"`
MoreResults bool `json:"hasMoreResults"`
Results []pleiadesPlace `json:"results"`
}
type pleiadesPlace struct {
Name string `json:"name"`
Country string `json:"country"`
PlaceType string `json:"placeType"`
Description string `json:"description"`
URI string `json:"pleiadesURL"`
}
type Template struct {
templates *template.Template
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
func main() {
// For dsn string format and supported params, see:
// https://pkg.go.dev/github.com/lib/pq#hdr-Connection_String_Parameters
// Normal connection strings are also supported by pq.
dsn := os.Getenv("DATABASE_URL")
if dsn == "" {
log.Fatal("Empty DSN")
}
port := os.Getenv("PORT")
if port == "" {
port = "80"
}
db, err := sql.Open("postgres", dsn)
if err != nil {
log.Fatal(err)
}
db.SetConnMaxLifetime(0)
db.SetMaxIdleConns(50)
db.SetMaxOpenConns(50)
t := &Template{
templates: template.Must(template.ParseGlob("public/views/*.html")),
}
e := echo.New()
// e.Debug = true
e.Renderer = t
e.HTTPErrorHandler = customHTTPErrorHandler
e.Static("/static", "public/assets")
e.File("/about.html", "public/about.html")
e.File("/guide.html", "public/guide.html")
homeHandler := func(c echo.Context) error {
return buildHomepage(c, db)
}
e.GET("/", homeHandler)
searchHandler := func(c echo.Context) error {
return searchResults(c, db)
}
e.GET("/search", searchHandler)
e.Logger.Fatal(e.Start(":"+port))
}
// serve error pages - source: https://echo.labstack.com/docs/error-handling
func customHTTPErrorHandler(err error, c echo.Context) {
code := http.StatusInternalServerError // default?
if he, ok := err.(*echo.HTTPError); ok {
code = he.Code
}
pd := new(pageData)
pd.PageTitle = strconv.Itoa(code)
if err := c.Render(code, "error", pd); err != nil {
c.Logger().Error(err)
}
}
func buildHomepage(c echo.Context, db *sql.DB) error {
countryListings := queryCountries(db)
pd := new(pageData)
pd.PageTitle = "Home"
pd.Data = countryListings
return c.Render(http.StatusOK, "home", pd)
}
// searchResults builds the country search results page
func searchResults(c echo.Context, db *sql.DB) error {
result := new(resultsPage)
country := c.QueryParam("country")
page, err := strconv.Atoi(c.QueryParam("page"))
if err != nil {
page = 0
}
matchCount := queryMatchCount(db, country)
places := queryCountryPlaces(db, country, page)
var hasMoreResults bool
if ((page + 1) * pageSize) > matchCount {
hasMoreResults = false
} else {
hasMoreResults = true
}
totalPages := math.Ceil(float64(matchCount / pageSize))
fmtPrinter := message.NewPrinter(message.MatchLanguage("en"))
result.SearchString = country
result.Count = matchCount
result.PageNo = page
result.NextPage = page + 1
// Data for display on the front end:
// Show the total counts with a thousands separator.
// Zero-indexed paging can be confusing.
result.FmtCount = fmtPrinter.Sprintf("%d", matchCount)
result.DispThisPage = page + 1
result.DispTotalPages = int(totalPages) + 1
result.MoreResults = hasMoreResults
result.Results = places
pd := new(pageData)
pd.PageTitle = "Search Results"
pd.Data = result
return c.Render(http.StatusOK, "results", pd)
}
// queryCountries returns a slice of all countries in the db
func queryCountries(db *sql.DB) []countryListing {
var countries []countryListing
q := `
SELECT country_name, COUNT(place_name)
FROM countries_places
WHERE country_name IS NOT NULL
GROUP BY country_name
ORDER BY country_name ASC
`
rows, err := db.Query(q)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var country countryListing
if err := rows.Scan(
&country.Name,
&country.PlaceCount,
); err != nil {
log.Fatal(err)
}
countries = append(countries, country)
}
return countries
}
// queryMatchCount returns a count of matching place results
func queryMatchCount(db *sql.DB, name string) int {
var count int
q := `
SELECT COUNT(place_name)
FROM countries_places
WHERE country_name ILIKE '%' || $1 || '%'
`
row := db.QueryRow(q, name)
row.Scan(&count)
return count
}
// queryCountryPlaces returns a slice of matching PleiadesPlaces
func queryCountryPlaces(db *sql.DB, name string, page int) []pleiadesPlace {
var matchPlaces []pleiadesPlace
offset := pageSize * page
q := `
SELECT
place_name,
country_name,
place_type,
COALESCE(descrip, ''),
pleiades_uri
FROM countries_places
WHERE country_name ILIKE '%' || $1 || '%'
ORDER BY place_name ASC
LIMIT $2 OFFSET $3;
`
rows, err := db.Query(q, name, pageSize, offset)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var place pleiadesPlace
if err := rows.Scan(
&place.Name,
&place.Country,
&place.PlaceType,
&place.Description,
&place.URI,
); err != nil {
log.Fatal(err)
}
matchPlaces = append(matchPlaces, place)
}
return matchPlaces
}