From d38536d61a7b35d58c1a10494fdc5c6391fcbcaa Mon Sep 17 00:00:00 2001 From: kompotkot Date: Thu, 7 Oct 2021 14:49:19 +0000 Subject: [PATCH] Reuse db connections --- db/server/main.go | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/db/server/main.go b/db/server/main.go index caae18b1..da9e452c 100644 --- a/db/server/main.go +++ b/db/server/main.go @@ -23,6 +23,17 @@ type BlockResponse struct { BlockNumber uint64 `json:"block_number"` } +var dbConnection *gorm.DB + +func InitDB() *gorm.DB { + db, err := gorm.Open(postgres.Open(MOONSTREAM_DB_URI), &gorm.Config{}) + if err != nil { + log.Println("Database unavailable") + return nil + } + return db +} + // Extends handler with allowed CORS policies func setupCorsResponse(w *http.ResponseWriter, req *http.Request) { for _, allowedOrigin := range strings.Split(MOONSTREAM_CORS_ALLOWED_ORIGINS, ",") { @@ -58,14 +69,13 @@ func blockLatest(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json") var latestBlock BlockResponse - db, err := gorm.Open(postgres.Open(MOONSTREAM_DB_URI), &gorm.Config{}) - if err != nil { + + if dbConnection == nil { http.Error(w, http.StatusText(500), 500) return } - query := "SELECT block_number FROM ethereum_blocks ORDER BY block_number DESC LIMIT 1" - db.Raw(query, 1).Scan(&latestBlock.BlockNumber) + dbConnection.Raw(query, 1).Scan(&latestBlock.BlockNumber) json.NewEncoder(w).Encode(latestBlock) } @@ -77,6 +87,8 @@ func main() { flag.StringVar(&listenPort, "port", "8080", "Server listen port") flag.Parse() + dbConnection = InitDB() + address := listenAddr + ":" + listenPort log.Printf("Starting server at %s\n", address)