netmaker/logic/pro/netcache/netcache.go
kayos@tcp.direct e878e4820a
Fixes+Chores: avoid de-referencing nil ptrs + lint
- Avoid referencing conditions we know are false/true

 - Avoid using name of imported package as variable

 - Avoid broken (see list item 1) if else statement in `ipservice.go` by refactoring to switch statement

 - When assigning a pointer value to a variable along with an error, check that error before referencing that pointer. Thus avoiding de-referencing a nil and causing a panic.
  *** This item is the most important ***

 - Standard gofmt package sorting + linting; This includes fixing comment starts for go doc

 - Explicit non-handling of unhandled errors where appropriate (assigning errs to _ to reduce linter screaming)

 - Export ErrExpired in `netcache` package so that we can properly reference it using `errors.Is` instead of using `strings.Contains` against an `error.Error()` value
2022-12-06 20:11:20 -08:00

58 lines
1.2 KiB
Go

package netcache
import (
"encoding/json"
"fmt"
"time"
"github.com/gravitl/netmaker/database"
)
const (
expirationTime = time.Minute * 5
)
// CValue - the cache object for a network
type CValue struct {
Network string `json:"network"`
Value string `json:"value"`
Pass string `json:"pass"`
User string `json:"user"`
Expiration time.Time `json:"expiration"`
}
var ErrExpired = fmt.Errorf("expired")
// Set - sets a value to a key in db
func Set(k string, newValue *CValue) error {
newValue.Expiration = time.Now().Add(expirationTime)
newData, err := json.Marshal(newValue)
if err != nil {
return err
}
return database.Insert(k, string(newData), database.CACHE_TABLE_NAME)
}
// Get - gets a value from db, if expired, return err
func Get(k string) (*CValue, error) {
record, err := database.FetchRecord(database.CACHE_TABLE_NAME, k)
if err != nil {
return nil, err
}
var entry CValue
if err := json.Unmarshal([]byte(record), &entry); err != nil {
return nil, err
}
if time.Now().After(entry.Expiration) {
return nil, ErrExpired
}
return &entry, nil
}
// Del - deletes a value from db
func Del(k string) error {
return database.DeleteRecord(database.CACHE_TABLE_NAME, k)
}