0g-chain/internal/lcd/decode.go

58 lines
1.2 KiB
Go
Raw Normal View History

2018-06-21 23:37:55 +00:00
package lcd
import (
"encoding/base64"
"encoding/json"
2018-09-20 00:23:37 +00:00
"net/http"
2018-06-21 23:37:55 +00:00
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/wire"
"github.com/cosmos/cosmos-sdk/x/auth"
)
type TxBody struct {
TxBase64 string `json:"txbase64"`
}
// Decode a tx from base64 into json
2018-09-20 00:23:37 +00:00
func DecodeTxRequestHandlerFn(cliCtx context.CLIContext, cdc *wire.Codec) http.HandlerFunc {
2018-06-21 23:37:55 +00:00
return func(w http.ResponseWriter, r *http.Request) {
// get the input base64 string
var m TxBody
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&m)
if err != nil {
w.WriteHeader(400)
w.Write([]byte(err.Error()))
return
}
// convert from base64 string to bytes
txBytes, err := base64.StdEncoding.DecodeString(m.TxBase64)
if err != nil {
w.WriteHeader(400)
w.Write([]byte(err.Error()))
return
}
// convert bytes to Tx struct
var tx auth.StdTx
err = cdc.UnmarshalBinary(txBytes, &tx)
if err != nil {
w.WriteHeader(400)
w.Write([]byte(err.Error()))
return
}
// convert Tx struct to json (bytes) and return
output, err := cdc.MarshalJSON(tx)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
w.Write(output)
}
}