另客网go项目公用的代码库

check.go 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package check
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "net/http"
  7. )
  8. type (
  9. errorWriter struct {
  10. gin.ResponseWriter
  11. data []byte
  12. }
  13. )
  14. func (ew *errorWriter) WriteString(data string) (int, error) {
  15. ew.data = append(ew.data, []byte(data)...)
  16. return ew.ResponseWriter.WriteString(data)
  17. }
  18. func (ew *errorWriter) Write(data []byte) (int, error) {
  19. ew.data = append(ew.data, data...)
  20. return ew.ResponseWriter.Write(data)
  21. }
  22. func (ew *errorWriter) successful() bool {
  23. switch ew.Status() {
  24. case 200, 201, 202, 204:
  25. return true
  26. case 400, 401, 403, 404, 406, 410, 422, 500:
  27. return false
  28. default:
  29. panic(fmt.Sprintf("unsupported status code %d", ew.Status()))
  30. }
  31. }
  32. func CodeAnalysis() gin.HandlerFunc {
  33. return func(ctx *gin.Context) {
  34. ew := &errorWriter{ResponseWriter: ctx.Writer}
  35. ctx.Writer = ew
  36. ctx.Next()
  37. switch ew.Header().Get("Content-Type") {
  38. case "application/json; charset=utf-8":
  39. rps := map[string]string{}
  40. err := json.Unmarshal(ew.data, &rps)
  41. if err != nil {
  42. panic("unsupported data format, only json now.")
  43. }
  44. if !ew.successful() {
  45. // 对返回的错误信息格式进行代码检测
  46. if len(rps) != 1 || rps["msg"] == "" {
  47. panic(fmt.Sprintf("you need return %s but, %s", `{"msg":"content can't empty'"}`, string(ew.data)))
  48. }
  49. } else {
  50. // 如果post请求的状态码不是201的话返回错误
  51. if ctx.Request.Method == "POST" && ew.Status() != http.StatusCreated {
  52. panic(fmt.Sprintf("you need set http status to %d", http.StatusCreated))
  53. }
  54. // 如果状态码是201但是请求方式不是post的话返回错误
  55. if ew.Status() == http.StatusCreated && ctx.Request.Method != "POST" {
  56. panic(fmt.Sprintf("the http status %d can set when method=POST", http.StatusCreated))
  57. }
  58. // 如果返回的数据为nil则报错
  59. if rps == nil {
  60. panic(fmt.Sprintf("if response body is null, please only set http status"))
  61. }
  62. // 如果返回状态码为204则body不能有任何数据
  63. if ew.Status() == http.StatusNoContent && len(ew.data) != 0 {
  64. panic(fmt.Sprintf("if response stauts is %d, can't have reponse body", http.StatusNoContent))
  65. }
  66. }
  67. default:
  68. if len(ew.data) == 0 && ew.Status() != http.StatusNoContent {
  69. panic(fmt.Sprintf("if response body is null, please only set http status %d", http.StatusNoContent))
  70. }
  71. if len(ew.data) != 0 {
  72. panic("unsupported data format, only json now.")
  73. }
  74. }
  75. }
  76. }