Add post respones process to add json to header and decide whether bring in indent to make response more readable

This commit is contained in:
HaoyangLiu 2018-10-02 23:15:04 +08:00
parent 5fb7e65079
commit 5d259b1b39
14 changed files with 97 additions and 88 deletions

View File

@ -35,6 +35,7 @@ const (
FlagPrintResponse = "print-response" FlagPrintResponse = "print-response"
FlagDryRun = "dry-run" FlagDryRun = "dry-run"
FlagGenerateOnly = "generate-only" FlagGenerateOnly = "generate-only"
FlagIndentResponse= "indent"
) )
// LineBreak can be included in a command list to provide a blank line // LineBreak can be included in a command list to provide a blank line
@ -47,12 +48,13 @@ var (
// GetCommands adds common flags to query commands // GetCommands adds common flags to query commands
func GetCommands(cmds ...*cobra.Command) []*cobra.Command { func GetCommands(cmds ...*cobra.Command) []*cobra.Command {
for _, c := range cmds { for _, c := range cmds {
c.Flags().Bool(FlagIndentResponse, false, "Add indent to JSON response")
c.Flags().Bool(FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)") c.Flags().Bool(FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)")
c.Flags().Bool(FlagUseLedger, false, "Use a connected Ledger device") c.Flags().Bool(FlagUseLedger, false, "Use a connected Ledger device")
c.Flags().String(FlagChainID, "", "Chain ID of tendermint node") c.Flags().String(FlagChainID, "", "Chain ID of tendermint node")
c.Flags().String(FlagNode, "tcp://localhost:26657", "<host>:<port> to tendermint rpc interface for this chain") c.Flags().String(FlagNode, "tcp://localhost:26657", "<host>:<port> to tendermint rpc interface for this chain")
c.Flags().Int64(FlagHeight, 0, "block height to query, omit to get most recent provable block") c.Flags().Int64(FlagHeight, 0, "block height to query, omit to get most recent provable block")
viper.BindPFlag(FlagTrustNode, c.Flags().Lookup(FlagTrustNode)) //viper.BindPFlag(FlagTrustNode, c.Flags().Lookup(FlagTrustNode))
viper.BindPFlag(FlagUseLedger, c.Flags().Lookup(FlagUseLedger)) viper.BindPFlag(FlagUseLedger, c.Flags().Lookup(FlagUseLedger))
viper.BindPFlag(FlagChainID, c.Flags().Lookup(FlagChainID)) viper.BindPFlag(FlagChainID, c.Flags().Lookup(FlagChainID))
viper.BindPFlag(FlagNode, c.Flags().Lookup(FlagNode)) viper.BindPFlag(FlagNode, c.Flags().Lookup(FlagNode))
@ -63,6 +65,7 @@ func GetCommands(cmds ...*cobra.Command) []*cobra.Command {
// PostCommands adds common flags for commands to post tx // PostCommands adds common flags for commands to post tx
func PostCommands(cmds ...*cobra.Command) []*cobra.Command { func PostCommands(cmds ...*cobra.Command) []*cobra.Command {
for _, c := range cmds { for _, c := range cmds {
c.Flags().Bool(FlagIndentResponse, false, "Add indent to JSON response")
c.Flags().String(FlagFrom, "", "Name or address of private key with which to sign") c.Flags().String(FlagFrom, "", "Name or address of private key with which to sign")
c.Flags().Int64(FlagAccountNumber, 0, "AccountNumber number to sign the tx") c.Flags().Int64(FlagAccountNumber, 0, "AccountNumber number to sign the tx")
c.Flags().Int64(FlagSequence, 0, "Sequence number to sign the tx") c.Flags().Int64(FlagSequence, 0, "Sequence number to sign the tx")
@ -81,7 +84,7 @@ func PostCommands(cmds ...*cobra.Command) []*cobra.Command {
// --gas can accept integers and "simulate" // --gas can accept integers and "simulate"
c.Flags().Var(&GasFlagVar, "gas", fmt.Sprintf( c.Flags().Var(&GasFlagVar, "gas", fmt.Sprintf(
"gas limit to set per-transaction; set to %q to calculate required gas automatically (default %d)", GasFlagSimulate, DefaultGasLimit)) "gas limit to set per-transaction; set to %q to calculate required gas automatically (default %d)", GasFlagSimulate, DefaultGasLimit))
viper.BindPFlag(FlagTrustNode, c.Flags().Lookup(FlagTrustNode)) //viper.BindPFlag(FlagTrustNode, c.Flags().Lookup(FlagTrustNode))
viper.BindPFlag(FlagUseLedger, c.Flags().Lookup(FlagUseLedger)) viper.BindPFlag(FlagUseLedger, c.Flags().Lookup(FlagUseLedger))
viper.BindPFlag(FlagChainID, c.Flags().Lookup(FlagChainID)) viper.BindPFlag(FlagChainID, c.Flags().Lookup(FlagChainID))
viper.BindPFlag(FlagNode, c.Flags().Lookup(FlagNode)) viper.BindPFlag(FlagNode, c.Flags().Lookup(FlagNode))

View File

@ -123,6 +123,7 @@ func ServeCommand(cdc *codec.Codec) *cobra.Command {
cmd.Flags().String(client.FlagNode, "tcp://localhost:26657", "Address of the node to connect to") cmd.Flags().String(client.FlagNode, "tcp://localhost:26657", "Address of the node to connect to")
cmd.Flags().Int(flagMaxOpenConnections, 1000, "The number of maximum open connections") cmd.Flags().Int(flagMaxOpenConnections, 1000, "The number of maximum open connections")
cmd.Flags().Bool(client.FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)") cmd.Flags().Bool(client.FlagTrustNode, false, "Trust connected full node (don't verify proofs for responses)")
cmd.Flags().Bool(client.FlagIndentResponse, false, "Add indent to JSON response")
viper.BindPFlag(client.FlagTrustNode, cmd.Flags().Lookup(client.FlagTrustNode)) viper.BindPFlag(client.FlagTrustNode, cmd.Flags().Lookup(client.FlagTrustNode))
viper.BindPFlag(client.FlagChainID, cmd.Flags().Lookup(client.FlagChainID)) viper.BindPFlag(client.FlagChainID, cmd.Flags().Lookup(client.FlagChainID))
viper.BindPFlag(client.FlagNode, cmd.Flags().Lookup(client.FlagNode)) viper.BindPFlag(client.FlagNode, cmd.Flags().Lookup(client.FlagNode))

View File

@ -12,6 +12,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
tmliteProxy "github.com/tendermint/tendermint/lite/proxy" tmliteProxy "github.com/tendermint/tendermint/lite/proxy"
"github.com/cosmos/cosmos-sdk/client/utils"
) )
//BlockCommand returns the verified block data for a given heights //BlockCommand returns the verified block data for a given heights
@ -62,13 +63,12 @@ func getBlock(cliCtx context.CLIContext, height *int64) ([]byte, error) {
} }
} }
// TODO move maarshalling into cmd/rest functions indent := viper.GetBool(client.FlagIndentResponse)
// output, err := tmcodec.MarshalJSON(res) if indent {
output, err := cdc.MarshalJSONIndent(res, "", " ") return cdc.MarshalJSONIndent(res, "", " ")
if err != nil { } else {
return nil, err return cdc.MarshalJSON(res)
} }
return output, nil
} }
// get the current blockchain height // get the current blockchain height
@ -133,8 +133,7 @@ func BlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
w.Write([]byte(err.Error())) w.Write([]byte(err.Error()))
return return
} }
w.Header().Set("Content-Type", "application/json") utils.PostProcessResponse(w, cdc, output)
w.Write(output)
} }
} }
@ -153,7 +152,6 @@ func LatestBlockRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
w.Write([]byte(err.Error())) w.Write([]byte(err.Error()))
return return
} }
w.Header().Set("Content-Type", "application/json") utils.PostProcessResponse(w, cdc, output)
w.Write(output)
} }
} }

