engine.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package gin_engine
  2. import (
  3. "app/commons/config"
  4. "app/commons/core"
  5. "app/commons/gin_engine/middleware"
  6. "fmt"
  7. "github.com/gin-gonic/gin"
  8. )
  9. // k8s - 健康检查http服务
  10. func RunK8sHttp() {
  11. engine := gin.New()
  12. engine.Use(middleware.Recovery()) // 全局错误恢复中间件
  13. engine.Use(middleware.Cors()) // 跨域 -- 放行所有
  14. k8sGroup(engine)
  15. address := fmt.Sprintf(":%d", config.AppConf().JobAddr)
  16. core.Log.Infof("Http 开启监听端口: %s", address)
  17. core.Log.Infof("Gin run : %+v", engine.Run(address))
  18. }
  19. // gin
  20. func NewHttpEngine() *gin.Engine {
  21. gin.SetMode(gin.ReleaseMode)
  22. engine := gin.New()
  23. engine.Use(gin.Logger())
  24. //engine.Use(middleware.GinLogger()) // 自定义日志处理 -- 自定义日志
  25. // 全局中间件
  26. engine.Use(middleware.Recovery()) // 全局错误恢复中间件
  27. engine.Use(middleware.Cors()) // 跨域 -- 放行所有
  28. k8sGroup(engine)
  29. return engine
  30. }
  31. func k8sGroup(engine *gin.Engine) {
  32. health := engine.Group("/health")
  33. {
  34. health.GET("/liveness", func(ctx *gin.Context) {
  35. ctx.JSON(200, gin.H{"status": "alive"})
  36. })
  37. health.GET("/readiness", func(ctx *gin.Context) {
  38. ctx.JSON(200, gin.H{"status": "ready"})
  39. })
  40. }
  41. }
  42. func RegisterRouter(group *gin.RouterGroup, iCore ContextInterface) {
  43. iCore.Register(group.Group(iCore.Route()))
  44. }
  45. type ContextInterface interface {
  46. Route() string
  47. Register(group *gin.RouterGroup)
  48. }
  49. type CommonHandler struct {
  50. }
  51. func (c CommonHandler) Route() string {
  52. panic("implement me")
  53. }
  54. func (CommonHandler) Register(group *gin.RouterGroup) {
  55. panic("implement me")
  56. }