Archived
Template
1
0
This repository has been archived on 2023-12-20. You can view files and clone it, but cannot push or open issues or pull requests.
Files
golang-base-project/routes/search.go

77 lines
2.1 KiB
Go
Raw Normal View History

2021-12-12 14:56:13 +01:00
package routes
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/uberswe/golang-base-project/models"
"log"
"net/http"
2022-01-29 12:31:01 +01:00
"net/url"
"strconv"
2021-12-12 14:56:13 +01:00
)
// SearchData holds additional data needed to render the search HTML page
2021-12-12 14:56:13 +01:00
type SearchData struct {
PageData
Results []models.Website
2022-01-29 12:31:01 +01:00
Prev bool
Next bool
PrevURL string
NextURL string
2021-12-12 14:56:13 +01:00
}
// Search renders the search HTML page and any search results
2021-12-12 14:56:13 +01:00
func (controller Controller) Search(c *gin.Context) {
2022-01-29 12:31:01 +01:00
page := 1
resultsPerPage := 5
2022-01-29 10:21:05 +01:00
pdS := controller.DefaultPageData(c)
pdS.Title = pdS.Trans("Search")
2021-12-12 14:56:13 +01:00
pd := SearchData{
2022-01-29 10:21:05 +01:00
PageData: pdS,
2021-12-12 14:56:13 +01:00
}
2022-01-29 12:31:01 +01:00
search := ""
if c.Request.Method == "POST" && c.Request.RequestURI == "/search" {
search = c.PostForm("search")
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("/search/1/%s", url.QueryEscape(search)))
return
} else {
search = c.Param("query")
if i, err := strconv.Atoi(c.Param("page")); err == nil {
page = i
}
}
2021-12-12 14:56:13 +01:00
var results []models.Website
log.Println(search)
2022-01-29 12:31:01 +01:00
searchFilter := fmt.Sprintf("%s%s%s", "%", search, "%")
search2 := fmt.Sprintf("%s%s", "%", search)
search4 := fmt.Sprintf("%s%s", search, "%")
2021-12-12 14:56:13 +01:00
2022-01-29 12:31:01 +01:00
res := controller.db.
Raw(fmt.Sprintf("SELECT * FROM websites WHERE title LIKE ? OR description LIKE ? ORDER BY CASE WHEN title LIKE ? OR description LIKE ? THEN 1 WHEN title LIKE ? OR description LIKE ? THEN 2 WHEN title LIKE ? OR description LIKE ? THEN 4 ELSE 3 END LIMIT %d OFFSET %d", resultsPerPage, resultsPerPage*(page-1)), searchFilter, searchFilter, search, search, search2, search2, search4, search4).
Find(&results)
2021-12-12 14:56:13 +01:00
if res.Error != nil || len(results) == 0 {
pd.Messages = append(pd.Messages, Message{
Type: "error",
2022-01-29 10:21:05 +01:00
Content: pdS.Trans("No results found"),
2021-12-12 14:56:13 +01:00
})
log.Println(res.Error)
c.HTML(http.StatusOK, "search.html", pd)
return
}
pd.Results = results
2022-01-29 12:31:01 +01:00
if len(pd.Results) >= resultsPerPage {
pd.Next = true
pd.NextURL = fmt.Sprintf("/search/%d/%s", page+1, url.QueryEscape(search))
}
if page > 1 {
pd.Prev = true
pd.PrevURL = fmt.Sprintf("/search/%d/%s", page-1, url.QueryEscape(search))
}
2021-12-12 14:56:13 +01:00
c.HTML(http.StatusOK, "search.html", pd)
}