View File

@ -11,6 +11,7 @@ import (
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
ctypes "github.com/tendermint/tendermint/rpc/core/types" ctypes "github.com/tendermint/tendermint/rpc/core/types"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/cosmos/cosmos-sdk/client/utils"
) )
func statusCommand() *cobra.Command { func statusCommand() *cobra.Command {
@ -22,6 +23,7 @@ func statusCommand() *cobra.Command {
cmd.Flags().StringP(client.FlagNode, "n", "tcp://localhost:26657", "Node to connect to") cmd.Flags().StringP(client.FlagNode, "n", "tcp://localhost:26657", "Node to connect to")
viper.BindPFlag(client.FlagNode, cmd.Flags().Lookup(client.FlagNode)) viper.BindPFlag(client.FlagNode, cmd.Flags().Lookup(client.FlagNode))
cmd.Flags().Bool(client.FlagIndentResponse, false, "Add indent to JSON response")
return cmd return cmd
} }
@ -43,8 +45,13 @@ func printNodeStatus(cmd *cobra.Command, args []string) error {
return err return err
} }
output, err := cdc.MarshalJSON(status) var output []byte
// output, err := cdc.MarshalJSONIndent(res, " ", "") indent := viper.GetBool(client.FlagIndentResponse)
if indent {
output, err = cdc.MarshalJSONIndent(status, "", " ")
} else {
output, err = cdc.MarshalJSON(status)
}
if err != nil { if err != nil {
return err return err
} }
@ -66,14 +73,7 @@ func NodeInfoRequestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
} }
nodeInfo := status.NodeInfo nodeInfo := status.NodeInfo
output, err := cdc.MarshalJSONIndent(nodeInfo, "", " ") utils.PostProcessResponse(w, cdc, nodeInfo)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(output)
} }
} }

