responses.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package httpx
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "sync"
  6. "git.i2edu.net/i2/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 := errorHandler(err)
  22. e, ok := body.(error)
  23. if ok {
  24. http.Error(w, e.Error(), code)
  25. } else {
  26. WriteJson(w, code, body)
  27. }
  28. }
  29. // Ok writes HTTP 200 OK into w.
  30. func Ok(w http.ResponseWriter) {
  31. w.WriteHeader(http.StatusOK)
  32. }
  33. // OkJson writes v into w with 200 OK.
  34. func OkJson(w http.ResponseWriter, v interface{}) {
  35. WriteJson(w, http.StatusOK, v)
  36. }
  37. // SetErrorHandler sets the error handler, which is called on calling Error.
  38. func SetErrorHandler(handler func(error) (int, interface{})) {
  39. lock.Lock()
  40. defer lock.Unlock()
  41. errorHandler = handler
  42. }
  43. // WriteJson writes v as json string into w with code.
  44. func WriteJson(w http.ResponseWriter, code int, v interface{}) {
  45. w.Header().Set(ContentType, ApplicationJson)
  46. w.WriteHeader(code)
  47. if bs, err := json.Marshal(v); err != nil {
  48. http.Error(w, err.Error(), http.StatusInternalServerError)
  49. } else if n, err := w.Write(bs); err != nil {
  50. // http.ErrHandlerTimeout has been handled by http.TimeoutHandler,
  51. // so it's ignored here.
  52. if err != http.ErrHandlerTimeout {
  53. logx.Errorf("write response failed, error: %s", err)
  54. }
  55. } else if n < len(bs) {
  56. logx.Errorf("actual bytes: %d, written bytes: %d", len(bs), n)
  57. }
  58. }