Files
Unified_Dashboard_Suite_Go/cmd/bulk-api-tester/storage.go
T

60 lines
1.2 KiB
Go

package main
import (
"encoding/json"
"os"
"path/filepath"
"sync"
)
// Use RWMutex so concurrent GETs during bulk runs don't block each other.
// Only writes take an exclusive lock.
var storageMutex sync.RWMutex
// atomicWriteJSON writes data to a temporary file and renames it atomically.
// Uses a compact (no indent) encoder to minimize disk I/O size.
func atomicWriteJSON(path string, data any) error {
storageMutex.Lock()
defer storageMutex.Unlock()
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
tmp := path + ".tmp"
f, err := os.Create(tmp)
if err != nil {
return err
}
// Compact encoding — no pretty-print indentation.
// Saves significant I/O on large payloads (collections with many requests).
encoder := json.NewEncoder(f)
if err := encoder.Encode(data); err != nil {
f.Close()
os.Remove(tmp)
return err
}
if err := f.Close(); err != nil {
os.Remove(tmp)
return err
}
return os.Rename(tmp, path)
}
func readJSON(path string, v any) error {
storageMutex.RLock()
defer storageMutex.RUnlock()
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
return json.NewDecoder(f).Decode(v)
}