answer/pkg/search/google.go
Steve Dudenhoeffer 37c18b3b58 Update module name to match new repository URL
Renamed the Go module to align with the updated repository path for better clarity and organization. This ensures consistency across the project and prevents potential import conflicts.
2025-02-21 18:45:27 -05:00

60 lines
1.2 KiB
Go

package search
import (
"context"
"log/slog"
"sort"
googlesearch "github.com/rocketlaunchr/google-search"
"gitea.stevedudenhoeffer.com/steve/answer/pkg/cache"
)
type Google struct {
Cache cache.Cache
}
var _ Search = Google{}
func (g Google) Search(ctx context.Context, search string) ([]Result, error) {
var res []Result
key := "google:" + search
err := g.Cache.GetJSON(key, &res)
slog.Info("searching", "search", search, "results", res, "err", err)
if err == nil {
return res, nil
}
results, err := googlesearch.Search(ctx, search, googlesearch.SearchOptions{
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
})
slog.Info("searched", "search", search, "results", results, "err", err)
if err != nil {
return nil, err
}
// just in case, sort the res by rank, as the api does not mention it is sorted
sort.Slice(res, func(i, j int) bool {
return results[i].Rank < results[j].Rank
})
for _, r := range results {
res = append(res, Result{
Title: r.Title,
URL: r.URL,
Description: r.Description,
})
}
_ = g.Cache.SetJSON(key, res)
return res, nil
}