Hey there, I got a doubt about database conection in a web application. Do I need to stablish one connection per request, or I can use the same database link to all the requests? Example below;
The db var below is declared global. Can I use this variable inside all functions and to all requests?
func login(w http.ResponseWriter, r *http.Request) {
if !RestVerificaChave(r.URL.Query().Get("chave")) {
fmt.Fprintf(w, "-1")
return
}
fmt.Fprintf(w, "TESTE PAGINA WEB LOGIN EM GO-LANG")
}
func teste(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "TESTE PAGINA WEB TESTE EM GO-LANG")
}
func main() {
// carrega configuracoes iniciais e conecta no banco ---------------------------
LoadConfig()
db = ConectaBanco()
// carrega configuracoes iniciais e conecta no banco ---------------------------
//chamada para os métodos ------------------------------------------------------
http.HandleFunc(URLRaiz+"login/", login)
http.HandleFunc(URLRaiz+"teste/", teste)
//chamada para os métodos ------------------------------------------------------
http.ListenAndServe(":81", nil)
}
Or for example, I gotta do like;
func login(w http.ResponseWriter, r *http.Request) {
if !RestVerificaChave(r.URL.Query().Get("chave")) {
fmt.Fprintf(w, "-1")
return
}
//connection here inside the request
db = ConectaBanco()
fmt.Fprintf(w, "TESTE PAGINA WEB LOGIN EM GO-LANG")
}
func teste(w http.ResponseWriter, r *http.Request) {
//connection here inside the request
db = ConectaBanco()
fmt.Fprintf(w, "TESTE PAGINA WEB TESTE EM GO-LANG")
}
func main() {
LoadConfig()
//chamada para os métodos ------------------------------------------------------
http.HandleFunc(URLRaiz+"login/", login)
http.HandleFunc(URLRaiz+"teste/", teste)
//chamada para os métodos ------------------------------------------------------
http.ListenAndServe(":81", nil)
}
Thanks.