bootstrap.go 5.7 KB

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