protocol.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package appservice
  2. import (
  3. "encoding/json"
  4. "maunium.net/go/gomatrix"
  5. "net/http"
  6. )
  7. // EventList contains a list of events.
  8. type EventList struct {
  9. Events []*gomatrix.Event `json:"events"`
  10. }
  11. // EventListener is a function that receives events.
  12. type EventListener func(event *gomatrix.Event)
  13. // WriteBlankOK writes a blank OK message as a reply to a HTTP request.
  14. func WriteBlankOK(w http.ResponseWriter) {
  15. w.WriteHeader(http.StatusOK)
  16. w.Write([]byte("{}"))
  17. }
  18. // Respond responds to a HTTP request with a JSON object.
  19. func Respond(w http.ResponseWriter, data interface{}) error {
  20. dataStr, err := json.Marshal(data)
  21. if err != nil {
  22. return err
  23. }
  24. _, err = w.Write([]byte(dataStr))
  25. return err
  26. }
  27. // Error represents a Matrix protocol error.
  28. type Error struct {
  29. HTTPStatus int `json:"-"`
  30. ErrorCode ErrorCode `json:"errcode"`
  31. Message string `json:"message"`
  32. }
  33. func (err Error) Write(w http.ResponseWriter) {
  34. w.WriteHeader(err.HTTPStatus)
  35. Respond(w, &err)
  36. }
  37. // ErrorCode is the machine-readable code in an Error.
  38. type ErrorCode string
  39. // Native ErrorCodes
  40. const (
  41. ErrForbidden ErrorCode = "M_FORBIDDEN"
  42. ErrUnknown ErrorCode = "M_UNKNOWN"
  43. )
  44. // Custom ErrorCodes
  45. const (
  46. ErrNoTransactionID ErrorCode = "NET.MAUNIUM.NO_TRANSACTION_ID"
  47. ErrNoBody ErrorCode = "NET.MAUNIUM.NO_REQUEST_BODY"
  48. ErrInvalidJSON ErrorCode = "NET.MAUNIUM.INVALID_JSON"
  49. )