added "next page" button

This commit is contained in:
admin 2024-04-07 15:48:25 +02:00
parent f91830e92e
commit fbbf5ad5ff
5 changed files with 77 additions and 26 deletions

View file

@ -37,19 +37,50 @@ type QwantAPIResponse struct {
} `json:"data"` } `json:"data"`
} }
// FetchImageResults contacts the image search API and returns a slice of ImageSearchResult var funcs = template.FuncMap{
func fetchImageResults(query string) ([]ImageSearchResult, error) { "sub": func(a, b int) int {
client := &http.Client{Timeout: 10 * time.Second} return a - b
},
"add": func(a, b int) int {
return a + b
},
}
// Update this URL to the actual API endpoint you intend to use // FetchImageResults contacts the image search API and returns a slice of ImageSearchResult
apiURL := fmt.Sprintf("https://api.qwant.com/v3/search/images?t=images&q=%s&count=50&locale=en_CA&offset=1&device=desktop&tgp=2&safesearch=1", url.QueryEscape(query)) func fetchImageResults(query string, safe, lang string, page int) ([]ImageSearchResult, error) {
const resultsPerPage = 50
var offset int
if page <= 1 {
offset = 0 // Assuming the API expects offset to start from 0 for the first page
} else {
offset = (page - 1) * resultsPerPage
}
// Ensuring safe search is enabled by default if not specified
if safe == "" {
safe = "1"
}
// Defaulting to English Canada locale if not specified
if lang == "" {
lang = "en_CA"
}
apiURL := fmt.Sprintf("https://api.qwant.com/v3/search/images?t=images&q=%s&count=%d&locale=%s&offset=%d&device=desktop&tgp=2&safesearch=%s",
url.QueryEscape(query),
resultsPerPage,
lang,
offset,
safe)
client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("GET", apiURL, nil) req, err := http.NewRequest("GET", apiURL, nil)
if err != nil { if err != nil {
return nil, fmt.Errorf("creating request: %v", err) return nil, fmt.Errorf("creating request: %v", err)
} }
req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; YourBot/1.0; +http://yourbot.com/bot.html)") req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36")
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
@ -83,15 +114,16 @@ func fetchImageResults(query string) ([]ImageSearchResult, error) {
} }
// HandleImageSearch is the HTTP handler for image search requests // HandleImageSearch is the HTTP handler for image search requests
func handleImageSearch(w http.ResponseWriter, r *http.Request, query string) { func handleImageSearch(w http.ResponseWriter, query, safe, lang string, page int) {
results, err := fetchImageResults(query) results, err := fetchImageResults(query, safe, lang, page)
if err != nil { if err != nil {
log.Printf("Error performing image search: %v", err) log.Printf("Error performing image search: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError) http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return return
} }
tmpl, err := template.ParseFiles("templates/images.html") // Ensure path is correct // Parsing the template file with the custom function map
tmpl, err := template.New("images.html").Funcs(funcs).ParseFiles("templates/images.html")
if err != nil { if err != nil {
log.Printf("Error parsing template: %v", err) log.Printf("Error parsing template: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError) http.Error(w, "Internal Server Error", http.StatusInternalServerError)
@ -99,13 +131,19 @@ func handleImageSearch(w http.ResponseWriter, r *http.Request, query string) {
} }
data := struct { data := struct {
Results []ImageSearchResult Results []ImageSearchResult
Query string Query string
Fetched string Page int
Fetched string
HasPrevPage bool
HasNextPage bool
}{ }{
Results: results, Results: results,
Query: query, Query: query,
Fetched: fmt.Sprintf("%.2f seconds", time.Since(time.Now()).Seconds()), Page: page,
Fetched: fmt.Sprintf("%.2f seconds", time.Since(time.Now()).Seconds()),
HasPrevPage: page > 1,
HasNextPage: len(results) >= 50,
} }
err = tmpl.Execute(w, data) err = tmpl.Execute(w, data)

10
main.go
View file

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"log" "log"
"net/http" "net/http"
"strconv"
) )
// LanguageOption represents a language option for search // LanguageOption represents a language option for search
@ -80,12 +81,19 @@ func main() {
func handleSearch(w http.ResponseWriter, r *http.Request) { func handleSearch(w http.ResponseWriter, r *http.Request) {
var query, safe, lang, searchType string var query, safe, lang, searchType string
var page int
if r.Method == "GET" { if r.Method == "GET" {
query = r.URL.Query().Get("q") query = r.URL.Query().Get("q")
safe = r.URL.Query().Get("safe") safe = r.URL.Query().Get("safe")
lang = r.URL.Query().Get("lang") lang = r.URL.Query().Get("lang")
searchType = r.URL.Query().Get("t") searchType = r.URL.Query().Get("t")
pageStr := r.URL.Query().Get("p")
var err error
page, err = strconv.Atoi(pageStr)
if err != nil || page < 1 {
page = 1 // Default to page 1 if no valid page is specified
}
} else if r.Method == "POST" { } else if r.Method == "POST" {
query = r.FormValue("q") query = r.FormValue("q")
safe = r.FormValue("safe") safe = r.FormValue("safe")
@ -102,7 +110,7 @@ func handleSearch(w http.ResponseWriter, r *http.Request) {
case "text": case "text":
handleTextSearch(w, r, query, safe, lang) // Handles fetching and rendering text search results handleTextSearch(w, r, query, safe, lang) // Handles fetching and rendering text search results
case "image": case "image":
handleImageSearch(w, r, query) // Handles fetching and rendering image search results handleImageSearch(w, query, safe, lang, page) // Adjusted: Pass *http.Request to match the function signature
default: default:
http.ServeFile(w, r, "static/search.html") http.ServeFile(w, r, "static/search.html")
} }

View file

@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search with TailsGo</title> <title>Search with Ocásek</title>
<link rel="stylesheet" href="/static/css/style.css"> <link rel="stylesheet" href="/static/css/style.css">
</head> </head>
<body> <body>
@ -11,7 +11,7 @@
<!-- Assuming you have specific styles for this in your CSS --> <!-- Assuming you have specific styles for this in your CSS -->
</div> </div>
<form action="/search" class="search-container" method="post" autocomplete="off"> <form action="/search" class="search-container" method="post" autocomplete="off">
<h1>TailsGo</h1> <h1>Ocásek</h1>
<div class="wrapper"> <div class="wrapper">
<input type="text" name="q" autofocus id="search-input" placeholder="Type to search..." /> <input type="text" name="q" autofocus id="search-input" placeholder="Type to search..." />
<button id="search-wrapper-ico" class="material-icons-round" name="t" value="text" type="submit">search</button> <button id="search-wrapper-ico" class="material-icons-round" name="t" value="text" type="submit">search</button>

View file

@ -8,7 +8,7 @@
</head> </head>
<body> <body>
<div class="header"> <div class="header">
<h1>TailsGo</h1> <h1>Ocásek</h1>
<form action="/search" method="post" class="search-form" autocomplete="off"> <form action="/search" method="post" class="search-form" autocomplete="off">
<div class="search-bar"> <div class="search-bar">
<input type="text" name="q" value="{{ .Query }}" autofocus id="search-input" placeholder="Type to search..." /> <input type="text" name="q" value="{{ .Query }}" autofocus id="search-input" placeholder="Type to search..." />
@ -40,7 +40,7 @@
<!-- Images Grid --> <!-- Images Grid -->
{{ range .Results }} {{ range .Results }}
<div class="image"> <div class="image">
<a class="clickable" href="{{ .Source }}" target="_blank"> <a class="clickable" href="{{ .ThumbProxy }}" target="_blank">
<img src="{{ .ThumbProxy }}" alt="{{ .Title }}" data-media="{{ .Media }}"> <img src="{{ .ThumbProxy }}" alt="{{ .Title }}" data-media="{{ .Media }}">
<div class="resolution">{{ .Width }} × {{ .Height }}</div> <div class="resolution">{{ .Width }} × {{ .Height }}</div>
<div class="details"> <div class="details">
@ -53,12 +53,17 @@
</div> </div>
<!-- Pagination --> <!-- Pagination -->
<div class="prev-next prev-img"> <div class="prev-next prev-img">
<!-- Update form action and method according to your app's routing and logic -->
<form action="/search" method="get"> <form action="/search" method="get">
<input type="hidden" name="q" value="{{ .Query }}"> <input type="hidden" name="q" value="{{ .Query }}">
<!-- Pagination buttons, implement pagination logic in your Go handler --> <input type="hidden" name="t" value="image">
<button type="submit" name="p" value="previous">Previous</button> {{ if .HasPrevPage }}
<button type="submit" name="p" value="next">Next</button> <!-- Subtract 1 from the current page for the Previous button -->
<button type="submit" name="p" value="{{ sub .Page 1 }}">Previous</button>
{{ end }}
{{ if .HasNextPage }}
<!-- Add 1 to the current page for the Next button -->
<button type="submit" name="p" value="{{ add .Page 1 }}">Next</button>
{{ end }}
</form> </form>
</div> </div>
{{ else }} {{ else }}
@ -66,4 +71,4 @@
{{ end }} {{ end }}
</div> </div>
</body> </body>
</html> </html>

View file

@ -8,7 +8,7 @@
</head> </head>
<body> <body>
<div class="header"> <div class="header">
<h1>TailsGo</h1> <h1>Ocásek</h1>
<form action="/search" method="post" class="search-form" autocomplete="off"> <form action="/search" method="post" class="search-form" autocomplete="off">
<div class="search-bar"> <div class="search-bar">
<input type="text" name="q" value="{{ .Query }}" autofocus id="search-input" placeholder="Type to search..." /> <input type="text" name="q" value="{{ .Query }}" autofocus id="search-input" placeholder="Type to search..." />