README
InMemCache: In-Memory Cache in Go
InMemCache is a simple and efficient Go package, offering a basic in-memory caching mechanism. This package serves as an ideal solution for applications that require quick and straightforward mechanisms for temporary data storage and retrieval.
Installation
To include the InMemCache package in your project, use the go get
command:
go get codeberg.org/Developer1214/inmemcache
Usage
First, import the package:
import "codeberg.org/Developer1214/inmemcache"
Here's how you can take advantage of the main features offered by the InMemCache package:
Creating a New Cache Instance
You can create a new cache instance using the New()
function:
cache := inmemcache.New()
Adding a Value to the Cache
To store a value in the cache, use the Set(key, value, ttl, isTracked)
method:
err := cache.Set("key", "value", time.Second*10, true)
if err != nil {
// handle error
}
Setting a value with an empty key will result in an internal error.
Retrieving a Value from the Cache
You can retrieve a value from the cache using the Get(key)
method:
value, expiryTime, err := cache.Get("key")
if err != nil {
// handle error
}
If you attempt to retrieve a value using a key not present in the cache, the method will return nil
, a zero-value time.Time
, and an internal error.
Deleting a Value from the Cache
To delete a value from the cache, use the Delete(key)
method:
err := cache.Delete("key")
if err != nil {
// handle error
}
Attempting to delete a value using a key not present in the cache will result in an internal error.
Error Handling
InMemCache provides detailed error messages in situations such as attempting to delete a non-existing key or setting a key without a value. These error messages include the filename and line number of origin, making debugging easier.
Running Tests
To ensure the reliability and correctness of the InMemCache package, a suite of tests has been provided. To run these tests, follow the steps below:
-
Run the Tests:
Execute the go test
command within the repository directory:
go test
This will run all tests in the package. If you want to run the tests in parallel for faster execution, you can use:
go test -parallel N
Where N
is the number of tests to run concurrently (e.g., -parallel 4
).
go test -race
For test the race condition
-
Viewing Code Coverage:
If you'd like to see the code coverage of the tests, you can generate a coverage report:
go test -coverprofile=coverage.out
go tool cover -html=coverage.out
This will create a coverage report and open it in your default web browser.
License
This project is licensed under the terms of the MIT license. Please see the LICENSE
file for more details.