Search/text-google.go

114 lines
2.9 KiB
Go
Raw Normal View History

2024-04-15 06:35:17 +00:00
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"net/url"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
)
type TextSearchResult struct {
URL string
Header string
Description string
}
func PerformTextSearch(query, safe, lang string) ([]TextSearchResult, error) {
var results []TextSearchResult
client := &http.Client{}
safeParam := "&safe=off"
if safe == "active" {
safeParam = "&safe=active"
}
langParam := ""
if lang != "" {
langParam = "&lr=" + lang
}
searchURL := "https://www.google.com/search?q=" + url.QueryEscape(query) + safeParam + langParam
req, err := http.NewRequest("GET", searchURL, nil)
if err != nil {
log.Fatalf("Failed to create request: %v", err)
}
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)
if err != nil {
return nil, err
}
defer resp.Body.Close()
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return nil, err
}
doc.Find(".yuRUbf").Each(func(i int, s *goquery.Selection) {
link := s.Find("a")
href, _ := link.Attr("href")
header := link.Find("h3").Text()
header = strings.TrimSpace(strings.TrimSuffix(header, ""))
descSelection := doc.Find(".VwiC3b").Eq(i)
description := ""
if descSelection.Length() > 0 {
description = descSelection.Text()
}
results = append(results, TextSearchResult{
URL: href,
Header: header,
Description: description,
})
})
return results, nil
}
2024-05-16 16:29:26 +00:00
func handleTextSearchGoogle(w http.ResponseWriter, query, safe, lang string) {
2024-04-15 06:35:17 +00:00
// Perform the text search
results, err := PerformTextSearch(query, safe, lang)
if err != nil {
log.Printf("Error performing text search: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Assuming you have a separate template for text search results
tmpl, err := template.ParseFiles("templates/text.html") // Ensure this path matches your templates' location
if err != nil {
log.Printf("Error parsing template: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
data := struct {
Results []TextSearchResult // Ensure this type matches the structure expected by your template
Query string
Fetched string
LanguageOptions []LanguageOption
CurrentLang string
}{
Results: results,
Query: query,
Fetched: fmt.Sprintf("%.2f seconds", time.Since(time.Now()).Seconds()), // Example fetched time, adjust as necessary
LanguageOptions: languageOptions, // Assuming this is defined globally or elsewhere
CurrentLang: lang,
}
err = tmpl.Execute(w, data)
if err != nil {
log.Printf("Error executing template: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}