base.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /*
  2. @Time : 2019-06-26 9:31
  3. @Author : zr
  4. @Software: GoLand
  5. */
  6. package controller
  7. import (
  8. "fmt"
  9. "gitee.com/zr233/bsf"
  10. "net/http"
  11. "strconv"
  12. "time"
  13. "video_course/errors"
  14. "video_course/model"
  15. "video_course/utils"
  16. )
  17. type Controller interface {
  18. }
  19. type BaseController struct {
  20. *bsf.ControllerBase
  21. }
  22. type ResponseBase struct {
  23. Code errors.ErrorCode
  24. Memo string
  25. }
  26. func newResponseBase() ResponseBase {
  27. return ResponseBase{
  28. Code: errors.CodeSUCCESS,
  29. Memo: "执行成功",
  30. }
  31. }
  32. func (b BaseController) getSession() *model.Session {
  33. if s, ok := b.Ctx().Get("session"); ok {
  34. s, ok := s.(*model.Session)
  35. if ok {
  36. return s
  37. }
  38. }
  39. return nil
  40. }
  41. func (b *BaseController) postInt(key string) (value *int) {
  42. valueStr := b.Ctx().PostForm(key)
  43. if valueStr != "" {
  44. valueInt, err := strconv.Atoi(valueStr)
  45. if err != nil {
  46. panic(errors.NewParamErr(err))
  47. }
  48. value = &valueInt
  49. }
  50. return
  51. }
  52. func (b *BaseController) postIntNecessary(key string) (value int) {
  53. valueStr := b.Ctx().PostForm(key)
  54. var err error
  55. if valueStr != "" {
  56. value, err = strconv.Atoi(valueStr)
  57. if err != nil {
  58. panic(errors.FromParamErr(key, err))
  59. }
  60. } else {
  61. panic(errors.FromParamErr(key, fmt.Errorf("参数不能为空。")))
  62. }
  63. return
  64. }
  65. func (b *BaseController) postString(key string, necessary bool) string {
  66. str := b.Ctx().PostForm(key)
  67. if necessary && str == "" {
  68. err := errors.FromParamErr(key, fmt.Errorf("参数不能为空。"))
  69. panic(err)
  70. }
  71. return str
  72. }
  73. // 日期校验
  74. func (b *BaseController) getPostFromDate(key string) (value time.Time) {
  75. valueStr := b.Ctx().PostForm(key)
  76. value, e := time.Parse(utils.TimeFormatterDate(), valueStr)
  77. if e != nil {
  78. err := errors.FromParamErr(key, e)
  79. panic(err)
  80. }
  81. return value
  82. }
  83. func (b *BaseController) postFloatToInt(key string, necessary bool) int {
  84. str := b.Ctx().PostForm(key)
  85. if necessary && str == "" {
  86. err := errors.FromParamErr(key, fmt.Errorf("参数不能为空。"))
  87. panic(err)
  88. }
  89. wt, err := strconv.ParseFloat(str, 32)
  90. if err != nil {
  91. err := errors.FromParamErr(key, err)
  92. panic(err)
  93. }
  94. i := int(wt * 10) // 乘以10转int型,保留1位小数
  95. return i
  96. }
  97. // 返回json
  98. func (b BaseController) json(obj interface{}) {
  99. b.Ctx().JSON(http.StatusOK, obj)
  100. }