cosmos-sdk/x/auth/client/rest/query.go

69 lines
1.8 KiB
Go
Raw Normal View History

2018-03-10 09:33:05 -08:00
package rest
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/cosmos/cosmos-sdk/client/context"
2018-03-10 09:33:05 -08:00
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/wire"
2018-05-23 19:47:33 -07:00
"github.com/cosmos/cosmos-sdk/x/auth"
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
2018-03-10 09:33:05 -08:00
)
2018-04-18 21:49:24 -07:00
// register REST routes
func RegisterRoutes(ctx context.CoreContext, r *mux.Router, cdc *wire.Codec, storeName string) {
2018-04-18 21:49:24 -07:00
r.HandleFunc(
"/accounts/{address}",
2018-05-23 19:47:33 -07:00
QueryAccountRequestHandlerFn(storeName, cdc, authcmd.GetAccountDecoder(cdc), ctx),
2018-04-18 21:49:24 -07:00
).Methods("GET")
2018-03-10 09:33:05 -08:00
}
2018-04-18 21:49:24 -07:00
// query accountREST Handler
2018-05-23 19:47:33 -07:00
func QueryAccountRequestHandlerFn(storeName string, cdc *wire.Codec, decoder auth.AccountDecoder, ctx context.CoreContext) http.HandlerFunc {
2018-03-10 09:33:05 -08:00
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
bech32addr := vars["address"]
2018-03-14 03:43:31 -07:00
addr, err := sdk.GetAccAddressBech32(bech32addr)
2018-03-10 09:33:05 -08:00
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
res, err := ctx.QueryStore(auth.AddressStoreKey(addr), storeName)
2018-03-10 09:33:05 -08:00
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("couldn't query account. Error: %s", err.Error())))
2018-03-10 09:33:05 -08:00
return
}
// the query will return empty if there is no data for this account
2018-03-14 03:43:31 -07:00
if len(res) == 0 {
2018-03-10 09:33:05 -08:00
w.WriteHeader(http.StatusNoContent)
return
}
2018-03-20 18:27:50 -07:00
// decode the value
2018-04-18 21:49:24 -07:00
account, err := decoder(res)
2018-03-10 09:33:05 -08:00
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("couldn't parse query result. Result: %s. Error: %s", res, err.Error())))
2018-03-10 09:33:05 -08:00
return
}
// print out whole account
2018-04-07 10:56:49 -07:00
output, err := cdc.MarshalJSON(account)
2018-03-10 09:33:05 -08:00
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("couldn't marshall query result. Error: %s", err.Error())))
2018-03-10 09:33:05 -08:00
return
}
w.Write(output)
}
}