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

68 lines
1.6 KiB
Go
Raw Normal View History

2018-03-10 09:33:05 -08:00
package rest
import (
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/cosmos/cosmos-sdk/client/core"
2018-03-10 09:33:05 -08:00
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/wire"
)
type commander struct {
storeName string
cdc *wire.Codec
2018-03-27 12:46:06 -07:00
decoder sdk.AccountDecoder
2018-03-10 09:33:05 -08:00
}
2018-03-20 18:27:50 -07:00
func QueryAccountRequestHandler(storeName string, cdc *wire.Codec, decoder sdk.AccountDecoder) func(http.ResponseWriter, *http.Request) {
c := commander{storeName, cdc, decoder}
2018-03-10 09:33:05 -08:00
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
addr := vars["address"]
2018-03-14 03:43:31 -07:00
2018-03-10 09:33:05 -08:00
bz, err := hex.DecodeString(addr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
key := sdk.Address(bz)
2018-03-30 05:57:53 -07:00
res, err := core.NewCoreContextFromViper().Query(key, c.storeName)
2018-03-10 09:33:05 -08:00
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("Could't query account. Error: %s", err.Error())))
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
account, err := c.decoder(res)
2018-03-10 09:33:05 -08:00
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("Could't parse query result. Result: %s. Error: %s", res, err.Error())))
return
}
// print out whole account
output, err := json.MarshalIndent(account, "", " ")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("Could't marshall query result. Error: %s", err.Error())))
return
}
w.Write(output)
}
}