-1

Is there any way to close the database connection without terminating the HTTP server?

my code:

func thisone(w http.ResponseWriter,r *http.Request){
    /*connect the db*/
    defer database.Close()
    /*query the database*/
}

func main(){
  http.HandleFunc("/route",thisone)
  http.ListenAndServe(":8000",nil)
}

what this does is after querying the database it terminates the program and stopped listening to the port but I want to keep listening to the port even after the database connection is close. so is there any way to do that

Thank You

THE CODER
  • 1
  • 1
  • 1
    Don't close the DB. It is designed to be reused and used concurrently and safely across requests. Go's SQL package comes with lots of optimizations like connection pooling. So, initialized the DB connection in your "server" struct - and have all http handlers (struct methods) that need this, use this common DB. That way they don't need to establish their own DB for every request. – colm.anseo Apr 25 '21 at 18:23
  • 2
    Which database client are you using? It's strange for a database client to terminate the program on connection close. – Charlie Tumahai Apr 25 '21 at 18:31
  • FYI: This blog has many best practices for writing a web service: https://pace.dev/blog/2018/05/09/how-I-write-http-services-after-eight-years.html – colm.anseo Apr 25 '21 at 19:30
  • @colm.anseo thanks for your time, I will check it out :) – THE CODER Apr 26 '21 at 18:41

2 Answers2

-2

Every time you are querying the database you are calling thisone() and every time that function is executed is closing the database connection. Try to put database.Close() inside main function.

func main(){
    defer database.Close()

    http.HandleFunc("/route",thisone)
    http.ListenAndServe(":8000",nil)}
  • Hey, Enrique Thanks for your time for answering, I have one doubt if I declare defer database.Close() in the main function then I should define the database connection in the main right? otherwise, it gonna throw me an error. But I have a post request in that function (thisone()) and the request body is gonna query the database. after the query, I need to close the database connection and listen to the port, But in my case, it is terminating the program. Do you have any other ideas? – THE CODER Apr 26 '21 at 07:01
-2

That's a little weird that you have an error putting up database.Close() in the main function because I recently made an API Rest with Go a little similar. You can see the code here.I hope it is useful.

Github API Rest with Go

enter image description here