User Tools

Site Tools


Generic Go database class

gendb.go
package main
 
import (
	"encoding/json"
	"fmt"
)
 
type Results interface {
	Task[Cluster] | Task[Flomaster]  
}
 
type Database[T Results] struct {
	store map[int64][]byte
}
 
func (db *Database[T]) Write(id int64, obj T) {
	jBytes, _ := json.Marshal(obj)
	db.store[id] = jBytes
}
 
func (db *Database[T]) Read(id int64) T {
	var res T
	_ = json.Unmarshal(db.store[id], &res)
	return res
}
 
func NewDatabase[T Results]() *Database[T] {
	return &Database[T]{
		store: make(map[int64][]byte),
	}
}
 
type Task[R any] struct {
	ID     int64 `json:"id"`
	Result R     `json:"result"`
}
 
type Cluster struct {
	ID      int64  `json:"id"`
	Address string `json:"address"`
	Name    string `json:"hostname"`
}
 
type Flomaster struct {
	ID    int64  `json:"id"`
	Color string `json:"color"`
}
 
func main() {
	{
		taskDb := NewDatabase[Task[Cluster]]()
		result := Cluster{
			ID:      45,
			Address: "192.167.56.1",
			Name:    "ccrt",
		}
		task := Task[Cluster]{
			ID:     12,
			Result: result,
		}
		taskDb.Write(task.ID, task)
		task = taskDb.Read(task.ID)
		j, _ := json.Marshal(task)
		fmt.Println(string(j))
	}
 
	{
		taskDb := NewDatabase[Task[Flomaster]]()
		result := Flomaster{
			ID:    78,
			Color: "red",
		}
		task := Task[Flomaster]{
			ID:     15,
			Result: result,
		}
		taskDb.Write(task.ID, task)
		task = taskDb.Read(task.ID)
		j, _ := json.Marshal(task)
		fmt.Println(string(j))
	}
 
}

Out

$ go run gendb.go
{"id":12,"result":{"id":45,"address":"192.167.56.1","hostname":"ccrt"}}
{"id":15,"result":{"id":78,"color":"red"}}