kaspad/apiserver/server/routes.go
Ori Newman ae25ec2e6b [NOD-303] Implement get transaction by id for api server (#391)
* [NOD-303] Implement get transaction by id for api server

* [NOD-303] Make routeParamTxID a constant

* [NOD-303] Change database is not current error.

* [NOD-303] Add ID to TransactionInput and TransactionOutput models

* [NOD-303] Change transactions_outputs table name to transaction_outputs and transactions_inputs to transaction_inputs

* [NOD-303] Add json annotations to transaction response types

* [NOD-303] Split server package

* [NOD-303] Add GetTransactionByHashHandler

* [NOD-303] Add comments to exported functions and variables

* [NOD-303] Put response types in a separate file

* [NOD-303] Rename functions
2019-09-03 15:54:59 +03:00

68 lines
1.8 KiB
Go

package server
import (
"encoding/json"
"fmt"
"github.com/daglabs/btcd/apiserver/controllers"
"github.com/daglabs/btcd/apiserver/utils"
"github.com/gorilla/mux"
"net/http"
)
const (
routeParamTxID = "txID"
routeParamTxHash = "txHash"
)
func makeHandler(handler func(vars map[string]string, ctx *utils.APIServerContext) (interface{}, *utils.HandlerError)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
ctx := utils.ToAPIServerContext(r.Context())
response, hErr := handler(mux.Vars(r), ctx)
if hErr != nil {
sendErr(ctx, w, hErr)
return
}
sendJSONResponse(w, response)
}
}
func sendErr(ctx *utils.APIServerContext, w http.ResponseWriter, hErr *utils.HandlerError) {
errMsg := fmt.Sprintf("got error: %s", hErr)
ctx.Warnf(errMsg)
w.WriteHeader(hErr.ErrorCode)
sendJSONResponse(w, hErr)
}
func sendJSONResponse(w http.ResponseWriter, response interface{}) {
b, err := json.Marshal(response)
if err != nil {
panic(err)
}
_, err = fmt.Fprintf(w, string(b))
if err != nil {
panic(err)
}
}
func mainHandler(_ map[string]string, _ *utils.APIServerContext) (interface{}, *utils.HandlerError) {
return "API server is running", nil
}
func addRoutes(router *mux.Router) {
router.HandleFunc("/", makeHandler(mainHandler))
router.HandleFunc(
fmt.Sprintf("/transaction/id/{%s}", routeParamTxID),
makeHandler(func(vars map[string]string, ctx *utils.APIServerContext) (interface{}, *utils.HandlerError) {
return controllers.GetTransactionByIDHandler(vars[routeParamTxID])
})).
Methods("GET")
router.HandleFunc(
fmt.Sprintf("/transaction/hash/{%s}", routeParamTxHash),
makeHandler(func(vars map[string]string, ctx *utils.APIServerContext) (interface{}, *utils.HandlerError) {
return controllers.GetTransactionByHashHandler(vars[routeParamTxHash])
})).
Methods("GET")
}