github.com/Anderson-Lu/gobox@v0.0.0-20191127065433-3e6c4c2da420/application/application.go (about)

     1  package application
     2  
     3  import (
     4  	log "log"
     5  	"runtime/debug"
     6  )
     7  
     8  //Application is your service
     9  type Application struct {
    10  
    11  	//Context
    12  	context *ApplicationContext
    13  
    14  	//When application start
    15  	onStart func(*ApplicationContext)
    16  
    17  	//When appliction stop
    18  	onStop func(*ApplicationContext)
    19  }
    20  
    21  //Setup application context
    22  func (self *Application) SetContext(c ApplicationContext) {
    23  	self.context = &c
    24  }
    25  
    26  //Setup application start event
    27  func (self *Application) SetOnStart(c func(*ApplicationContext)) {
    28  	self.onStart = c
    29  }
    30  
    31  //Setup application stop event
    32  func (self *Application) SetOnStop(c func(*ApplicationContext)) {
    33  	self.onStop = c
    34  }
    35  
    36  //Run application
    37  func (self *Application) Run(c func(*ApplicationContext)) {
    38  	defer func() {
    39  		if r := recover(); r != nil {
    40  			log.Println("Application Uncaught Error Occour:", r.(error).Error())
    41  			debug.PrintStack()
    42  		}
    43  	}()
    44  	self.onStart(self.context)
    45  	c(self.context)
    46  	self.onStop(self.context)
    47  }