github.com/df-mc/dragonfly@v0.9.13/server/player/playerdb/leveldb.go (about) 1 package playerdb 2 3 import ( 4 "encoding/json" 5 "github.com/df-mc/dragonfly/server/player" 6 "github.com/df-mc/dragonfly/server/world" 7 "github.com/df-mc/goleveldb/leveldb" 8 "github.com/df-mc/goleveldb/leveldb/opt" 9 "github.com/google/uuid" 10 "os" 11 ) 12 13 // Provider is a player data provider that uses a LevelDB database to store data. The data passed on 14 // will first be converted to make sure it can be marshaled into JSON. This JSON (in bytes) will then 15 // be stored in the database under a key that is the byte representation of the player's UUID. 16 type Provider struct { 17 db *leveldb.DB 18 } 19 20 // NewProvider creates a new player data provider that saves and loads data using 21 // a LevelDB database. 22 func NewProvider(path string) (*Provider, error) { 23 if _, err := os.Stat(path); os.IsNotExist(err) { 24 _ = os.Mkdir(path, 0777) 25 } 26 db, err := leveldb.OpenFile(path, &opt.Options{Compression: opt.SnappyCompression}) 27 if err != nil { 28 return nil, err 29 } 30 return &Provider{db: db}, nil 31 } 32 33 // Save ... 34 func (p *Provider) Save(id uuid.UUID, d player.Data) error { 35 b, err := json.Marshal(p.toJson(d)) 36 if err != nil { 37 return err 38 } 39 return p.db.Put(id[:], b, nil) 40 } 41 42 // Load ... 43 func (p *Provider) Load(id uuid.UUID, world func(world.Dimension) *world.World) (player.Data, error) { 44 b, err := p.db.Get(id[:], nil) 45 if err != nil { 46 return player.Data{}, err 47 } 48 var d jsonData 49 err = json.Unmarshal(b, &d) 50 if err != nil { 51 return player.Data{}, err 52 } 53 return p.fromJson(d, world), nil 54 } 55 56 // Close ... 57 func (p *Provider) Close() error { 58 return p.db.Close() 59 }