package moto import ( "context" "git.nobla.cn/golang/kos" httpkg "git.nobla.cn/golang/kos/entry/http" "git.nobla.cn/golang/moto/common/db" "git.nobla.cn/golang/moto/config" "git.nobla.cn/golang/moto/models" "git.nobla.cn/golang/moto/version" "git.nobla.cn/golang/rest" "io" "net/http" ) type Server struct { cfg *config.Config ctx context.Context cancelFunc context.CancelCauseFunc } func (svr *Server) prepare() (err error) { if err = db.Init(svr.ctx, svr.cfg.Database); err != nil { return } values := []any{ &models.User{}, &models.Role{}, &models.Department{}, } for _, item := range values { if err = db.DB().AutoMigrate(item); err != nil { return } if err = rest.AutoMigrate(svr.ctx, db.DB(), item, rest.WithoutDomain(), rest.WithModuleName(version.ProductName)); err != nil { return } } rest.SetHttpRouter(svr) return } func (svr *Server) Handle(method string, uri string, handler http.HandlerFunc) { kos.Http().Handle(method, uri, func(ctx *httpkg.Context) (err error) { handler(ctx.Response(), ctx.Request()) return }) } func (svr *Server) Start(ctx context.Context) (err error) { svr.ctx, svr.cancelFunc = context.WithCancelCause(ctx) if err = svr.prepare(); err != nil { return } svr.routes() return } func (svr *Server) Stop() (err error) { svr.cancelFunc(io.ErrClosedPipe) return } func New(cfg *config.Config) *Server { svr := &Server{ cfg: cfg, } return svr }