View File

@ -98,12 +98,13 @@ func getValidators(cliCtx context.CLIContext, height *int64) ([]byte, error) {
} }
} }
output, err := cdc.MarshalJSONIndent(outputValidatorsRes, "", " ") indent := viper.GetBool(client.FlagIndentResponse)
if err != nil {
return nil, err
}
return output, nil if indent {
return cdc.MarshalJSONIndent(outputValidatorsRes, "", " ")
} else {
return cdc.MarshalJSON(outputValidatorsRes)
}
} }
// CMD // CMD

View File

@ -4,14 +4,14 @@ import (
"net/http" "net/http"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
"io/ioutil"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/client/utils"
"github.com/cosmos/cosmos-sdk/codec"
"io/ioutil"
) )
const ( const (
// Returns with the response from CheckTx. // Returns with the response from CheckTx.
flagSync = "sync" flagSync = "sync"
// Returns right away, with no response // Returns right away, with no response
flagAsync = "async" flagAsync = "async"
// Only returns error if mempool.BroadcastTx errs (ie. problem with the app) or if we timeout waiting for tx to commit. // Only returns error if mempool.BroadcastTx errs (ie. problem with the app) or if we timeout waiting for tx to commit.
@ -21,7 +21,7 @@ const (
// BroadcastBody Tx Broadcast Body // BroadcastBody Tx Broadcast Body
type BroadcastBody struct { type BroadcastBody struct {
TxBytes []byte `json:"tx"` TxBytes []byte `json:"tx"`
Return string `json:"return"` Return string `json:"return"`
} }
// BroadcastTxRequest REST Handler // BroadcastTxRequest REST Handler
@ -55,12 +55,6 @@ func BroadcastTxRequest(cliCtx context.CLIContext, cdc *codec.Codec) http.Handle
utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return return
} }
output, err := cdc.MarshalJSONIndent(res, "", " ") utils.PostProcessResponse(w, cdc, res)
if err != nil {
utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(output)
} }
} }

View File

@ -17,6 +17,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/cosmos/cosmos-sdk/client/utils"
) )
// QueryTxCmd implements the default command for a tx query. // QueryTxCmd implements the default command for a tx query.
@ -78,7 +79,12 @@ func queryTx(cdc *codec.Codec, cliCtx context.CLIContext, hashHexStr string) ([]
return nil, err return nil, err
} }
return codec.MarshalJSONIndent(cdc, info) indent := viper.GetBool(client.FlagIndentResponse)
if indent {
return cdc.MarshalJSONIndent(info, "", " ")
} else {
return cdc.MarshalJSON(info)
}
} }
// ValidateTxResult performs transaction verification // ValidateTxResult performs transaction verification
@ -142,7 +148,6 @@ func QueryTxRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.H
w.Write([]byte(err.Error())) w.Write([]byte(err.Error()))
return return
} }
w.Header().Set("Content-Type", "application/json") utils.PostProcessResponse(w, cdc, output)
w.Write(output)
} }
} }

View File

