reply.go 988 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package reply
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "github.com/go-kratos/kratos/v2/errors"
  6. http2 "github.com/go-kratos/kratos/v2/transport/http"
  7. )
  8. type SuccessReply struct {
  9. Code int32 `json:"code"`
  10. Message string `json:"message"`
  11. Data interface{} `json:"data"`
  12. }
  13. func SetContentType(w http.ResponseWriter, contentType string) {
  14. if contentType == "" {
  15. return
  16. }
  17. w.Header().Set("Content-Type", contentType)
  18. }
  19. func ErrorReturn(err error, w http.ResponseWriter, r *http.Request, h http2.HandleOptions) {
  20. errStatus := errors.FromError(err)
  21. if errStatus != nil {
  22. if errStatus.Reason != "" {
  23. fail := &SuccessReply{
  24. Code: errStatus.GRPCStatus().Proto().Code,
  25. Message: errStatus.GRPCStatus().Message(),
  26. }
  27. var obj interface{}
  28. json.Unmarshal([]byte(errors.Reason(err)), &obj)
  29. fail.Data = obj
  30. w.WriteHeader(400)
  31. if err = h.Encode(w, r, fail); err != nil {
  32. h.Error(w, r, err)
  33. }
  34. return
  35. }
  36. }
  37. h.Error(w, r, err)
  38. return
  39. }