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