bootstrap.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. /*
  2. * @description:web项目启动
  3. * @Author: CP
  4. * @Date: 2020-08-21 11:20:00
  5. * @FilePath: \construction_management\bootstrap\bootstrap.go
  6. */
  7. package bootstrap
  8. import (
  9. "time"
  10. "github.com/iris-contrib/middleware/csrf"
  11. "github.com/kataras/iris/v12"
  12. "github.com/kataras/iris/v12/middleware/logger"
  13. "github.com/kataras/iris/v12/middleware/recover"
  14. "go.mod/conf"
  15. )
  16. //配置器,定制化的配置--方法类型
  17. type Configurator func(*Bootstrapper)
  18. //GCJSXM88CP20200902666A477C084477
  19. // const csrfKey = "GCJSXM88CP20200902666A477C084477"
  20. //结构体扩展iris,类此于继承
  21. type Bootstrapper struct {
  22. *iris.Application
  23. AppName string
  24. AppOwner string
  25. AppSpawnDate time.Time
  26. }
  27. //新建和返回一个Bootstrapper
  28. func New(appName, appOwner string, cfgs ...Configurator) *Bootstrapper {
  29. b := &Bootstrapper{
  30. AppName: appName,
  31. AppOwner: appOwner,
  32. AppSpawnDate: time.Now(),
  33. Application: iris.New(),
  34. }
  35. //数组遍历 cfg方法
  36. for _, cfg := range cfgs {
  37. cfg(b)
  38. }
  39. return b
  40. }
  41. //Bootstrapper的方法 读取模板
  42. func (b *Bootstrapper) SetupViews(viewsDir string) {
  43. htmlEngine := iris.HTML(viewsDir, ".html").Layout("shared/layout.html")
  44. // 每次重新加载模版(线上关闭它)
  45. htmlEngine.Reload(true)
  46. // 给模版内置各种定制的方法
  47. htmlEngine.AddFunc("FromUnixtimeShort", func(t int) string {
  48. dt := time.Unix(int64(t), int64(0))
  49. return dt.Format(conf.SysTimeformShort)
  50. })
  51. htmlEngine.AddFunc("FromUnixtime", func(t int) string {
  52. dt := time.Unix(int64(t), int64(0))
  53. return dt.Format(conf.SysTimeform)
  54. })
  55. b.RegisterView(htmlEngine)
  56. }
  57. // 配置csrf
  58. func (b *Bootstrapper) SetupCsrfHandlers(csrfKey string) {
  59. protect := csrf.Protect([]byte(csrfKey), csrf.FieldName("csrf"), csrf.Secure(false), csrf.Path("/"), csrf.ErrorHandler(func(ctx iris.Context) {
  60. ctx.JSON(iris.Map{"code": -1, "msg": "CSRF token invalid"})
  61. }))
  62. //csrf.Domain("")
  63. // , csrf.Domain("cmr.com"), csrf.Path("/")
  64. b.Party("/", protect)
  65. }
  66. // 配置jwt
  67. // func (b *Bootstrapper) SetupJwtHandlers(jwtKey string) {
  68. // j2 := jwt.New(jwt.Config{
  69. // // 注意,新增了一个错误处理函数
  70. // ErrorHandler: func(ctx iris.Context, err error) {
  71. // if err == nil {
  72. // return
  73. // }
  74. // ctx.StopExecution()
  75. // ctx.StatusCode(iris.StatusUnauthorized)
  76. // ctx.JSON(ResModel{
  77. // Code: "501",
  78. // Msg: err.Error(),
  79. // })
  80. // },
  81. // // 设置一个函数返回秘钥,关键在于return []byte("这里设置秘钥")
  82. // ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
  83. // return []byte(jwtKey), nil
  84. // },
  85. // // 设置一个加密方法
  86. // SigningMethod: jwt.SigningMethodHS256,
  87. // })
  88. // //b.Party("/", j2.Serve)
  89. // }
  90. //处理异常--设置错误信息展示
  91. func (b *Bootstrapper) SetupErrorHandlers() {
  92. b.OnAnyErrorCode(func(ctx iris.Context) {
  93. err := iris.Map{
  94. "app": b.AppName,
  95. "status": ctx.GetStatusCode(),
  96. "message": ctx.Values().GetString("message"),
  97. }
  98. //如果是json格式,使用json方式输出
  99. if jsonOutput := ctx.URLParamExists("json"); jsonOutput {
  100. ctx.JSON(err)
  101. return
  102. }
  103. ctx.ViewData("Err", err)
  104. ctx.ViewData("Title", "Error")
  105. ctx.View("shared/error.html")
  106. })
  107. }
  108. //配置的方法 Configure accepts configurations and runs them inside the Bootstraper's context.
  109. func (b *Bootstrapper) Configure(cs ...Configurator) {
  110. for _, c := range cs {
  111. c(b)
  112. }
  113. }
  114. // 启动计划任务服务
  115. func (b *Bootstrapper) setupCron() {
  116. // TODO
  117. }
  118. const (
  119. StaticAssets = "./public"
  120. Favicon = "/favicon.ico"
  121. //20200902GCJSXM7C084477AEA06096F5
  122. //9AB0F421E53A477C084477AEA06096F5
  123. CsrfKey = "9AB0F421E53A477C084477AEA06096F5"
  124. JwtKey = "9AB0F421E53A477C084477AEA06096F5"
  125. )
  126. // 初始化Bootstrap
  127. // Returns itself.
  128. func (b *Bootstrapper) Bootstrap() *Bootstrapper {
  129. //设置模板
  130. b.SetupViews("./views")
  131. // b.SetupSessions(24*time.Hour,
  132. // []byte("the-big-and-secret-fash-key-here"),
  133. // []byte("lot-secret-of-characters-big-too"),
  134. // )
  135. // 设置csrf
  136. b.SetupCsrfHandlers(CsrfKey)
  137. // 设置jwt
  138. //b.SetupJwtHandlers(JwtKey)
  139. //设置异常信息
  140. b.SetupErrorHandlers()
  141. // static files
  142. b.Favicon(StaticAssets + Favicon)
  143. //b.StaticWeb(StaticAssets[1:], StaticAssets)
  144. b.HandleDir(StaticAssets[1:], iris.Dir(StaticAssets))
  145. b.HandleDir("/docs", iris.Dir("./docs"))
  146. // indexHtml, err := ioutil.ReadFile(StaticAssets + "/index.html")
  147. // if err == nil {
  148. // b.StaticContent(StaticAssets[1:]+"/", "text/html",
  149. // indexHtml)
  150. // }
  151. // 不要把目录末尾"/"省略掉
  152. //iris.WithoutPathCorrectionRedirection(b.Application)
  153. // crontab
  154. b.setupCron()
  155. // middleware, after static files
  156. b.Use(recover.New())
  157. b.Use(logger.New())
  158. return b
  159. }
  160. func (b *Bootstrapper) Listen(addr string, cfgs ...iris.Configurator) {
  161. b.Run(iris.Addr(addr), cfgs...)
  162. }