You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.3 KiB

  1. /*
  2. package server provides http handlers to construct a server server
  3. for key management, transaction signing, and query validation.
  4. Please read the README and godoc to see how to
  5. configure the server for your application.
  6. */
  7. package server
  8. import (
  9. "encoding/json"
  10. "io/ioutil"
  11. "net/http"
  12. data "github.com/tendermint/go-data"
  13. "github.com/tendermint/go-crypto/keys/server/types"
  14. "github.com/pkg/errors"
  15. )
  16. func readRequest(r *http.Request, o interface{}) error {
  17. defer r.Body.Close()
  18. data, err := ioutil.ReadAll(r.Body)
  19. if err != nil {
  20. return errors.Wrap(err, "Read Request")
  21. }
  22. err = json.Unmarshal(data, o)
  23. if err != nil {
  24. return errors.Wrap(err, "Parse")
  25. }
  26. return validate(o)
  27. }
  28. // most errors are bad input, so 406... do better....
  29. func writeError(w http.ResponseWriter, err error) {
  30. // fmt.Printf("Error: %+v\n", err)
  31. res := types.ErrorResponse{
  32. Code: 406,
  33. Error: err.Error(),
  34. }
  35. writeCode(w, &res, 406)
  36. }
  37. func writeCode(w http.ResponseWriter, o interface{}, code int) {
  38. // two space indent to make it easier to read
  39. data, err := data.ToJSON(o)
  40. if err != nil {
  41. writeError(w, err)
  42. } else {
  43. w.Header().Set("Content-Type", "application/json")
  44. w.WriteHeader(code)
  45. w.Write(data)
  46. }
  47. }
  48. func writeSuccess(w http.ResponseWriter, o interface{}) {
  49. writeCode(w, o, 200)
  50. }