bootstrap.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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/iris-contrib/middleware/jwt"
  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. )
  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. AppSpawnDate time.Time
  27. }
  28. //var RpcConnect *grpc.ClientConn
  29. func init() {
  30. // log.Println("RpcConnect 初始化中...")
  31. // conn, err := grpc.Dial(conf.NodeRpcHost, grpc.WithInsecure())
  32. // if err != nil {
  33. // log.Fatalf("did not connect: %v", err)
  34. // }
  35. // RpcConnect = conn
  36. // log.Println("RpcConnect 初始化成功")
  37. }
  38. //新建和返回一个Bootstrapper
  39. func New(appName, appOwner string, cfgs ...Configurator) *Bootstrapper {
  40. b := &Bootstrapper{
  41. AppName: appName,
  42. AppOwner: appOwner,
  43. AppSpawnDate: time.Now(),
  44. Application: iris.New(),
  45. }
  46. //数组遍历 cfg方法
  47. for _, cfg := range cfgs {
  48. cfg(b)
  49. }
  50. return b
  51. }
  52. //Bootstrapper的方法 读取模板
  53. func (b *Bootstrapper) SetupViews(viewsDir string) {
  54. htmlEngine := iris.HTML(viewsDir, ".html").Layout("shared/layout.html")
  55. // 每次重新加载模版(线上关闭它)
  56. htmlEngine.Reload(true)
  57. // 给模版内置各种定制的方法
  58. htmlEngine.AddFunc("FromUnixtimeShort", func(t int) string {
  59. dt := time.Unix(int64(t), int64(0))
  60. return dt.Format(conf.SysTimeformShort)
  61. })
  62. htmlEngine.AddFunc("FromUnixtime", func(t int) string {
  63. dt := time.Unix(int64(t), int64(0))
  64. return dt.Format(conf.SysTimeform)
  65. })
  66. b.RegisterView(htmlEngine)
  67. }
  68. // 配置csrf
  69. func (b *Bootstrapper) SetupCsrfHandlers(csrfKey string) {
  70. protect := csrf.Protect([]byte(csrfKey), csrf.FieldName("csrf"), csrf.Secure(false), csrf.Path("/"), csrf.ErrorHandler(func(ctx iris.Context) {
  71. ctx.JSON(iris.Map{"code": -1, "msg": "CSRF token invalid"})
  72. }))
  73. //csrf.Domain("")
  74. // , csrf.Domain("cmr.com"), csrf.Path("/")
  75. b.Party("/", protect)
  76. }
  77. // 配置jwt
  78. func (b *Bootstrapper) SetupJwtHandlers(jwtKey string) {
  79. j2 := jwt.New(jwt.Config{
  80. // 注意,新增了一个错误处理函数
  81. ErrorHandler: func(ctx iris.Context, err error) {
  82. if err == nil {
  83. return
  84. }
  85. ctx.StopExecution()
  86. ctx.StatusCode(iris.StatusUnauthorized)
  87. ctx.JSON(iris.Map{
  88. "code": 2,
  89. "msg": "token invalid",
  90. })
  91. },
  92. // 设置一个函数返回秘钥,关键在于return []byte("这里设置秘钥")
  93. ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
  94. return []byte(jwtKey), nil
  95. },
  96. // 设置一个加密方法
  97. SigningMethod: jwt.SigningMethodHS256,
  98. })
  99. b.Party("/", j2.Serve)
  100. }
  101. // 装配rpcClient
  102. func (b *Bootstrapper) SetupRpcClient() {
  103. // b.Use(func(ctx iris.Context) {
  104. // ctx.Values().Set("RpcConnect", RpcConnect)
  105. // ctx.Next()
  106. // })
  107. // log.Println("RpcConnect 注入成功")
  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. }