mise run and cache hit log
This commit is contained in:
31
cmd/maps.go
31
cmd/maps.go
@@ -2,8 +2,11 @@ package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"golang.org/x/time/rate"
|
||||
"googlemaps.github.io/maps"
|
||||
@@ -11,10 +14,13 @@ import (
|
||||
|
||||
type Maps struct {
|
||||
around Location
|
||||
cache Cache
|
||||
}
|
||||
|
||||
func NewMapsOf(ctx context.Context, town string) (*Maps, error) {
|
||||
m := &Maps{}
|
||||
m := &Maps{
|
||||
cache: NewCache(ctx),
|
||||
}
|
||||
var err error
|
||||
m.around, err = m.textSearchOne(ctx, town)
|
||||
return m, err
|
||||
@@ -32,7 +38,7 @@ type Location struct {
|
||||
}
|
||||
|
||||
func (m *Maps) textSearchOne(ctx context.Context, query string) (Location, error) {
|
||||
results, err := m.textSearch(ctx, query)
|
||||
results, err := m.Search(ctx, query)
|
||||
if err != nil {
|
||||
return Location{}, err
|
||||
} else if len(results) < 1 {
|
||||
@@ -41,7 +47,17 @@ func (m *Maps) textSearchOne(ctx context.Context, query string) (Location, error
|
||||
return results[0], nil
|
||||
}
|
||||
|
||||
func (m *Maps) textSearch(ctx context.Context, query string) ([]Location, error) {
|
||||
func (m *Maps) Search(ctx context.Context, query string) ([]Location, error) {
|
||||
cacheK := path.Join(fmt.Sprint(m.around), query)
|
||||
if b, err := m.cache.Get(ctx, cacheK); err == nil {
|
||||
var locations []Location
|
||||
log.Printf("cache hit for %q", cacheK)
|
||||
if err := json.Unmarshal(b, &locations); err == nil {
|
||||
return locations, nil
|
||||
}
|
||||
}
|
||||
log.Printf("cache miss for %q", cacheK)
|
||||
|
||||
locations := []Location{}
|
||||
nextToken := ""
|
||||
for {
|
||||
@@ -62,6 +78,10 @@ func (m *Maps) textSearch(ctx context.Context, query string) ([]Location, error)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
cacheV, _ := json.Marshal(locations)
|
||||
m.cache.Set(ctx, cacheK, cacheV)
|
||||
|
||||
return locations, ctx.Err()
|
||||
}
|
||||
|
||||
@@ -69,10 +89,9 @@ func (m *Maps) _textSearch(ctx context.Context, query string, nextToken string)
|
||||
mapsLimiter.Wait(ctx)
|
||||
|
||||
var location *maps.LatLng
|
||||
radius := uint(0)
|
||||
if m.around == (Location{}) {
|
||||
radius := uint(250)
|
||||
if m.around != (Location{}) {
|
||||
radius = 250
|
||||
} else {
|
||||
location = &maps.LatLng{
|
||||
Lat: m.around.Lat,
|
||||
Lng: m.around.Lng,
|
||||
|
||||
Reference in New Issue
Block a user