json.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. This file is part of go-ethereum
  3. go-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. go-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. package rpc
  15. import (
  16. "encoding/json"
  17. "github.com/ethereum/go-ethereum/logger"
  18. "io"
  19. "net/http"
  20. )
  21. var rpclogger = logger.NewLogger("RPC")
  22. type JsonWrapper struct{}
  23. func (self JsonWrapper) Send(writer io.Writer, v interface{}) (n int, err error) {
  24. var payload []byte
  25. payload, err = json.Marshal(v)
  26. if err != nil {
  27. rpclogger.Fatalln("Error marshalling JSON", err)
  28. return 0, err
  29. }
  30. rpclogger.Infof("Sending payload: %s", payload)
  31. return writer.Write(payload)
  32. }
  33. func (self JsonWrapper) ParseRequestBody(req *http.Request) (RpcRequest, error) {
  34. var reqParsed RpcRequest
  35. // Convert JSON to native types
  36. d := json.NewDecoder(req.Body)
  37. // d.UseNumber()
  38. defer req.Body.Close()
  39. err := d.Decode(&reqParsed)
  40. if err != nil {
  41. rpclogger.Errorln("Error decoding JSON: ", err)
  42. return reqParsed, err
  43. }
  44. rpclogger.DebugDetailf("Parsed request: %s", reqParsed)
  45. return reqParsed, nil
  46. }