nuclei/pkg/utils/storage/storage.go

62 lines
1.1 KiB
Go
Raw Normal View History

2024-03-01 02:11:18 +01:00
package storage
import (
"fmt"
2024-03-01 02:11:18 +01:00
"os"
"github.com/cespare/xxhash/v2"
2024-03-01 02:11:18 +01:00
"github.com/projectdiscovery/utils/conversion"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/opt"
)
type Storage struct {
dbPath string
storage *leveldb.DB
}
func New() (*Storage, error) {
storage := &Storage{}
dbPath, err := os.MkdirTemp("", "nuclei-storage-*")
storage.dbPath = dbPath
if err != nil {
return nil, err
}
storage.storage, err = leveldb.OpenFile(dbPath, &opt.Options{})
if err != nil {
return nil, err
}
return storage, nil
}
func (s *Storage) Close() {
s.storage.Close()
os.RemoveAll(s.dbPath)
}
func HashString(v string) uint64 {
return Hash(conversion.Bytes(v))
2024-03-01 02:11:18 +01:00
}
func Hash(v []byte) uint64 {
return xxhash.Sum64(v)
2024-03-01 02:11:18 +01:00
}
func (s *Storage) Get(k uint64) (string, error) {
v, err := s.storage.Get(conversion.Bytes(fmt.Sprint(k)), nil)
2024-03-01 02:11:18 +01:00
return conversion.String(v), err
}
func (s *Storage) SetString(v string) (uint64, error) {
2024-03-01 02:11:18 +01:00
return s.Set(conversion.Bytes(v))
}
func (s *Storage) Set(v []byte) (uint64, error) {
2024-03-01 02:11:18 +01:00
hash := Hash(v)
return hash, s.storage.Put(conversion.Bytes(fmt.Sprint(hash)), v, nil)
2024-03-01 02:11:18 +01:00
}