@ -16,6 +16,7 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
ctypes "github.com/tendermint/tendermint/rpc/core/types" ctypes "github.com/tendermint/tendermint/rpc/core/types"
"github.com/cosmos/cosmos-sdk/client/utils"
) )
const ( const (
@ -51,7 +52,14 @@ $ gaiacli tendermint txs --tag test1,test2 --any
return err return err
} }
output, err := cdc.MarshalJSON(txs) var output []byte
indent := viper.GetBool(client.FlagIndentResponse)
if indent {
output, err = cdc.MarshalJSONIndent(txs, "", " ")
} else {
output, err = cdc.MarshalJSON(txs)
}
if err != nil { if err != nil {
return err return err
} }
@ -174,13 +182,6 @@ func SearchTxRequestHandlerFn(cliCtx context.CLIContext, cdc *codec.Codec) http.
return return
} }
output, err := cdc.MarshalJSONIndent(txs, "", " ") utils.PostProcessResponse(w, cdc, txs)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(output)
} }
} }

View File

@ -1,5 +1,6 @@
package utils package utils
import "C"
import ( import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
@ -8,12 +9,13 @@ import (
"strconv" "strconv"
"strings" "strings"
client "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
auth "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth"
authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder"
"github.com/spf13/viper"
) )
const ( const (
@ -240,10 +242,26 @@ func CompleteAndBroadcastTxREST(w http.ResponseWriter, r *http.Request, cliCtx c
return return
} }
output, err := codec.MarshalJSONIndent(cdc, res) PostProcessResponse(w, cdc, res)
if err != nil { }
WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return func PostProcessResponse(w http.ResponseWriter, cdc *codec.Codec, response interface{}) {
var output []byte
switch response.(type) {
default:
indent := viper.GetBool(client.FlagIndentResponse)
var err error
if indent {
output, err = cdc.MarshalJSONIndent(response, "", " ")
} else {
output, err = cdc.MarshalJSON(response)
}
if err != nil {
WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
case []byte:
output = response.([]byte)
} }
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.Write(output) w.Write(output)

View File

@ -9,6 +9,8 @@ import (
"github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth"
"github.com/spf13/viper"
"github.com/cosmos/cosmos-sdk/client"
) )
// GetAccountCmdDefault invokes the GetAccountCmd for the auth.BaseAccount type. // GetAccountCmdDefault invokes the GetAccountCmd for the auth.BaseAccount type.
@ -58,7 +60,13 @@ func GetAccountCmd(storeName string, cdc *codec.Codec, decoder auth.AccountDecod
return err return err
} }
output, err := codec.MarshalJSONIndent(cdc, acc) var output []byte
indent := viper.GetBool(client.FlagIndentResponse)
if indent {
output, err = cdc.MarshalJSONIndent(acc, "", " ")
} else {
output, err = cdc.MarshalJSON(acc)
}
if err != nil { if err != nil {
return err return err
} }

View File

@ -57,7 +57,13 @@ func makeSignCmd(cdc *amino.Codec, decoder auth.AccountDecoder) func(cmd *cobra.
if err != nil { if err != nil {
return err return err
} }
json, err := cdc.MarshalJSON(newTx) var json []byte
indent := viper.GetBool(client.FlagIndentResponse)
if indent {
json, err = cdc.MarshalJSONIndent(newTx, "", " ")
} else {
json, err = cdc.MarshalJSON(newTx)
}
if err != nil { if err != nil {
return err return err
} }

View File

@ -65,14 +65,7 @@ func QueryAccountRequestHandlerFn(
return return
} }
// print out whole account utils.PostProcessResponse(w, cdc, account)
output, err := cdc.MarshalJSON(account)
if err != nil {
utils.WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("couldn't marshall query result. Error: %s", err.Error()))
return
}
w.Write(output)
} }
} }
@ -111,13 +104,6 @@ func QueryBalancesRequestHandlerFn(
return return
} }
// print out whole account utils.PostProcessResponse(w, cdc, account.GetCoins())
output, err := cdc.MarshalJSONIndent(account.GetCoins(), "", " ")
if err != nil {
utils.WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("couldn't marshall query result. Error: %s", err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(output)
} }
} }

View File

@ -52,12 +52,6 @@ func SignTxRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) http.Ha
return return
} }
output, err := codec.MarshalJSONIndent(cdc, signedTx) utils.PostProcessResponse(w, cdc, signedTx)
if err != nil {
utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(output)
} }
} }

View File

@ -33,13 +33,7 @@ func BroadcastTxRequestHandlerFn(cdc *codec.Codec, cliCtx context.CLIContext) ht
return return
} }
output, err := codec.MarshalJSONIndent(cdc, res) utils.PostProcessResponse(w, cdc, res)
if err != nil {
utils.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(output)
} }
} }