bootstrap.go 5.3 KB

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