bestBlockHash and blockHash http handlers

This commit is contained in:
Martin Boehm 2018-01-18 23:05:26 +01:00
parent 5ae73b9bb7
commit a9bfb59103

View File

@ -4,9 +4,11 @@ import (
"blockbook/db" "blockbook/db"
"context" "context"
"encoding/json" "encoding/json"
"fmt"
"log" "log"
"net/http" "net/http"
"os" "os"
"strconv"
"github.com/gorilla/handlers" "github.com/gorilla/handlers"
"github.com/gorilla/mux" "github.com/gorilla/mux"
@ -28,7 +30,9 @@ func New(db *db.RocksDB) (*HttpServer, error) {
r := mux.NewRouter() r := mux.NewRouter()
r.HandleFunc("/", s.Info) r.HandleFunc("/", s.info)
r.HandleFunc("/bestBlockHash", s.bestBlockHash)
r.HandleFunc("/blockHash/{height}", s.blockHash)
var h http.Handler = r var h http.Handler = r
h = handlers.LoggingHandler(os.Stdout, h) h = handlers.LoggingHandler(os.Stdout, h)
@ -37,22 +41,39 @@ func New(db *db.RocksDB) (*HttpServer, error) {
return s, nil return s, nil
} }
// Run starts the server
func (s *HttpServer) Run() error { func (s *HttpServer) Run() error {
log.Printf("http server starting on port %s", s.https.Addr) log.Printf("http server starting on port %s", s.https.Addr)
return s.https.ListenAndServe() return s.https.ListenAndServe()
} }
// Close closes the server
func (s *HttpServer) Close() error { func (s *HttpServer) Close() error {
log.Printf("http server closing") log.Printf("http server closing")
return s.https.Close() return s.https.Close()
} }
// Shutdown shuts down the server
func (s *HttpServer) Shutdown(ctx context.Context) error { func (s *HttpServer) Shutdown(ctx context.Context) error {
log.Printf("http server shutdown") log.Printf("http server shutdown")
return s.https.Shutdown(ctx) return s.https.Shutdown(ctx)
} }
func (s *HttpServer) Info(w http.ResponseWriter, r *http.Request) { func respondError(w http.ResponseWriter, err error, context string) {
w.WriteHeader(http.StatusBadRequest)
log.Printf("http server %s error: %v", context, err)
}
func respondHashData(w http.ResponseWriter, hash string) {
type hashData struct {
Hash string `json:"hash"`
}
json.NewEncoder(w).Encode(hashData{
Hash: hash,
})
}
func (s *HttpServer) info(w http.ResponseWriter, r *http.Request) {
type info struct { type info struct {
Version string `json:"version"` Version string `json:"version"`
} }
@ -60,3 +81,26 @@ func (s *HttpServer) Info(w http.ResponseWriter, r *http.Request) {
Version: "0.0.1", Version: "0.0.1",
}) })
} }
func (s *HttpServer) bestBlockHash(w http.ResponseWriter, r *http.Request) {
hash, err := s.db.GetBestBlockHash()
if err != nil {
respondError(w, err, "bestBlockHash")
return
}
respondHashData(w, hash)
}
func (s *HttpServer) blockHash(w http.ResponseWriter, r *http.Request) {
heightString := mux.Vars(r)["height"]
var hash string
height, err := strconv.ParseUint(heightString, 10, 32)
if err == nil {
hash, err = s.db.GetBlockHash(uint32(height))
}
if err != nil {
respondError(w, err, fmt.Sprintf("blockHash %s", heightString))
} else {
respondHashData(w, hash)
}
}