我算是明白了,别说 go wire 了,勾八连 GO 这个语言能不能靠得住都挺难说的。既然如此,还是大胆一点吧。俗话说得好,所有让人难绷的细节都是为了宏观上的达成意图的方便。那就来吧。
46 lines
764 B
Go
46 lines
764 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(ct Ctrl, p *sql.DB) *Application {
|
|
route := gin.Default()
|
|
srv := &http.Server{
|
|
Addr: ":8443",
|
|
Handler: route,
|
|
}
|
|
return &Application{srv, p}
|
|
}
|