Last active
November 17, 2016 13:16
-
-
Save barthr/8dee1155c467bf76ad23da7e835ad900 to your computer and use it in GitHub Desktop.
Persit errors golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package errorstore | |
import "github.com/boltdb/bolt" | |
var ( | |
errName = []byte("error") | |
) | |
type ErrorPersistance interface { | |
SetError(key, value string) | |
GetError(key string) string | |
RemoveError(key string) | |
} | |
type errorStore struct { | |
db *bolt.DB | |
} | |
func NewErrorPersistence(storage *bolt.DB) ErrorPersistance { | |
datastorage := &errorStore{ | |
db: storage, | |
} | |
return datastorage | |
} | |
func (e *errorStore) SetError(key, value string) { | |
err := e.db.Update(func(tx *bolt.Tx) error { | |
buck, _ := tx.CreateBucketIfNotExists(errName) | |
return buck.Put([]byte(key), []byte(value)) | |
}) | |
if err != nil { | |
Log.Println("Couldn't set error") | |
} | |
} | |
func (e *errorStore) RemoveError(key string) { | |
err := e.db.Update(func(tx *bolt.Tx) error { | |
buck, _ := tx.CreateBucketIfNotExists(errName) | |
return buck.Delete([]byte(key)) | |
}) | |
if err != nil { | |
Log.Println("Couldn't remove key") | |
} | |
} | |
func (e *errorStore) GetError(key string) string { | |
var value string | |
err := e.db.View(func(tx *bolt.Tx) error { | |
buck := tx.Bucket(errName) | |
if buck == nil { | |
return bolt.ErrBucketNotFound | |
} | |
value = string(buck.Get([]byte(key))) | |
return nil | |
}) | |
if err != nil { | |
return "" | |
} | |
return value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment