92 lines
2.6 KiB
Go
92 lines
2.6 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/PuerkitoBio/goquery"
|
|
)
|
|
|
|
// PerformBraveTextSearch performs a text search on Brave and returns the results.
|
|
func PerformBraveTextSearch(query, safe, lang string, offset int) ([]TextSearchResult, time.Duration, error) {
|
|
startTime := time.Now() // Start the timer
|
|
var results []TextSearchResult
|
|
|
|
// Build the search URL
|
|
searchURL := fmt.Sprintf("https://search.brave.com/search?q=%s&offset=%d", url.QueryEscape(query), offset)
|
|
|
|
req, err := http.NewRequest("GET", searchURL, nil)
|
|
if err != nil {
|
|
printWarn("Error creating request: %v", err)
|
|
return nil, 0, fmt.Errorf("creating request: %v", err)
|
|
}
|
|
|
|
// Set headers including User-Agent
|
|
TextUserAgent, err := GetUserAgent("Text-Search")
|
|
if err != nil {
|
|
printWarn("Error generating User-Agent: %v", err)
|
|
return nil, 0, err
|
|
}
|
|
req.Header.Set("User-Agent", TextUserAgent)
|
|
|
|
var resp *http.Response
|
|
|
|
// Determine whether to use a proxy client or a default client
|
|
if config.MetaProxyEnabled && metaProxyClient != nil {
|
|
resp, err = metaProxyClient.Do(req)
|
|
} else {
|
|
client := &http.Client{}
|
|
resp, err = client.Do(req)
|
|
}
|
|
|
|
if err != nil {
|
|
printWarn("Error performing request: %v", err)
|
|
return nil, 0, fmt.Errorf("performing request: %v", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
// Read the response body
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
printWarn("Error reading response body: %v", err)
|
|
return nil, 0, fmt.Errorf("reading response body: %v", err)
|
|
}
|
|
|
|
// Parse the response body
|
|
doc, err := goquery.NewDocumentFromReader(strings.NewReader(string(body)))
|
|
if err != nil {
|
|
printErr("Error parsing response body: %v", err)
|
|
return nil, 0, fmt.Errorf("parsing response body: %v", err)
|
|
}
|
|
|
|
// Extract search results
|
|
doc.Find(".snippet").Each(func(i int, s *goquery.Selection) {
|
|
title := s.Find(".title").Text()
|
|
description := s.Find(".snippet-description").Text()
|
|
url, exists := s.Find("a").Attr("href")
|
|
|
|
// Add to results only if all components are present
|
|
if title != "" && description != "" && exists && url != "" {
|
|
results = append(results, TextSearchResult{
|
|
Header: title,
|
|
URL: url,
|
|
Description: description,
|
|
})
|
|
}
|
|
})
|
|
|
|
duration := time.Since(startTime) // Calculate the duration
|
|
|
|
// Return an error if no results are found
|
|
if len(results) == 0 {
|
|
printDebug("No results found for query: %s", query)
|
|
return nil, duration, fmt.Errorf("no results found")
|
|
}
|
|
|
|
printDebug("Search completed successfully for query: %s, found %d results", query, len(results))
|
|
return results, duration, nil
|
|
}
|