2021-11-16 04:56:33 +00:00
|
|
|
package cheapcash
|
|
|
|
|
|
|
|
import "os"
|
|
|
|
|
2021-11-19 10:55:31 +00:00
|
|
|
// Write a key with a value.
|
|
|
|
// If the key already exists in the first place, it will
|
|
|
|
// delete the existing key and replace it with the new
|
|
|
|
// value.
|
|
|
|
//
|
|
|
|
// c := cheapcash.Default()
|
|
|
|
// err := c.Write("users", []byte("Someone\n"))
|
|
|
|
// if err != nil {
|
|
|
|
// // handle your error
|
|
|
|
// }
|
|
|
|
//
|
2021-11-16 04:56:33 +00:00
|
|
|
func (c *Cache) Write(key string, value []byte) error {
|
|
|
|
err := checkDir(sanitizePath(c.Path))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-11-16 05:20:12 +00:00
|
|
|
check, err := c.Exists(c.Path + key)
|
2021-11-16 04:56:33 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if check {
|
|
|
|
err = c.Delete(key)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
file, err := os.Create(sanitizePath(c.Path + key))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
_, err = file.Write(value)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|