Hi everyone!
I’m new to Golang and trying to learn as I go. I’m stuck at the moment and would love some help to see where I’m going wrong.
I’m trying to implement a simple database call with go functions in my main file. At the moment the functions are returning as undefined, and I’m not sure why.
This is the main file,
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func say(s string) {
for i := 0; i < 3; i++ {
fmt.Println(s)
time.Sleep(time.Millisecond * 100)
}
wg.Done()
}
func main() {
db := &Database{data: map[string]interface{}{
"key0": "value0",
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5",
"key6": "value6",
"key7": "value7",
"key8": "value8",
"key9": "value9",
}}
fmt.Println(db)
go getFromDS(db, "key0")
wg.Add(1)
go getFromDS(db, "key1")
wg.Wait()
fmt.Println(getFromDS)
fmt.Println(v, err, elapsed)
// wg.Add(1)
// go say("Hey")
// wg.Add(1)
// go say("There")
// wg.Wait()
// wg.Add(1)
// go say("Hi")
// wg.Wait()
}
And this is the tree of the files,
.
├── datasource
│ ├── cache.go
│ ├── database.go
│ ├── datasource.go
│ ├── datasource_test.go
│ ├── go.mod
│ ├── go.sum
│ └── greetings.go
├── example_Structure.sql
├── go.mod
├── go.sum
├── greetings
│ ├── go.mod
│ └── greetings.go
├── hello
│ └── go.mod
├── main
├── main.go
├── MakeFile
├── README.md
├── scraps.md
└── util
├── go.mod
└── random.go
the specific module,
package datasource
import (
“fmt”
“time”
"github.com/patrickmn/go-cache"
)
type DataSource interface {
Value(key string) (interface{}, error)
}
// DataSourceStr type, implements the DataSource interface
type DataSourceStr struct {
data map[string]string
}
type cachedClient struct {
c *cache.Cache
}
var c = cache.New(5*time.Minute, 5*time.Minute)
func (n *DataSourceStr) Value(key string) (interface{}, error) {
/*
1. Compute a cache key
2. Search cache key
3. If hit return value
4. If miss, do datasource
5. Cache and return slow thing.
*/
cached, found := c.Get(key)
if found {
return cached, nil
} else if _, ok := n.data[key]; ok {
//measure how often a key gets called.
fmt.Println(cached)
c.Set(key, n.data[key], cache.DefaultExpiration)
return n.data[key], nil
} else {
return nil, fmt.Errorf("key not found %v", ok)
}
}
func getFromDS(datasource DataSource, key string) (string, error) {
v, err := datasource.Value(key)
//create a map that decays based on time.
if err != nil {
return "", nil
}
return fmt.Sprint(v), nil
}
I don’t understand where I have gone wrong!