bootstrap.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. ctx.JSON(iris.Map{"code": -1, "msg": "请求错误,请检查"})
  107. })
  108. }
  109. //配置的方法 Configure accepts configurations and runs them inside the Bootstraper's context.
  110. func (b *Bootstrapper) Configure(cs ...Configurator) {
  111. for _, c := range cs {
  112. c(b)
  113. }
  114. }
  115. // 启动计划任务服务
  116. func (b *Bootstrapper) setupCron() {
  117. // TODO
  118. }
  119. const (
  120. StaticAssets = "./public"
  121. Favicon = "/favicon.ico"
  122. //20200902GCJSXM7C084477AEA06096F5
  123. //9AB0F421E53A477C084477AEA06096F5
  124. CsrfKey = "9AB0F421E53A477C084477AEA06096F5"
  125. JwtKey = "9AB0F421E53A477C084477AEA06096F5"
  126. )
  127. // 初始化Bootstrap
  128. // Returns itself.
  129. func (b *Bootstrapper) Bootstrap() *Bootstrapper {
  130. //设置模板
  131. b.SetupViews("./views")
  132. // b.SetupSessions(24*time.Hour,
  133. // []byte("the-big-and-secret-fash-key-here"),
  134. // []byte("lot-secret-of-characters-big-too"),
  135. // )
  136. // 设置csrf
  137. b.SetupCsrfHandlers(CsrfKey)
  138. // 设置jwt
  139. //b.SetupJwtHandlers(JwtKey)
  140. //设置异常信息
  141. b.SetupErrorHandlers()
  142. // static files
  143. b.Favicon(StaticAssets + Favicon)
  144. //b.StaticWeb(StaticAssets[1:], StaticAssets)
  145. b.HandleDir(StaticAssets[1:], iris.Dir(StaticAssets))
  146. b.HandleDir("/docs", iris.Dir("./docs"))
  147. // indexHtml, err := ioutil.ReadFile(StaticAssets + "/index.html")
  148. // if err == nil {
  149. // b.StaticContent(StaticAssets[1:]+"/", "text/html",
  150. // indexHtml)
  151. // }
  152. // 不要把目录末尾"/"省略掉
  153. //iris.WithoutPathCorrectionRedirection(b.Application)
  154. // crontab
  155. b.setupCron()
  156. // middleware, after static files
  157. b.Use(recover.New())
  158. b.Use(logger.New())
  159. return b
  160. }
  161. func (b *Bootstrapper) Listen(addr string, cfgs ...iris.Configurator) {
  162. b.Run(iris.Addr(addr), cfgs...)
  163. }