bootstrap.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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))
  60. //csrf.Domain("")
  61. b.Party("/", protect)
  62. }
  63. // 配置jwt
  64. // func (b *Bootstrapper) SetupJwtHandlers(jwtKey string) {
  65. // // j2 := jwt.New(jwt.Config{
  66. // // // 注意,新增了一个错误处理函数
  67. // // ErrorHandler: func(ctx iris.Context, err error) {
  68. // // if err == nil {
  69. // // return
  70. // // }
  71. // // ctx.StopExecution()
  72. // // ctx.StatusCode(iris.StatusUnauthorized)
  73. // // ctx.JSON(ResModel{
  74. // // Code: "501",
  75. // // Msg: err.Error(),
  76. // // })
  77. // // },
  78. // // // 设置一个函数返回秘钥,关键在于return []byte("这里设置秘钥")
  79. // // ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
  80. // // return []byte(jwtKey), nil
  81. // // },
  82. // // // 设置一个加密方法
  83. // // SigningMethod: jwt.SigningMethodHS256,
  84. // // })
  85. // //b.Party("/", j2.Serve)
  86. // }
  87. //处理异常--设置错误信息展示
  88. func (b *Bootstrapper) SetupErrorHandlers() {
  89. b.OnAnyErrorCode(func(ctx iris.Context) {
  90. err := iris.Map{
  91. "app": b.AppName,
  92. "status": ctx.GetStatusCode(),
  93. "message": ctx.Values().GetString("message"),
  94. }
  95. //如果是json格式,使用json方式输出
  96. if jsonOutput := ctx.URLParamExists("json"); jsonOutput {
  97. ctx.JSON(err)
  98. return
  99. }
  100. ctx.ViewData("Err", err)
  101. ctx.ViewData("Title", "Error")
  102. ctx.View("shared/error.html")
  103. })
  104. }
  105. //配置的方法 Configure accepts configurations and runs them inside the Bootstraper's context.
  106. func (b *Bootstrapper) Configure(cs ...Configurator) {
  107. for _, c := range cs {
  108. c(b)
  109. }
  110. }
  111. // 启动计划任务服务
  112. func (b *Bootstrapper) setupCron() {
  113. // TODO
  114. }
  115. const (
  116. StaticAssets = "./public"
  117. Favicon = "/favicon.ico"
  118. //20200902GCJSXM7C084477AEA06096F5
  119. //9AB0F421E53A477C084477AEA06096F5
  120. CsrfKey = "9AB0F421E53A477C084477AEA06096F5"
  121. JwtKey = "9AB0F421E53A477C084477AEA06096F5"
  122. )
  123. // 初始化Bootstrap
  124. // Returns itself.
  125. func (b *Bootstrapper) Bootstrap() *Bootstrapper {
  126. //设置模板
  127. b.SetupViews("./views")
  128. // b.SetupSessions(24*time.Hour,
  129. // []byte("the-big-and-secret-fash-key-here"),
  130. // []byte("lot-secret-of-characters-big-too"),
  131. // )
  132. // 设置csrf
  133. b.SetupCsrfHandlers(CsrfKey)
  134. // 设置jwt
  135. //b.SetupJwtHandlers(JwtKey)
  136. //设置异常信息
  137. b.SetupErrorHandlers()
  138. // static files
  139. b.Favicon(StaticAssets + Favicon)
  140. //b.StaticWeb(StaticAssets[1:], StaticAssets)
  141. b.HandleDir(StaticAssets[1:], iris.Dir(StaticAssets))
  142. b.HandleDir("/docs", iris.Dir("./docs"))
  143. // indexHtml, err := ioutil.ReadFile(StaticAssets + "/index.html")
  144. // if err == nil {
  145. // b.StaticContent(StaticAssets[1:]+"/", "text/html",
  146. // indexHtml)
  147. // }
  148. // 不要把目录末尾"/"省略掉
  149. //iris.WithoutPathCorrectionRedirection(b.Application)
  150. // crontab
  151. b.setupCron()
  152. // middleware, after static files
  153. b.Use(recover.New())
  154. b.Use(logger.New())
  155. return b
  156. }
  157. func (b *Bootstrapper) Listen(addr string, cfgs ...iris.Configurator) {
  158. b.Run(iris.Addr(addr), cfgs...)
  159. }