add basic caching
parent
5419a77c48
commit
cd2da0aa5c
|
@ -0,0 +1 @@
|
||||||
|
.cache/
|
|
@ -0,0 +1,3 @@
|
||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
rm -rf .cache
|
59
main.go
59
main.go
|
@ -2,21 +2,70 @@ package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/karashiiro/bingode"
|
"github.com/karashiiro/bingode"
|
||||||
"github.com/xivapi/godestone/v2"
|
"github.com/xivapi/godestone/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
const CachePath = "./.cache"
|
||||||
s := godestone.NewScraper(bingode.New(), godestone.EN)
|
|
||||||
|
|
||||||
c, err := s.FetchCharacter(29932586)
|
type CacheRecord struct {
|
||||||
|
Time time.Time `json:"time"`
|
||||||
|
Data string `json:"data"`
|
||||||
|
}
|
||||||
|
type Cache map[uint32]CacheRecord
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
err := os.MkdirAll(CachePath, 0755)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
raw_cache, err := os.ReadFile(path.Join(CachePath, "cache.json"))
|
||||||
|
var cache Cache
|
||||||
|
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
cache = make(Cache)
|
||||||
|
} else if err == nil {
|
||||||
|
err := json.Unmarshal(raw_cache, &cache)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalln(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.Fatalln(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var id uint32 = 29932586
|
||||||
|
data, ok := cache[id]
|
||||||
|
if !ok {
|
||||||
|
log.Printf("Fetching fresh data for %d\n", id)
|
||||||
|
s := godestone.NewScraper(bingode.New(), godestone.EN)
|
||||||
|
|
||||||
|
c, err := s.FetchCharacter(id)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalln(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
raw_data, _ := json.Marshal(c.ClassJobs)
|
||||||
|
data = CacheRecord{Time: time.Now(), Data: string(raw_data)}
|
||||||
|
|
||||||
|
cache[id] = data
|
||||||
|
}
|
||||||
|
|
||||||
|
cache_as_stored, err := json.Marshal(cache)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalln(err)
|
log.Fatalln(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
data, _ := json.Marshal(c.ClassJobs)
|
err = os.WriteFile(path.Join(CachePath, "cache.json"), cache_as_stored, 0755)
|
||||||
fmt.Printf("%s\n", data)
|
if err != nil {
|
||||||
|
log.Fatalln(err)
|
||||||
|
}
|
||||||
|
fmt.Printf("%s\n", data.Data)
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue