http_base.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package http
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "go-common/app/admin/main/up/service"
  7. "go-common/library/ecode"
  8. "go-common/library/log"
  9. "go-common/library/net/http/blademaster"
  10. "io/ioutil"
  11. )
  12. // service的函数原型
  13. type serviceFunc func(context context.Context, arg interface{}) (res interface{}, err error)
  14. // 由于不支持泛型,写得比较难看
  15. // 很多重复的代码用下面来代替
  16. func httpQueryFunc(arg interface{}, sfunc serviceFunc, description string) (httpFunc func(c *blademaster.Context)) {
  17. httpFunc = func(c *blademaster.Context) {
  18. //var arg = new(upcrmmodel.ScoreQueryUpHistoryArgs)
  19. var res interface{}
  20. var err error
  21. var errMsg string
  22. switch {
  23. default:
  24. if err = c.Bind(arg); err != nil {
  25. log.Error("%s, request argument bind fail, err=%v", description, err)
  26. errMsg = fmt.Sprintf("wrong argument, %s", err.Error())
  27. err = ecode.RequestErr
  28. break
  29. }
  30. var scoreRes, e = sfunc(c, arg)
  31. err = e
  32. if e != nil {
  33. errMsg = err.Error()
  34. log.Error("%s query fail, req=%+v, err=%+v", description, arg, err)
  35. break
  36. }
  37. log.Info("%s query ok, req=%+v, result=%+v", description, arg, scoreRes)
  38. res = scoreRes
  39. }
  40. if err != nil {
  41. service.BmHTTPErrorWithMsg(c, err, errMsg)
  42. } else {
  43. c.JSON(res, err)
  44. }
  45. }
  46. return
  47. }
  48. func httpPostFunc(arg interface{}, sfunc serviceFunc, description string) (httpFunc func(c *blademaster.Context)) {
  49. httpFunc = func(c *blademaster.Context) {
  50. //var arg = new(upcrmmodel.ScoreQueryUpHistoryArgs)
  51. var res interface{}
  52. var err error
  53. var errMsg string
  54. switch {
  55. default:
  56. respBody, _ := ioutil.ReadAll(c.Request.Body)
  57. if err = json.Unmarshal(respBody, arg); err != nil {
  58. log.Error("%s, json unmarshal fail, err=%v", description, err)
  59. errMsg = fmt.Sprintf("wrong argument, %s", err.Error())
  60. err = ecode.RequestErr
  61. break
  62. }
  63. scoreRes, e := sfunc(c, arg)
  64. err = e
  65. if e != nil {
  66. errMsg = err.Error()
  67. log.Error("%s query fail, req=%+v, err=%+v", description, arg, err)
  68. break
  69. }
  70. log.Info("%s query ok, req=%+v, result=%+v", description, arg, scoreRes)
  71. res = scoreRes
  72. }
  73. if err != nil {
  74. service.BmHTTPErrorWithMsg(c, err, errMsg)
  75. } else {
  76. c.JSON(res, err)
  77. }
  78. }
  79. return
  80. }