responses.go 1.6 KB

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