Select last block from db with server

pull/292/head
kompotkot 2021-09-27 13:00:45 +00:00
rodzic 98ab736ef4
commit 66a6b0eb63
2 zmienionych plików z 44 dodań i 0 usunięć

Wyświetl plik

@ -1,3 +1,20 @@
module moonstreamdb
go 1.17
require (
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.10.0 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.1.1 // indirect
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
github.com/jackc/pgtype v1.8.1 // indirect
github.com/jackc/pgx/v4 v4.13.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.2 // indirect
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 // indirect
golang.org/x/text v0.3.7 // indirect
gorm.io/driver/postgres v1.1.1 // indirect
gorm.io/gorm v1.21.15 // indirect
)

Wyświetl plik

@ -3,24 +3,51 @@ package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type PingResponse struct {
Status string `json:"status"`
}
type BlockResponse struct {
BlockNumber uint64 `json:"block_number"`
}
func ping(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
response := PingResponse{Status: "ok"}
json.NewEncoder(w).Encode(response)
}
func blockLatest(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
var latestBlock BlockResponse
MOONSTREAM_DB_URI := os.Getenv("MOONSTREAM_DB_URI")
db, err := gorm.Open(postgres.Open(MOONSTREAM_DB_URI), &gorm.Config{})
if err != nil {
log.Print(err)
}
query := "SELECT block_number FROM ethereum_blocks ORDER BY block_number DESC LIMIT 1"
db.Raw(query, 1).Scan(&latestBlock.BlockNumber)
json.NewEncoder(w).Encode(latestBlock)
}
func main() {
address := "0.0.0.0:8931"
fmt.Printf("Starting server at %s\n", address)
http.HandleFunc("/ping", ping)
http.HandleFunc("/block/latest", blockLatest)
http.ListenAndServe(address, nil)
}