Search/text.go

85 lines
2.1 KiB
Go
Raw Normal View History

2024-05-16 16:29:26 +00:00
// text.go
package main
import (
2024-05-17 12:26:28 +00:00
"fmt"
"html/template"
"log"
2024-05-16 16:29:26 +00:00
"net/http"
2024-05-17 12:26:28 +00:00
"sort"
"time"
2024-05-16 16:29:26 +00:00
)
2024-05-17 12:26:28 +00:00
type TextSearchResult struct {
URL string
Header string
Description string
}
2024-05-16 16:29:26 +00:00
func handleTextSearch(w http.ResponseWriter, query, safe, lang string) {
2024-05-17 12:26:28 +00:00
googleResults, googleErr := PerformGoogleTextSearch(query, safe, lang)
if googleErr != nil {
log.Printf("Error performing Google text search: %v", googleErr)
}
qwantResults, qwantErr := PerformQwantTextSearch(query, safe, lang)
if qwantErr != nil {
log.Printf("Error performing Qwant text search: %v", qwantErr)
}
// Use a map to track URLs and prioritize Qwant results
resultMap := make(map[string]TextSearchResult)
// Add Qwant results to the map first
for _, result := range qwantResults {
resultMap[result.URL] = result
}
// Add Google results to the map if the URL is not already present
for _, result := range googleResults {
if _, exists := resultMap[result.URL]; !exists {
resultMap[result.URL] = result
}
}
// Convert the map back to a slice
var combinedResults []TextSearchResult
for _, result := range resultMap {
combinedResults = append(combinedResults, result)
}
// Sort results (optional, based on some criteria)
sort.SliceStable(combinedResults, func(i, j int) bool {
return combinedResults[i].Header < combinedResults[j].Header
})
displayResults(w, combinedResults, query, lang)
2024-05-16 16:29:26 +00:00
}
2024-05-17 12:26:28 +00:00
func displayResults(w http.ResponseWriter, results []TextSearchResult, query, lang string) {
tmpl, err := template.ParseFiles("templates/text.html")
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
data := struct {
Results []TextSearchResult
Query string
Fetched string
LanguageOptions []LanguageOption
CurrentLang string
}{
Results: results,
Query: query,
Fetched: fmt.Sprintf("%.2f seconds", time.Since(time.Now()).Seconds()),
LanguageOptions: languageOptions,
CurrentLang: lang,
}
err = tmpl.Execute(w, data)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
2024-05-16 16:29:26 +00:00
}