api.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package api
  2. import (
  3. "encoding/json"
  4. "log"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. )
  9. const (
  10. Error_code = 0
  11. Error_code_1001 = 1001
  12. Error_msg_1001 = "需要登录"
  13. Error_code_1002 = 1002
  14. Error_msg_1002 = "缺失参数"
  15. Error_code_1003 = 1003
  16. Error_msg_1003 = "无效参数"
  17. Error_code_1004 = 1004
  18. Error_msg_1004 = "没有权限"
  19. Error_code_1005 = 1005
  20. Error_msg_1005 = "请求方式有误"
  21. )
  22. var R = &r{}
  23. type M map[string]interface{}
  24. type r struct{}
  25. //校验是否缺少请求参数
  26. func (r *r) CheckReqParam(w http.ResponseWriter, req *http.Request, keys ...string) bool {
  27. msg := Error_msg_1002
  28. array := []string{}
  29. for _, v := range keys {
  30. if len(req.Form[v]) > 0 {
  31. continue
  32. }
  33. array = append(array, v)
  34. }
  35. if len(array) > 0 {
  36. msg += strings.Join(array, ",")
  37. log.Println(msg)
  38. r.ServeJson(w, req, &Result{
  39. Error_code: Error_code_1002,
  40. Error_msg: msg,
  41. })
  42. return false
  43. }
  44. return true
  45. }
  46. //无效参数
  47. func (r *r) InvalidReqParam(w http.ResponseWriter, req *http.Request, args ...string) string {
  48. msg := Error_msg_1003 + strings.Join(args, ",")
  49. r.ServeJson(w, req, &Result{
  50. Error_code: Error_code_1003,
  51. Error_msg: msg,
  52. })
  53. log.Println(msg)
  54. return msg
  55. }
  56. //没有权限
  57. func (r *r) NoPermissionReq(w http.ResponseWriter, req *http.Request, args ...string) string {
  58. msg := Error_msg_1004
  59. if len(args) >= 0 {
  60. msg += ","
  61. }
  62. msg += strings.Join(args, ",")
  63. r.ServeJson(w, req, &Result{
  64. Error_code: Error_code_1004,
  65. Error_msg: msg,
  66. })
  67. log.Println(msg)
  68. return msg
  69. }
  70. func (r *r) ServeJson(w http.ResponseWriter, req *http.Request, result *Result) {
  71. content, err := json.MarshalIndent(result, "", " ")
  72. if err != nil {
  73. http.Error(w, err.Error(), http.StatusInternalServerError)
  74. return
  75. }
  76. w.Header().Set("Content-Length", strconv.Itoa(len(content)))
  77. w.Header().Set("Content-Type", "application/json")
  78. w.Write(content)
  79. }
  80. func NewResult(data interface{}, err error) Result {
  81. errCode := 0
  82. errMsg := ""
  83. if err != nil {
  84. errCode = -1
  85. errMsg = err.Error()
  86. }
  87. return Result{
  88. Error_code: errCode,
  89. Error_msg: errMsg,
  90. Data: data,
  91. }
  92. }
  93. //接口统一返回值
  94. type Result struct {
  95. Error_code int `json:"error_code"`
  96. Error_msg string `json:"error_msg"`
  97. Data interface{} `json:"data"`
  98. }