com_context.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package services
  2. import (
  3. "app/commons/constant"
  4. "app/commons/core"
  5. "app/commons/core/redisclient"
  6. "context"
  7. "fmt"
  8. "github.com/demdxx/gocast"
  9. "github.com/gin-gonic/gin"
  10. "time"
  11. )
  12. type Context struct {
  13. *gin.Context
  14. }
  15. func (ctx *Context) Resp(args ...any) {
  16. ctx.Header("Content-Type", "application/json; charset=utf-8")
  17. core.Resp(ctx.Context, args...)
  18. }
  19. func (ctx *Context) Fail(message string) {
  20. ctx.Header("Content-Type", "application/json; charset=utf-8")
  21. core.Resp(ctx.Context, message)
  22. }
  23. func (ctx *Context) UserId() int64 {
  24. return ctx.GetInt64("userId")
  25. }
  26. func (ctx *Context) AdminId() int64 {
  27. return gocast.ToInt64(ctx.GetHeader("authId"))
  28. }
  29. func (ctx *Context) Uid() string {
  30. return ctx.GetString("uid")
  31. }
  32. func (ctx *Context) OpenId() string {
  33. return ctx.GetString("openId")
  34. }
  35. func (ctx *Context) unique(a string) string {
  36. return fmt.Sprintf("CRC:%s", a)
  37. }
  38. func (ctx *Context) RepeatFilter(serviceName string, timeSt time.Duration) bool {
  39. // 尝试设置KEY
  40. nxBool, err := redisclient.DefaultClient().SetNX(context.Background(), ctx.unique(serviceName), true, timeSt).Result()
  41. if err != nil {
  42. return false
  43. }
  44. if !nxBool {
  45. return false
  46. }
  47. // 获取过期时间 -- 可用于验证码获取上 暂五使用场景
  48. _, err = redisclient.DefaultClient().TTL(context.Background(), ctx.unique(serviceName)).Result()
  49. if err != nil {
  50. return false
  51. }
  52. return true
  53. }
  54. func (ctx *Context) I18n(name string) string {
  55. lang := ctx.GetHeader(constant.HeaderKeyLanguage)
  56. if lang == "" {
  57. lang = ctx.GetHeader(constant.HeaderKeyLang)
  58. }
  59. return GetI18nService().Translate(lang, name)
  60. }
  61. func (ctx *Context) OK(data any) {
  62. ctx.Header("Content-Type", "application/json; charset=utf-8")
  63. core.Resp(ctx.Context, data)
  64. }
  65. func (ctx *Context) QueryInt64(key string, defaultVal int64) int64 {
  66. val := ctx.Query(key)
  67. if val == "" {
  68. return defaultVal
  69. }
  70. return gocast.ToInt64(val)
  71. }
  72. func (ctx *Context) QueryString(key string, defaultVal string) string {
  73. val := ctx.Query(key)
  74. if val == "" {
  75. return defaultVal
  76. }
  77. return val
  78. }