95 lines
2.3 KiB
Go
95 lines
2.3 KiB
Go
package api
|
|
|
|
import (
|
|
"easyvqd/internal/conf"
|
|
"git.lnton.com/lnton/pkg/reason"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/ixugo/goddd/pkg/web"
|
|
"github.com/jinzhu/copier"
|
|
"github.com/pelletier/go-toml/v2"
|
|
"io"
|
|
"log/slog"
|
|
"strconv"
|
|
"sync"
|
|
)
|
|
|
|
var confMutex sync.Mutex
|
|
|
|
type ConfigAPI struct {
|
|
cfg *conf.Bootstrap
|
|
uc *Usecase
|
|
}
|
|
|
|
func registerConfig(g gin.IRouter, api ConfigAPI, handler ...gin.HandlerFunc) {
|
|
group := g.Group("/api/configs", handler...)
|
|
//group.GET("", api.getToml)
|
|
//group.PUT("", api.editToml)
|
|
|
|
group.GET("/base", web.WarpH(api.getBase))
|
|
group.PUT("/base", web.WarpH(api.editBase))
|
|
|
|
}
|
|
|
|
type getBaseOutput conf.VqdConfig
|
|
type editBaseInput conf.VqdConfig
|
|
|
|
func (uc *ConfigAPI) editBase(c *gin.Context, in *editBaseInput) (any, error) {
|
|
uc.cfg.VqdConfig.FrmNum = in.FrmNum
|
|
uc.cfg.VqdConfig.SaveDay = in.SaveDay
|
|
uc.cfg.VqdConfig.IsDeepLearn = in.IsDeepLearn
|
|
conf.WriteConfig(uc.cfg, uc.cfg.ConfigDirPath())
|
|
return in, nil
|
|
}
|
|
func (uc *ConfigAPI) getBase(_ *gin.Context, _ *struct{}) (getBaseOutput, error) {
|
|
confMutex.Lock()
|
|
defer confMutex.Unlock()
|
|
|
|
return getBaseOutput{
|
|
FrmNum: uc.cfg.VqdConfig.FrmNum,
|
|
IsDeepLearn: uc.cfg.VqdConfig.IsDeepLearn,
|
|
SaveDay: uc.cfg.VqdConfig.SaveDay,
|
|
}, nil
|
|
}
|
|
func (uc *ConfigAPI) getToml(c *gin.Context) {
|
|
c.Header("Content-Type", "application/toml")
|
|
if err := toml.NewEncoder(c.Writer).Encode(uc.uc.Conf); err != nil {
|
|
slog.Error("获取配置失败", "err", err)
|
|
return
|
|
}
|
|
}
|
|
|
|
func (uc *ConfigAPI) editToml(c *gin.Context) {
|
|
b, err := io.ReadAll(io.LimitReader(c.Request.Body, 1024*20))
|
|
if err != nil {
|
|
web.Fail(c, reason.ErrBadRequest.SetMsg(err.Error()))
|
|
return
|
|
}
|
|
if len(b) <= 10 {
|
|
web.Fail(c, reason.ErrBadRequest.SetMsg("错误的文件"))
|
|
return
|
|
}
|
|
|
|
data, err := strconv.Unquote(string(b))
|
|
if err != nil {
|
|
web.Fail(c, reason.ErrBadRequest.SetMsg(err.Error()))
|
|
return
|
|
}
|
|
|
|
var cfg conf.Bootstrap
|
|
if err := toml.Unmarshal([]byte(data), &cfg); err != nil {
|
|
web.Fail(c, reason.ErrBadRequest.SetMsg(err.Error()))
|
|
return
|
|
}
|
|
|
|
if err := copier.Copy(uc.uc.Conf, cfg); err != nil {
|
|
web.Fail(c, reason.ErrServer.SetMsg(err.Error()))
|
|
return
|
|
}
|
|
if err := conf.WriteConfig(uc.uc.Conf, uc.uc.Conf.ConfigDirPath()); err != nil {
|
|
web.Fail(c, reason.ErrServer.SetMsg(err.Error()))
|
|
return
|
|
}
|
|
|
|
web.Success(c, gin.H{"msg": "ok"})
|
|
}
|