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

check.go 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. if len(rps) != 1 || rps["msg"] == "" {
  46. panic(fmt.Sprintf("you need return %s but, %s", `{"msg":"content can't empty'"}`, string(ew.data)))
  47. }
  48. } else {
  49. // 如果post请求的状态码不是201的话返回错误
  50. if ctx.Request.Method == "POST" && ew.Status() != http.StatusCreated {
  51. panic(fmt.Sprintf("you need set http status to %d", http.StatusCreated))
  52. }
  53. // 如果状态码是201但是请求方式不是post的话返回错误
  54. if ew.Status() == http.StatusCreated && ctx.Request.Method != "POST" {
  55. panic(fmt.Sprintf("the http status %d can set when method=POST", http.StatusCreated))
  56. }
  57. // 如果返回的数据为nil则报错
  58. if rps == nil {
  59. panic(fmt.Sprintf("if response body is null, please only set http status"))
  60. }
  61. // 如果返回状态码为204则body不能有任何数据
  62. if ew.Status() == http.StatusNoContent && len(ew.data) != 0 {
  63. panic(fmt.Sprintf("if response stauts is %d, can't have reponse body", http.StatusNoContent))
  64. }
  65. }
  66. default:
  67. if len(ew.data) == 0 && ew.Status() != http.StatusNoContent {
  68. panic(fmt.Sprintf("if response body is null, please only set http status %d", http.StatusNoContent))
  69. }
  70. if len(ew.data) != 0 {
  71. panic("unsupported data format, only json now.")
  72. }
  73. }
  74. }
  75. }