简体   繁体   中英

how to close database connection without terminating the server connection in golang

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

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)}

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM