answer/pkg/search/google.go
Steve Dudenhoeffer 7a43e3a5c8 Fix unmarshalling issues and adjust logging for debugging
Modify `FunctionCall` struct to handle arguments as strings. Add debugging logs to facilitate error tracing and improve JSON unmarshalling in various functions.
2024-11-11 00:23:00 -05:00

58 lines
1.1 KiB
Go

package search
import (
"answer/pkg/cache"
"context"
googlesearch "github.com/rocketlaunchr/google-search"
"log/slog"
"sort"
)
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
}