Add mechanism for initializing database with produce
This commit is contained in:
BIN
Binary file not shown.
+4
-3
@@ -6,9 +6,10 @@ import (
|
||||
)
|
||||
|
||||
type config struct {
|
||||
Env string `default:"dev"`
|
||||
APIPort int `default:3000`
|
||||
LogLevel string `default:"debug"`
|
||||
Env string `default:"dev"`
|
||||
APIPort int `default:3000`
|
||||
LogLevel string `default:"debug"`
|
||||
DMLInitFile string
|
||||
}
|
||||
|
||||
func load() (cfg config, err error) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
ENV: dev
|
||||
APIPORT: 3000
|
||||
LOGLEVEL: debug
|
||||
DMLINITFILE: defaultproduce.json
|
||||
|
||||
@@ -2,6 +2,8 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
@@ -43,6 +45,7 @@ func main() {
|
||||
}
|
||||
|
||||
produceSvc := produce.NewService(db.From("produce"))
|
||||
initProduce(produceSvc)
|
||||
|
||||
server := http.NewServer(cfg.APIPort, logger, cfg.Env, produceSvc)
|
||||
|
||||
@@ -70,3 +73,31 @@ func main() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func initProduce(produceSvc http.ProduceService) {
|
||||
if cfg.DMLInitFile == "" {
|
||||
logger.Info("no init file provided, database will be empty")
|
||||
return
|
||||
}
|
||||
|
||||
f, err := os.Open(cfg.DMLInitFile)
|
||||
if err != nil {
|
||||
logger.Fatalf("could not open file: %s", cfg.DMLInitFile)
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(f)
|
||||
if err != nil {
|
||||
logger.Fatal("could not read file: %s", cfg.DMLInitFile)
|
||||
}
|
||||
|
||||
var items []produce.Item
|
||||
err = json.Unmarshal(b, &items)
|
||||
if err != nil {
|
||||
logger.Fatalf("could not unmarshal items: %v", err)
|
||||
}
|
||||
|
||||
err = produceSvc.Add(items)
|
||||
if err != nil {
|
||||
logger.Fatal("failed to add items to produce service")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user