bootstrap.go 5.3 KB

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