app.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Code generated by dol build. Only Generate by tools if not existed, your can rewrite platform.App default action
  2. // source: app.go
  3. package app
  4. import (
  5. "sync"
  6. "time"
  7. "github.com/2637309949/dolphin/packages/gin"
  8. "github.com/2637309949/dolphin/packages/go-funk"
  9. pApp "github.com/2637309949/dolphin/platform/app"
  10. )
  11. type (
  12. // Engine defined parse app engine
  13. Engine struct {
  14. *pApp.Engine
  15. pool sync.Pool
  16. }
  17. // Context defined http handle hook context
  18. Context struct {
  19. *pApp.Context
  20. engine *Engine
  21. }
  22. // RouterGroup defines struct that extend from gin.RouterGroup
  23. RouterGroup struct {
  24. *pApp.RouterGroup
  25. engine *Engine
  26. }
  27. // HandlerFunc defines the handler used by gin middleware as return value.
  28. HandlerFunc func(*Context)
  29. )
  30. func (e *Engine) allocateContext() *Context {
  31. return &Context{engine: e}
  32. }
  33. // Group handlers
  34. func (e *Engine) Group(relativePath string, handlers ...gin.HandlerFunc) *RouterGroup {
  35. return &RouterGroup{engine: e, RouterGroup: e.Engine.Group(relativePath, handlers...)}
  36. }
  37. // HandlerFunc convert to pApp.HandlerFunc
  38. func (e *Engine) HandlerFunc(h HandlerFunc) (phf pApp.HandlerFunc) {
  39. return pApp.HandlerFunc(func(ctx *pApp.Context) {
  40. c := e.pool.Get().(*Context)
  41. c.Context = ctx
  42. h(c)
  43. e.pool.Put(c)
  44. })
  45. }
  46. // Handle overwrite RouterGroup.Handle
  47. func (rg *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) gin.IRoutes {
  48. rh := rg.RouterGroup.Handle(
  49. httpMethod,
  50. relativePath,
  51. funk.Map(handlers, func(h HandlerFunc) pApp.HandlerFunc {
  52. return rg.engine.HandlerFunc(h)
  53. }).([]pApp.HandlerFunc)...)
  54. return rh
  55. }
  56. // Auth middles
  57. func Auth(ctx *Context) {
  58. pApp.Auth(ctx.Context)
  59. }
  60. // Roles middles
  61. func Roles(roles ...string) func(ctx *Context) {
  62. return func(ctx *Context) {
  63. pApp.Roles(roles...)(ctx.Context)
  64. }
  65. }
  66. // Cache middles
  67. func Cache(time time.Duration) func(ctx *Context) {
  68. return func(ctx *Context) {
  69. pApp.Cache(time)(ctx.Context)
  70. }
  71. }
  72. // buildEngine defined init engine you can custom engine
  73. // if you need
  74. func buildEngine() *Engine {
  75. e := &Engine{Engine: pApp.App}
  76. e.pool.New = func() interface{} {
  77. return e.allocateContext()
  78. }
  79. return e
  80. }
  81. // Run app
  82. func Run() {
  83. App.Run()
  84. }
  85. // App instance
  86. var App = buildEngine()