component.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package mhayaGin
  2. import (
  3. "github.com/gin-gonic/gin"
  4. cfacade "github.com/mhaya/facade"
  5. clog "github.com/mhaya/logger"
  6. )
  7. const (
  8. NamePrefix = "gin_component_"
  9. )
  10. type (
  11. // Component wrapper gin
  12. Component struct {
  13. cfacade.Component
  14. *HttpServer
  15. name string
  16. }
  17. )
  18. func NewHttp(name, address string) *Component {
  19. return New(name, address)
  20. }
  21. func NewHttps(name, address, certFile, keyFile string) *Component {
  22. return New(
  23. name,
  24. address,
  25. WithCert(certFile, keyFile),
  26. )
  27. }
  28. func New(name string, address string, opts ...OptionFunc) *Component {
  29. return &Component{
  30. name: name,
  31. HttpServer: NewHttpServer(address, opts...),
  32. }
  33. }
  34. // Name unique components name
  35. func (g *Component) Name() string {
  36. return NamePrefix + g.name
  37. }
  38. func (g *Component) Init() {
  39. }
  40. func (g *Component) OnAfterInit() {
  41. g.SetIApplication(g.App())
  42. go g.Run()
  43. }
  44. func (g *Component) OnBeforeStop() {
  45. }
  46. func (g *Component) OnStop() {
  47. g.Stop()
  48. clog.Infof("[component = %s] has been shut down", g.Name())
  49. }
  50. func (g *Component) Register(controllers ...IController) *Component {
  51. g.HttpServer.Register(controllers...)
  52. return g
  53. }
  54. func (g *Component) Engine() *gin.Engine {
  55. return g.HttpServer.Engine
  56. }