separate cache module
Marco Andronaco andronacomarco@gmail.com
Fri, 22 Dec 2023 12:47:55 +0100
3 files changed,
60 insertions(+),
60 deletions(-)
M
api.go
→
cache/api.go
@@ -1,4 +1,4 @@
-package main +package cache import ( "context"@@ -20,8 +20,10 @@ "google.golang.org/api/sheets/v4"
) type GoogleAPI struct { - Ctx context.Context - Client *http.Client + Ctx context.Context + Client *http.Client + spreadsheetId string + spreadsheetRange string } type Entry struct {@@ -86,7 +88,7 @@ defer f.Close()
json.NewEncoder(f).Encode(token) } -func initGoogleAPI() *GoogleAPI { +func initGoogleAPI(spreadsheetId string, spreadsheetRange string) *GoogleAPI { ctx := context.Background() b, err := os.ReadFile("credentials.json") if err != nil {@@ -99,7 +101,7 @@ if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err) } client := getClient(config) - return &GoogleAPI{ctx, client} + return &GoogleAPI{ctx, client, spreadsheetId, spreadsheetRange} } func getEntries(googleApi *GoogleAPI) ([]Entry, error) {@@ -109,7 +111,7 @@ log.Fatalf("Unable to retrieve Sheets client: %v", err)
return nil, err } - resp, err := srv.Spreadsheets.Values.Get(spreadsheetId, spreadsheetRange).Do() + resp, err := srv.Spreadsheets.Values.Get(googleApi.spreadsheetId, googleApi.spreadsheetRange).Do() if err != nil { log.Fatalf("Unable to retrieve data from sheet: %v", err) return nil, err
M
artbound.go
→
artbound.go
@@ -10,11 +10,9 @@ "net/url"
"os" "time" + "github.com/BiRabittoh/artbound-go/cache" "github.com/joho/godotenv" ) - -var spreadsheetId string -var spreadsheetRange string var templatesDirectory = "templates/" var indexTemplate = template.Must(template.ParseFiles(templatesDirectory + "index.html"))@@ -26,7 +24,7 @@ LastUpdated string
CurrentMonth string } -func indexHandler(db *DB) http.HandlerFunc { +func indexHandler(db *cache.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "Please use GET.", http.StatusMethodNotAllowed)@@ -61,7 +59,7 @@ }
buf.WriteTo(w) } -func clearHandler(db *DB) http.HandlerFunc { +func clearHandler(db *cache.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Please use POST.", http.StatusMethodNotAllowed)@@ -76,7 +74,7 @@ http.Error(w, "Done.", http.StatusOK)
} } -func updateHandler(googleApi *GoogleAPI, db *DB) http.HandlerFunc { +func updateHandler(db *cache.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Please use POST.", http.StatusMethodNotAllowed)@@ -89,7 +87,7 @@ json.NewEncoder(w).Encode(p)
} } -func getHandler(googleApi *GoogleAPI, db *DB) http.HandlerFunc { +func getHandler(db *cache.DB) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { u, err := url.Parse(r.URL.String()) if err != nil {@@ -116,6 +114,7 @@ func main() {
err := godotenv.Load() if err != nil { log.Println("No .env file provided.") + os.Exit(1) } port := os.Getenv("PORT")@@ -123,29 +122,27 @@ if port == "" {
port = "3000" } - spreadsheetId = os.Getenv("SPREADSHEET_ID") + spreadsheetId := os.Getenv("SPREADSHEET_ID") if spreadsheetId == "" { log.Fatal("Please fill out SPREADSHEET_ID in .env") os.Exit(1) } - spreadsheetRange = os.Getenv("SPREADSHEET_RANGE") + spreadsheetRange := os.Getenv("SPREADSHEET_RANGE") if spreadsheetRange == "" { log.Fatal("Please fill out SPREADSHEET_RANGE in .env") os.Exit(1) } fs := http.FileServer(http.Dir("./static")) - - googleApi := initGoogleAPI() - db := initDB(googleApi) + db := cache.InitDB(spreadsheetId, spreadsheetRange) r := http.NewServeMux() r.HandleFunc("/", indexHandler(db)) r.HandleFunc("/clear", clearHandler(db)) + r.HandleFunc("/update", updateHandler(db)) + r.HandleFunc("/get", getHandler(db)) r.HandleFunc("/help", helpHandler) - r.HandleFunc("/update", updateHandler(googleApi, db)) - r.HandleFunc("/get", getHandler(googleApi, db)) r.Handle("/static/", http.StripPrefix("/static/", fs)) log.Println("Serving on port", port)
M
cache.go
→
cache/cache.go
@@ -1,4 +1,4 @@
-package main +package cache import ( "fmt"@@ -19,46 +19,15 @@
type DB struct { LastUpdated time.Time Entries []Entry - cachedEntries []FileDetails + cachedEntries []fileDetails googleApi GoogleAPI } -type FileDetails struct { +type fileDetails struct { FileName string Extension string } -func initDB(googleApi *GoogleAPI) *DB { - files, err := listCachedEntries(cachePath) - if err != nil { - log.Fatal("Could not list cached entries.") - } - db := &DB{time.Now(), []Entry{}, files, *googleApi} - db.update() - return db -} - -func (db *DB) update() (error, int) { - entries, err := getEntries(&db.googleApi) - if err != nil { - log.Fatal("Could not update DB!", err) - return err, 0 - } - newEntries := len(entries) - len(db.Entries) - db.Entries = entries - db.LastUpdated = time.Now() - return nil, newEntries -} - -func (db *DB) UpdateCall() UpdateDBPayload { - err, newEntries := db.update() - if err != nil { - log.Fatal("Could not update DB!", err) - newEntries = 0 - } - return UpdateDBPayload{db.LastUpdated.Format("02/01/2006 15:04"), newEntries} -} - func filter[T any](ss []T, test func(T) bool) (ret []T) { for _, s := range ss { if test(s) {@@ -68,8 +37,8 @@ }
return } -func listCachedEntries(cachePath string) ([]FileDetails, error) { - var files []FileDetails +func listCachedEntries(cachePath string) ([]fileDetails, error) { + var files []fileDetails err := filepath.Walk(cachePath, func(path string, info os.FileInfo, err error) error { if err != nil {@@ -84,7 +53,7 @@ fileName := info.Name()
extension := filepath.Ext(fileName) fileNameWithoutExt := strings.TrimSuffix(fileName, extension) - file := FileDetails{ + file := fileDetails{ FileName: fileNameWithoutExt, Extension: extension, }@@ -94,13 +63,13 @@ return nil
}) if err != nil { - return []FileDetails{}, err + return []fileDetails{}, err } return files, nil } -func isCached(cachedEntries []FileDetails, target string) (bool, string) { +func isCached(cachedEntries []fileDetails, target string) (bool, string) { for _, file := range cachedEntries { if file.FileName == target { return true, file.Extension@@ -109,6 +78,38 @@ }
return false, "" } +func InitDB(spreadsheetId string, spreadsheetRange string) *DB { + files, err := listCachedEntries(cachePath) + if err != nil { + log.Fatal("Could not list cached entries.") + } + googleApi := initGoogleAPI(spreadsheetId, spreadsheetRange) + db := &DB{time.Now(), []Entry{}, files, *googleApi} + db.update() + return db +} + +func (db *DB) update() (error, int) { + entries, err := getEntries(&db.googleApi) + if err != nil { + log.Fatal("Could not update DB!", err) + return err, 0 + } + newEntries := len(entries) - len(db.Entries) + db.Entries = entries + db.LastUpdated = time.Now() + return nil, newEntries +} + +func (db *DB) UpdateCall() UpdateDBPayload { + err, newEntries := db.update() + if err != nil { + log.Fatal("Could not update DB!", err) + newEntries = 0 + } + return UpdateDBPayload{db.LastUpdated.Format("02/01/2006 15:04"), newEntries} +} + func (db *DB) GetEntries(month string) ([]Entry, error) { monthTest := func(f Entry) bool { return f.Month == month } res := filter(db.Entries, monthTest)@@ -156,6 +157,6 @@
if err != nil { return err } - db.cachedEntries = []FileDetails{} + db.cachedEntries = []fileDetails{} return nil }