Search/text.go
2024-05-17 14:26:28 +02:00

84 lines
2.1 KiB
Go

// text.go
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"sort"
"time"
)
type TextSearchResult struct {
URL string
Header string
Description string
}
func handleTextSearch(w http.ResponseWriter, query, safe, lang string) {
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)
}
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)
}
}