Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
github.com/philippgille/gokv
Simple key-value store abstraction and implementations for Go
Note: The interface is not final yet! See Project status for details.
type Store interface {
Set(k string, v any) error
Get(k string, v any) (found bool, err error)
Delete(k string) error
Close() error
}
There are detailed descriptions of the methods in the docs and in the code. You should read them if you plan to write your own gokv.Store
implementation or if you create a Go package with a method that takes a gokv.Store
as parameter, so you know exactly what happens in the background.
Some of the following databases aren't specifically engineered for storing key-value pairs, but if someone's running them already for other purposes and doesn't want to set up one of the proper key-value stores due to administrative overhead etc., they can of course be used as well. In those cases let's focus on a few of the most popular though. This mostly goes for the SQL, NoSQL and NewSQL categories.
Feel free to suggest more stores by creating an issue or even add an actual implementation - .
For differences between the implementations, see Choosing an implementation.
For the Godoc of specific implementations, see https://pkg.go.dev/github.com/philippgille/gokv#section-directories.
noop
does nothing except validate the inputs, if applicable.Again:
For differences between the implementations, see Choosing an implementation.
For the Godoc of specific implementations, see https://pkg.go.dev/github.com/philippgille/gokv#section-directories.
Most Go packages for key-value stores just accept a []byte
as value, which requires developers for example to marshal (and later unmarshal) their structs. gokv
is meant to be simple and make developers' lifes easier, so it accepts any type (with using any
/interface{}
as parameter), including structs, and automatically (un-)marshals the value.
The kind of (un-)marshalling is left to the implementation. All implementations in this repository currently support JSON and gob by using the encoding
subpackage in this repository, which wraps the core functionality of the standard library's encoding/json
and encoding/gob
packages. See Marshal formats for details.
For unexported struct fields to be (un-)marshalled to/from JSON/gob, the respective custom (un-)marshalling methods need to be implemented as methods of the struct (e.g. MarshalJSON() ([]byte, error)
for custom marshalling into JSON). See Marshaler and Unmarshaler for JSON, and GobEncoder and GobDecoder for gob.
To improve performance you can also implement the custom (un-)marshalling methods so that no reflection is used by the encoding/json
/ encoding/gob
packages. This is not a disadvantage of using a generic key-value store package, it's the same as if you would use a concrete key-value store package which only accepts []byte
, requiring you to (un-)marshal your structs.
This repository contains the subpackage encoding
, which is an abstraction and wrapper for the core functionality of packages like encoding/json
and encoding/gob
. The currently supported marshal formats are:
More formats will be supported in the future (e.g. XML).
The stores use this encoding
package to marshal and unmarshal the values when storing / retrieving them. The default format is JSON, but all gokv.Store
implementations in this repository also support gob as alternative, configurable via their Options
.
The marshal format is up to the implementations though, so package creators using the gokv.Store
interface as parameter of a function should not make any assumptions about this. If they require any specific format they should inform the package user about this in the GoDoc of the function taking the store interface as parameter.
Differences between the formats:
gokv
storagescombiner
package that allows you to create a gokv.Store
which forwards its call to multiple implementations at the same time. So for example you can use memcached
and s3
simultaneously to have 1) super fast access but also 2) durable redundant persistent storage.redis.Options
struct in github.com/philippgille/gokv
, but instead the redis.Options
struct in github.com/go-redis/redis
)
gokv
when switching the underlying used Go package, but definitely useful for some peoplegokv
to SimpleKV
?github.com/philippgille/gokv/store/redis
?First, download the module you want to work with:
gokv.Store
interface:
go get github.com/philippgille/gokv@latest
go get github.com/philippgille/gokv/redis@latest
Then you can import and use it.
Every implementation has its own Options
struct, but all implementations have a NewStore()
/ NewClient()
function that returns an object of a sctruct that implements the gokv.Store
interface. Let's take the implementation for Redis as example, which is the most popular distributed key-value store.
package main
import (
"fmt"
"github.com/philippgille/gokv"
"github.com/philippgille/gokv/redis"
)
type foo struct {
Bar string
}
func main() {
options := redis.DefaultOptions // Address: "localhost:6379", Password: "", DB: 0
// Create client
client, err := redis.NewClient(options)
if err != nil {
panic(err)
}
defer client.Close()
// Store, retrieve, print and delete a value
interactWithStore(client)
}
// interactWithStore stores, retrieves, prints and deletes a value.
// It's completely independent of the store implementation.
func interactWithStore(store gokv.Store) {
// Store value
val := foo{
Bar: "baz",
}
err := store.Set("foo123", val)
if err != nil {
panic(err)
}
// Retrieve value
retrievedVal := new(foo)
found, err := store.Get("foo123", retrievedVal)
if err != nil {
panic(err)
}
if !found {
panic("Value not found")
}
fmt.Printf("foo: %+v", *retrievedVal) // Prints `foo: {Bar:baz}`
// Delete value
err = store.Delete("foo123")
if err != nil {
panic(err)
}
}
As described in the comments, that code does the following:
Close()
because you don't know which implementation is passed. Even if you work with a specific implementation you should always call Close()
, so you can easily change the implementation without the risk of forgetting to add the call.interactWithStore()
, which requires a gokv.Store
as parameter. This method then:
foo
in the Redis server running on localhost:6379
with the key foo123
foo123
foo: {Bar:baz}
, which is exactly what was stored before.Now let's say you don't want to use Redis but Consul instead. You just have to make three simple changes:
"github.com/philippgille/gokv/redis"
by "github.com/philippgille/gokv/consul"
redis.DefaultOptions
by consul.DefaultOptions
redis.NewClient(options)
by consul.NewClient(options)
Everything else works the same way. interactWithStore()
is completely unaffected.
See the examples directory for more code examples.
Note:
gokv
's API is not stable yet and is under active development. Upcoming releases are likely to contain breaking changes as long as the version isv0.x.y
. You should use vendoring to prevent bad surprises. This project adheres to Semantic Versioning and all notable changes to this project are documented in CHANGELOG.md.
Planned interface methods until v1.0.0
:
List(any) error
/ GetAll(any) error
or similarThe interface might even change until v1.0.0
. For example one consideration is to change Get(string, any) (bool, error)
to Get(string, any) error
(no boolean return value anymore), with the error
being something like gokv.ErrNotFound // "Key-value pair not found"
to fulfill the additional role of indicating that the key-value pair wasn't found. But at the moment we prefer the current method signature.
Also, more interfaces might be added. For example so that there's a SimpleStore
and an AdvancedStore
, with the first one containing only the basic methods and the latter one with advanced features such as key-value pair lifetimes (deletion of key-value pairs after a given time), notification of value changes via Go channels etc. But currently the focus is simplicity, see Design decisions.
When creating a package you want the package to be usable by as many developers as possible. Let's look at a specific example: You want to create a paywall middleware for the Gin web framework. You need some database to store state. You can't use a Go map, because its data is not persisted across web service restarts. You can't use an embedded DB like bbolt, BadgerDB or SQLite, because that would restrict the web service to one instance, but nowadays every web service is designed with high horizontal scalability in mind. If you use Redis, MongoDB or PostgreSQL though, you would force the package user (the developer who creates the actual web service with Gin and your middleware) to run and administrate the server, even if she might never have used it before and doesn't know how to configure them for high performance and security.
Any decision for a specific database would limit the package's usability.
One solution would be a custom interface where you would leave the implementation to the package user. But that would require the developer to dive into the details of the Go package of the chosen key-value store. And if the developer wants to switch the store, or maybe use one for local testing and another for production, she would need to write multiple implementations.
gokv
is the solution for these problems. Package creators use the gokv.Store
interface as parameter and can call its methods within their code, leaving the decision which actual store to use to the package user. Package users pick one of the implementations, for example github.com/philippgille/gokv/redis
for Redis and pass the redis.Client
created by redis.NewClient(...)
as parameter. Package users can also develop their own implementations if they need to.
gokv
doesn't just have to be used to satisfy some gokv.Store
parameter. It can of course also be used by application / web service developers who just don't want to dive into the sometimes complicated usage of some key-value store packages.
Initially it was developed as storage
package within the project ln-paywall to provide the users of ln-paywall with multiple storage options, but at some point it made sense to turn it into a repository of its own.
Before doing so I examined existing Go packages with a similar purpose (see Related projects), but none of them fit my needs. They either had too few implementations, or they didn't automatically marshal / unmarshal passed structs, or the interface had too many methods, making the project seem too complex to maintain and extend, proven by some that were abandoned or forked (splitting the community with it).
gokv
is primarily an abstraction for key-value stores, not caches, so there's no need for cache eviction and timeouts.
Option
that configures the key-value store client to set a timeout on some key-value pair when storing it in the server. But this should be implementation-specific and not be part of the interface methods, which would require every implementation to support cache eviction.MarshalJSON()
/ GobEncode()
and UnmarshalJSON()
/ GobDecode()
first. It's still possible to implement these methods to customize the (un-)marshalling, for example to include unexported fields, or for higher performance (because the encoding/json
/ encoding/gob
package doesn't have to use reflection).gokv.Store
interface as parameter can do everything that's usually required when working with a key-value store. For example, a boolean return value for the Delete
method that indicates whether a value was actually deleted (because it was previously present) can be useful, but isn't a must-have, and also it would require some Store
implementations to implement the check by themselves (because the existing libraries don't support it), which would unnecessarily decrease performance for those who don't need it. Or as another example, a Watch(key string) (<-chan Notification, error)
method that sends notifications via a Go channel when the value of a given key changes is nice to have for a few use cases, but in most cases it's not required.
Note: In the future we might add another interface, so that there's one for the basic operations and one for advanced uses.
boltdb.BoltDB
, but this leads to so called "stuttering" that's discouraged when writing idiomatic Go. That's why gokv
uses for example bbolt.Store
and syncmap.Store
. For easier differentiation between embedded DBs and DBs that have a client and a server component though, the first ones are called Store
and the latter ones are called Client
, for example redis.Client
.gokv.StoreError
type and define some constants like a SetError
or something more specific like a TimeoutError
, but non-specific errors don't help the package user, and specific errors would make it very hard to create and especially maintain a gokv.Store
implementation. You would need to know exactly in which cases the package (that the implementation uses) returns errors, what the errors mean (to "translate" them) and keep up with changes and additions of errors in the package. So instead, errors are just forwarded. For example, if you use the dynamodb
package, the returned errors will be errors from the "github.com/aws/aws-sdk-go
package.Path
and another Directory
, then how should be name the option for the database directory? Maybe Folder
, to add to the confusion? Also, some users might already have used the packages we use directly and they would wonder about the "new" variable name which has the same meaning.gokv.Store
implementations, so most user won't even notice the differences in variable names.gokv
implementation is a Go module. This differs from repositories that contain a single Go module with many subpackages, but has the huge advantage that if you only want to work with the Redis client for example, the go get
will only fetch the Redis dependencies and not the huge amount of dependencies that are used across the whole repository.[]byte
as value, no automatic (un-)marshalling of structs[]byte
as value, no automatic (un-)marshalling of structsjson.Marshaler
/ json.Unmarshaler
as parameter, so you always need to explicitly implement their methods for your structs, and also you can't use gob or other formats for (un-)marshaling.Others:
Delete()
method, no Redis, embedded DBs etc., no Git tags / releases, no stars (as of 2018-11-28)Codec
.gokv
is licensed under the Mozilla Public License Version 2.0.
Dependencies might be licensed under other licenses.
FAQs
Unknown package
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.