Reuse db connections

pull/308/head
kompotkot 2021-10-07 14:49:19 +00:00
rodzic 1fdbdc5f1b
commit d38536d61a
1 zmienionych plików z 16 dodań i 4 usunięć

Wyświetl plik

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