49 lines
825 B
Go
49 lines
825 B
Go
|
|
package application
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"database/sql"
|
||
|
|
"fmt"
|
||
|
|
"net/http"
|
||
|
|
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
)
|
||
|
|
|
||
|
|
type Ctrl interface {
|
||
|
|
RegisterRoutes(engine *gin.Engine)
|
||
|
|
}
|
||
|
|
|
||
|
|
type Application struct {
|
||
|
|
srv *http.Server
|
||
|
|
pool *sql.DB
|
||
|
|
}
|
||
|
|
|
||
|
|
func (app *Application) Start() error {
|
||
|
|
return app.srv.ListenAndServe()
|
||
|
|
}
|
||
|
|
|
||
|
|
func (app *Application) Stop() {
|
||
|
|
err := app.pool.Close()
|
||
|
|
if err != nil {
|
||
|
|
fmt.Println("关闭数据库链接遭遇错误")
|
||
|
|
fmt.Println(err)
|
||
|
|
}
|
||
|
|
err = app.srv.Shutdown(context.Background())
|
||
|
|
if err != nil {
|
||
|
|
fmt.Println("优雅关闭服务遭遇错误")
|
||
|
|
fmt.Println(err)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func NewApplication(cs []Ctrl, p *sql.DB) *Application {
|
||
|
|
route := gin.Default()
|
||
|
|
for _, ctrl := range cs {
|
||
|
|
ctrl.RegisterRoutes(route)
|
||
|
|
}
|
||
|
|
srv := &http.Server{
|
||
|
|
Addr: ":8443",
|
||
|
|
Handler: route,
|
||
|
|
}
|
||
|
|
return &Application{srv, p}
|
||
|
|
}
|