what is the best practice when we are using database\sql package for sql.Open and db.close(). I have scenario where i have to multiple function and each function is responsible to hit the database and fetch the data. In this case do we need write sql.open() and db.close() in each of those functions.
Please find the three file and rough layout of my code. If I’m using this approach. what would be the best possible way to follow with best practices.
-
main.go
func main() {
router := mux.NewRouter()
controller := controllers.Controller{}router.HandleFunc("/protectedEndpoint", controller.GetStudents).Methods(“GET”)
router.HandleFunc("/signup", controller.GetBook).Methods(“GET”)
router.HandleFunc("/login", controller.GetReports).Methods(“GET”)
} - controller.go
func GetStudents(w http.ResponseWriter, r *http.request){
//fetch request param and call the repository method to fetch data from db
studentId := r.URL.Query().get("id)
repository.GetStudents(studentId)
}
func GetBook(w http.ResponseWriter, r *http.request){
//fetch request param and call the repository method to fetch data from db
bookId := r.URL.Query().get("id)
repository.GetBook(bookId)
}
func GetReports(w http.ResponseWriter, r *http.request){
//fetch request param and call the repository method to fetch data from db
studentId := r.URL.Query().get("id)
repository.GetReports(studentId)
}
- repository.go
import database/sql
func GetStudents(studentId int){
db, err := sql.open( driverName, connectionString)
if err != nil {
log.panic(err)
}
defer db.close()
row, err := db.query(“select * from student where studentId = :0”, studentId)
if err != nil {
log.panic(err)
}
defer row.close()
//iterate through the row
}
func GetBook(bookId int){
db, err := sql.open( driverName, connectionString)
if err != nil {
log.panic(err)
}
defer db.close()
row, err := db.query(“select * from book where bookId = :0”, bookId)
if err != nil {
log.panic(err)
}
defer row.close()
//iterate through the row
}
func GetReports(studentId int){
db, err := sql.open( driverName, connectionString)
if err != nil {
log.panic(err)
}
defer db.close()
row, err := db.query(“select * from reports where studentId = :0”, studentId)
if err != nil {
log.panic(err)
}
defer row.close()
//iterate through the row
}