mirror of
https://github.com/trafficlunar/api.git
synced 2026-06-27 22:24:08 +00:00
feat: data store
This commit is contained in:
parent
4f8ee6cf9c
commit
19bdd27de1
8 changed files with 123 additions and 53 deletions
|
|
@ -1,63 +1,19 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"api/internal/model"
|
||||
"api/internal/storage"
|
||||
)
|
||||
|
||||
const path = "./data/hit.json"
|
||||
|
||||
func GetHitCounter() model.HitCounter {
|
||||
var data model.HitCounter
|
||||
|
||||
jsonFile, err := os.Open(path)
|
||||
if err != nil {
|
||||
slog.Warn("File not found or unable to open", slog.Any("error", err), slog.Any("path", path))
|
||||
return data
|
||||
}
|
||||
defer jsonFile.Close()
|
||||
|
||||
bytes, err := io.ReadAll(jsonFile)
|
||||
if err != nil {
|
||||
slog.Error("Error reading file", slog.Any("error", err), slog.Any("path", path))
|
||||
return data
|
||||
}
|
||||
|
||||
err = json.Unmarshal(bytes, &data)
|
||||
if err != nil {
|
||||
slog.Error("Error unmarshalling JSON", slog.Any("error", err), slog.Any("path", path))
|
||||
return data
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
func IncrementHitCounter() model.Success {
|
||||
data := GetHitCounter()
|
||||
data.Counter++
|
||||
hitsData := storage.GlobalDataStore.Get("hits")
|
||||
|
||||
err := os.MkdirAll(filepath.Dir(path), 0755)
|
||||
if err != nil {
|
||||
slog.Error("Unable to create directory", slog.Any("error", err), slog.Any("path", filepath.Dir(path)))
|
||||
return model.Success{}
|
||||
var hits uint32
|
||||
if hitsData != nil {
|
||||
hits = hitsData.(uint32)
|
||||
}
|
||||
|
||||
jsonString, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
slog.Error("Error marshalling JSON", slog.Any("error", err), slog.Any("path", path))
|
||||
return model.Success{}
|
||||
}
|
||||
|
||||
err = os.WriteFile(path, jsonString, 0644)
|
||||
if err != nil {
|
||||
slog.Error("Error writing to file", slog.Any("error", err), slog.Any("path", path))
|
||||
return model.Success{}
|
||||
}
|
||||
storage.GlobalDataStore.Set("hits", hits+1)
|
||||
|
||||
return model.Success{
|
||||
Success: true,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue