69 lines
1.3 KiB
Go
69 lines
1.3 KiB
Go
|
package loaders
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"os"
|
||
|
)
|
||
|
|
||
|
/*
|
||
|
This is a simple database system that peforms CRUD operations on a JSON file.
|
||
|
It will be a proper database system in the future, but for now it will be a JSON file.
|
||
|
Hope this is understandable for future coders.
|
||
|
*/
|
||
|
|
||
|
type DataLoader interface {
|
||
|
Read(filename string) (interface{}, error)
|
||
|
Write(filename string, data interface{}) error
|
||
|
}
|
||
|
|
||
|
type JSON struct{}
|
||
|
|
||
|
func (l *JSON) Read(filename string) (interface{}, error) {
|
||
|
file, err := os.Open(filename)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
defer file.Close()
|
||
|
|
||
|
bytes, err := os.ReadFile(filename)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
data := make(map[string]interface{})
|
||
|
err = json.Unmarshal(bytes, &data)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return data, nil
|
||
|
}
|
||
|
|
||
|
func (l *JSON) Write(filename string, data interface{}) error {
|
||
|
existingData, err := l.Read(filename)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
newData := data.(map[string]interface{})
|
||
|
for k, v := range existingData.(map[string]interface{}) {
|
||
|
if newV, ok := newData[k]; ok {
|
||
|
newData[k] = newV
|
||
|
} else {
|
||
|
newData[k] = v
|
||
|
}
|
||
|
}
|
||
|
|
||
|
bytes, err := json.MarshalIndent(newData, "", " ")
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
err = os.WriteFile(filename, bytes, 0644)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|