2024-12-12 11:45:03 +08:00
|
|
|
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"
|
2024-12-13 10:37:09 +08:00
|
|
|
"git.nobla.cn/golang/moto/version"
|
2024-12-12 11:45:03 +08:00
|
|
|
"git.nobla.cn/golang/rest"
|
2024-12-12 17:39:04 +08:00
|
|
|
"git.nobla.cn/golang/rest/plugins/identity"
|
|
|
|
"git.nobla.cn/golang/rest/plugins/validate"
|
2024-12-12 11:45:03 +08:00
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
|
|
|
cfg *config.Config
|
|
|
|
ctx context.Context
|
|
|
|
cancelFunc context.CancelCauseFunc
|
|
|
|
}
|
|
|
|
|
|
|
|
func (svr *Server) prepare() (err error) {
|
2024-12-12 17:39:04 +08:00
|
|
|
if err = db.Init(svr.ctx, svr.cfg.Database, identity.New(), validate.New()); err != nil {
|
2024-12-12 11:45:03 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
values := []any{
|
|
|
|
&models.User{},
|
|
|
|
&models.Role{},
|
2024-12-12 16:24:50 +08:00
|
|
|
&models.Login{},
|
2024-12-12 11:45:03 +08:00
|
|
|
&models.Department{},
|
|
|
|
}
|
2024-12-12 17:39:04 +08:00
|
|
|
rest.SetHttpRouter(svr)
|
2024-12-12 11:45:03 +08:00
|
|
|
for _, item := range values {
|
|
|
|
if err = db.DB().AutoMigrate(item); err != nil {
|
|
|
|
return
|
|
|
|
}
|
2024-12-13 10:37:09 +08:00
|
|
|
if err = rest.AutoMigrate(svr.ctx, db.DB(), item, rest.WithoutDomain(), rest.WithModuleName(version.ModuleName)); err != nil {
|
2024-12-12 11:45:03 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2024-12-13 10:37:09 +08:00
|
|
|
if err = migrate(svr.ctx); err != nil {
|
|
|
|
return
|
|
|
|
}
|
2024-12-12 11:45:03 +08:00
|
|
|
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
|
|
|
|
}
|