Best Practices for DB Connections

So I am completely new to GoLang, coming from NodeJS. I currently have an API written in NodeJS using ExpressJS. Just for practice i want to migrate to Golang. I have decided to go with Gin Framework. My database is called KDB which im sure isnt really heard of but we use it at work so i want to practice interfacing Go with it also so i can introduce GO there and get rid of Java.

Im having hard time wrapping my head around opening a connection to db and keeping it open for multiple different calls. Below is what I have now.

main.go

package main

import (
	"example/CC-GO-Server/controllers"
	"example/CC-GO-Server/db"

	"github.com/gin-gonic/gin"
)

func main() {
	db.Conn()
	router := gin.Default()
	router.GET("/linkgroups", controllers.GetLinkgroups)
	router.Run("localhost:8080")
}

db/db.go

package db

import (
	"log"
	"time"

	kdb "github.com/sv/kdbgo"
)

var connectionInstance *kdb.KDBConn

func ConnectDB() *kdb.KDBConn {
	db, err := kdb.DialKDBTimeout("192.168.1.91", 5001, "", time.Second*10)
	if err != nil {
		return &kdb.KDBConn{}
	}
	return db
}

func isConnected() bool {
	res, err := connectionInstance.Call("1+1")
	if err != nil {
		return false
	}
	return res.Data == int64(2)
}

func Conn() *kdb.KDBConn {
	if connectionInstance == nil {
		log.Print("Connecting to DB...")
		connectionInstance = ConnectDB()
	}
	connected := isConnected()
	for connected != true {
		log.Print("Connection to KDB was lost. Waiting 5s...")
		connectionInstance.Close()
		time.Sleep(5 * time.Second)
		log.Print("Reconnecting...")
		connectionInstance = ConnectDB()
		connected = isConnected()
	}

	return connectionInstance
}

controllers/linkgroups.go

package controllers

import (
	"example/CC-GO-Server/models"
	"net/http"

	"github.com/gin-gonic/gin"
)

func GetLinkgroups(c *gin.Context) {
	c.IndentedJSON(http.StatusOK, models.GetAllLinkgroups())
}

models/linkgroup.go

package models

import (
	"example/CC-GO-Server/db"
	"log"
	"time"

	kdb "github.com/sv/kdbgo"
)

type Linkgroup struct {
	ID          string    `json:"id"`
	Dispname    string    `json:"dispname"`
	Order       int       `json:"order"`
	Update_Time time.Time `json:"update_time"`
}

var tablename string = "linkgroups"

func GetAllLinkgroups() []Linkgroup {
	conn := db.Conn()
	res, err := conn.Call("0!" + tablename)
	if err != nil {
		log.Fatal("Error getting all linkgroups", err)
	}
	linkgroups := tableToStruct(res.Data.(kdb.Table))

	return linkgroups

}

func tableToStruct(tbl kdb.Table) []Linkgroup {
	data := []Linkgroup{}
	rowCount := int(tbl.Data[0].Len())
	for i := 0; i < rowCount; i++ {
		var row = Linkgroup{}
		row.ID = tbl.Data[0].Index(i).(string)
		row.Dispname = tbl.Data[1].Index(i).(*kdb.K).String()
                row.Order = tbl.Data[2].Index(i).(int32)
		row.Update_Time = tbl.Data[3].Index(i).(time.Time)
		data = append(data, row)
	}
	return data
}

User on reddit recommended not using packages for each file(models/controllers/db) and to just use main. They also recommended using the DB connection in a struct then make all functions that need DB connection a method of that struct. Problem is I’m completely lost on how to do that. Then how do you manage if the connection is open or not and to reconnect when its not. Any guidance is appreciated

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.