using the cache lmao
This commit is contained in:
parent
d5bbfe118d
commit
bc85d7d4a2
2 changed files with 66 additions and 20 deletions
43
text.go
43
text.go
|
@ -1,4 +1,3 @@
|
|||
// text.go
|
||||
package main
|
||||
|
||||
import (
|
||||
|
@ -14,7 +13,7 @@ import (
|
|||
|
||||
var (
|
||||
debugMode bool
|
||||
resultsCache = NewResultsCache()
|
||||
resultsCache = NewResultsCache(6 * time.Hour) // Cache with 6-hour expiration
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
@ -27,21 +26,45 @@ func HandleTextSearch(w http.ResponseWriter, query, safe, lang string, page int)
|
|||
const resultsPerPage = 10
|
||||
|
||||
cacheKey := CacheKey{Query: query, Page: page, Safe: safe, Lang: lang}
|
||||
cacheChan := make(chan []TextSearchResult)
|
||||
var combinedResults []TextSearchResult
|
||||
var fromCache bool
|
||||
|
||||
// Try to get results from cache
|
||||
combinedResults, exists := resultsCache.Get(cacheKey)
|
||||
if !exists {
|
||||
// Fetch results for the current page
|
||||
go func() {
|
||||
results, exists := resultsCache.Get(cacheKey)
|
||||
if exists {
|
||||
log.Println("Cache hit")
|
||||
cacheChan <- results
|
||||
} else {
|
||||
log.Println("Cache miss")
|
||||
cacheChan <- nil
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case combinedResults = <-cacheChan:
|
||||
if combinedResults != nil {
|
||||
fromCache = true
|
||||
} else {
|
||||
combinedResults = fetchAndCacheResults(query, safe, lang, page, resultsPerPage)
|
||||
resultsCache.Set(cacheKey, combinedResults)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
log.Println("Cache check timeout")
|
||||
combinedResults = fetchAndCacheResults(query, safe, lang, page, resultsPerPage)
|
||||
resultsCache.Set(cacheKey, combinedResults)
|
||||
}
|
||||
|
||||
// Pre-fetch and cache results for the next page
|
||||
nextPageResults := fetchAndCacheResults(query, safe, lang, page+1, resultsPerPage)
|
||||
resultsCache.Set(CacheKey{Query: query, Page: page + 1, Safe: safe, Lang: lang}, nextPageResults)
|
||||
// Only pre-fetch and cache results for the next page if we fetched new results
|
||||
if !fromCache {
|
||||
go func() {
|
||||
nextPageResults := fetchAndCacheResults(query, safe, lang, page+1, resultsPerPage)
|
||||
resultsCache.Set(CacheKey{Query: query, Page: page + 1, Safe: safe, Lang: lang}, nextPageResults)
|
||||
}()
|
||||
}
|
||||
|
||||
hasPrevPage := page > 1
|
||||
hasNextPage := len(nextPageResults) > 0
|
||||
hasNextPage := len(combinedResults) == resultsPerPage
|
||||
|
||||
displayResults(w, combinedResults, query, lang, time.Since(startTime).Seconds(), page, hasPrevPage, hasNextPage)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue