moto/server.go

76 lines
1.6 KiB
Go

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"
"git.nobla.cn/golang/rest/plugins/identity"
"git.nobla.cn/golang/rest/plugins/validate"
"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, identity.New(), validate.New()); err != nil {
return
}
values := []any{
&models.User{},
&models.Role{},
&models.Login{},
&models.Department{},
}
rest.SetHttpRouter(svr)
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.ModuleName)); err != nil {
return
}
}
if err = migrate(svr.ctx); err != nil {
return
}
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
}