kopia lustrzana https://github.com/bugout-dev/moonstream
Reuse db connections
rodzic
1fdbdc5f1b
commit
d38536d61a
|
@ -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)
|
||||
|
||||
|
|
Ładowanie…
Reference in New Issue