123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- package datautil
- import (
- "encoding/gob"
- "os"
- )
- type PersistentMap struct {
- filename string
- Data map[string]interface{}
- }
- func NewPersistentMap(filename string) (*PersistentMap, error) {
- pm := &PersistentMap{filename, make(map[string]interface{})}
- return pm, pm.Flush()
- }
- func LoadPersistentMap(filename string) (*PersistentMap, error) {
- file, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0660)
- if err != nil {
- return nil, err
- }
- defer file.Close()
- pm := &PersistentMap{filename, make(map[string]interface{})}
- de := gob.NewDecoder(file)
- return pm, de.Decode(&pm.Data)
- }
- func (pm *PersistentMap) Flush() error {
- file, err := os.OpenFile(pm.filename, os.O_CREATE|os.O_RDWR, 0660)
- if err != nil {
- return err
- }
- defer file.Close()
- en := gob.NewEncoder(file)
- return en.Encode(pm.Data)
- }
- type PersistentStringMap struct {
- filename string
- Data map[string]string
- }
- func NewPersistentStringMap(filename string) (*PersistentStringMap, error) {
- pm := &PersistentStringMap{filename, make(map[string]string)}
- return pm, pm.Flush()
- }
- func LoadPersistentStringMap(filename string) (*PersistentStringMap, error) {
- file, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0660)
- if err != nil {
- return nil, err
- }
- pm := &PersistentStringMap{filename, make(map[string]string)}
- de := gob.NewDecoder(file)
- de.Decode(&pm.Data)
- return pm, file.Close()
- }
- func (pm *PersistentStringMap) Flush() error {
- file, err := os.OpenFile(pm.filename, os.O_CREATE|os.O_RDWR, 0660)
- if err != nil {
- return err
- }
- en := gob.NewEncoder(file)
- en.Encode(pm.Data)
- return file.Close()
- }
|