responses.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package httpx
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "sync"
  6. "github.com/zeromicro/go-zero/core/logx"
  7. "github.com/zeromicro/go-zero/rest/internal/errcode"
  8. "github.com/zeromicro/go-zero/rest/internal/header"
  9. )
  10. var (
  11. errorHandler func(error) (int, interface{})
  12. lock sync.RWMutex
  13. )
  14. // Error writes err into w.
  15. func Error(w http.ResponseWriter, err error, fns ...func(w http.ResponseWriter, err error)) {
  16. lock.RLock()
  17. handler := errorHandler
  18. lock.RUnlock()
  19. if handler == nil {
  20. if len(fns) > 0 {
  21. fns[0](w, err)
  22. } else if errcode.IsGrpcError(err) {
  23. // don't unwrap error and get status.Message(),
  24. // it hides the rpc error headers.
  25. http.Error(w, err.Error(), errcode.CodeFromGrpcError(err))
  26. } else {
  27. http.Error(w, err.Error(), http.StatusBadRequest)
  28. }
  29. return
  30. }
  31. code, body := handler(err)
  32. if body == nil {
  33. w.WriteHeader(code)
  34. return
  35. }
  36. e, ok := body.(error)
  37. if ok {
  38. http.Error(w, e.Error(), code)
  39. } else {
  40. WriteJson(w, code, body)
  41. }
  42. }
  43. // Ok writes HTTP 200 OK into w.
  44. func Ok(w http.ResponseWriter) {
  45. w.WriteHeader(http.StatusOK)
  46. }
  47. // OkJson writes v into w with 200 OK.
  48. func OkJson(w http.ResponseWriter, v interface{}) {
  49. WriteJson(w, http.StatusOK, v)
  50. }
  51. // SetErrorHandler sets the error handler, which is called on calling Error.
  52. func SetErrorHandler(handler func(error) (int, interface{})) {
  53. lock.Lock()
  54. defer lock.Unlock()
  55. errorHandler = handler
  56. }
  57. // WriteJson writes v as json string into w with code.
  58. func WriteJson(w http.ResponseWriter, code int, v interface{}) {
  59. bs, err := json.Marshal(v)
  60. if err != nil {
  61. http.Error(w, err.Error(), http.StatusInternalServerError)
  62. return
  63. }
  64. w.Header().Set(ContentType, header.JsonContentType)
  65. w.WriteHeader(code)
  66. if n, err := w.Write(bs); err != nil {
  67. // http.ErrHandlerTimeout has been handled by http.TimeoutHandler,
  68. // so it's ignored here.
  69. if err != http.ErrHandlerTimeout {
  70. logx.Errorf("write response failed, error: %s", err)
  71. }
  72. } else if n < len(bs) {
  73. logx.Errorf("actual bytes: %d, written bytes: %d", len(bs), n)
  74. }
  75. }