Before we start adding anything to the frontend side of things we need to create a migration.
Adding and registering the new route
Let’s add search
into a navbar and also register its route with our HTTP server.
In /web/handler/html/common/layout.go
add the following link:
<a href="/search">search</a>
To register a new route, we need to edit /web/handler/handler.go
, since we don’t have a template, let’s add placeholder for now:
// Search
publicSubRouter.HandleFunc("/search", nil).Methods(http.MethodGet)
Creating and displaying the template
Let’s create /web/handler/search.go
and create a function that checks if we have a query (from search input form) and perform a request to our database with that query. Then we set context for our template with the query itself and the response from the database.
// /web/handler.search.go
package handler
import (
"net/http"
)
func (h *Handler) searchShow(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("q")
thing, _ := h.storage.Search(query)
v := NewView(w, r, "search") // We don't have that yet!
v.Set("sql", thing)
v.Set("q", query)
v.Render()
}
And let’s create a template for it - /web/handler/html/search.gohtml
. We need to display the text input, submit button and some sort of a list of results.
We need to add 2 sections: title
and content
. In content
we check if we have:
.q
- our query (""
means empty)
.sql
- response from the database
{{ define "title" }} Search {{ end }}
{{ define "content" }}
<h2>Search</h2>
{{ if .q }}
<p>{{ len .sql }} results found.</p>
{{ else }}
<p>Enter your search query down below.</p>
{{ end }}
<form action="/search" method="get" class="search-form">
<label for="q" style="display: none">Search</label>
<input type="text" value="{{ .q }}" name="q" id="q" placeholder="...">
<button type="submit">search</button>
</form>
{{ if .sql }}
{{ range $index, $element := .sql }}
<div class="search-result">
<span>[{{ $element.OriginTable }}]</span>
<a href="/{{ $element.OriginTable }}/{{ $element.ID }}">{{ $element.HighlightedTitle }}</a>
{{ if ne $element.HighlightedContent "" }}
<div class="content">
{{ $element.HighlightedContent }}...
</div>
{{ end }}
</div>
{{ end }}
{{ end }}
{{ end }}
And done! Run go generate
and run the vpub itself.