From 231e0aaf517dda1b3ed9b33a9521f61335650a59 Mon Sep 17 00:00:00 2001 From: evlic Date: Sat, 13 May 2023 01:27:48 +0800 Subject: [PATCH] =?UTF-8?q?feat(update):=20=E2=9C=A8=20sync=20command=20wi?= =?UTF-8?q?th=20project=20latest?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 +- Makefile | 60 ++++++++++++++++++++ cmd/init/db.go | 77 ------------------------- cmd/{init => inits}/common.go | 2 +- cmd/{init => inits}/conf.go | 2 +- cmd/inits/db.go | 68 +++++++++++++++++++++++ cmd/{init => inits}/logger.go | 2 +- cmd/inits/service.go | 55 ++++++++++++++++++ cmd/root.go | 3 +- cmd/svr.go | 73 +++++++++++------------- go.mod | 12 ++-- go.sum | 36 ++++++++++-- internal/dao/interface.go | 5 ++ internal/server/init.go | 43 +++++++++----- internal/server/router.go | 102 ++++++++++++++++------------------ internal/server/server.go | 62 +++++++++------------ internal/server/web.go | 42 -------------- internal/service/interface.go | 5 ++ 18 files changed, 374 insertions(+), 278 deletions(-) create mode 100644 Makefile delete mode 100644 cmd/init/db.go rename cmd/{init => inits}/common.go (98%) rename cmd/{init => inits}/conf.go (99%) create mode 100644 cmd/inits/db.go rename cmd/{init => inits}/logger.go (99%) create mode 100644 cmd/inits/service.go create mode 100644 internal/dao/interface.go delete mode 100644 internal/server/web.go create mode 100644 internal/service/interface.go diff --git a/.gitignore b/.gitignore index 2e70d46..270eb37 100644 --- a/.gitignore +++ b/.gitignore @@ -39,4 +39,5 @@ /logs/ */logs/ -/conf/ \ No newline at end of file +/conf/ +/bin \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..6e4ca08 --- /dev/null +++ b/Makefile @@ -0,0 +1,60 @@ +## 编译器 +#GO=go +# +## 编译选项 +#GOFLAGS=-v + +NODE=npm + +# 源文件 +SRC=main.go + +NAME=demo-server + +# 目标文件 +BIN=bin/$(NAME) +WEB_PATH=gui +WEB_DST=../internal/server/ext/web + +################ 构建并启动 ######################## +run-web: b-web b-dev run +dev: b-dev run + +test: build test-run + +################ 构建 ############################# +build: + go build -o $(BIN) $(SRC) + +b-web: + cd $(WEB_PATH) && $(NODE) install && $(NODE) run build \ + && rm -rf $(WEB_DST) && mv dist $(WEB_DST) + +b-dev: + go build -o $(BIN) -tags "web swag" $(SRC) + +#### 辅助工具 ###################################### +swag-install: + go install github.com/swaggo/swag/cmd/swag@latest + +swag: + swag fmt + swag init + +############## 启动 ############################# +run: + $(BIN) svr + +# 测试 +test-run: + $(BIN) --conf test/ + +# 清除 +clean: + rm -rf $(BIN) + +clean-app: + rm -rf ./app + +clean-web: + rm -rf $(WEB_DST) \ No newline at end of file diff --git a/cmd/init/db.go b/cmd/init/db.go deleted file mode 100644 index 05956c1..0000000 --- a/cmd/init/db.go +++ /dev/null @@ -1,77 +0,0 @@ -package init - -//import ( -// "btdp-agent-admin/internal/config" -// "btdp-agent-admin/internal/dao" -// "btdp-agent-admin/internal/dao/db" -// "btdp-agent-admin/internal/dao/group" -// "btdp-agent-admin/internal/dao/instance" -// "btdp-agent-admin/internal/dao/log" -// "btdp-agent-admin/internal/model" -//) -// -//var ( -// d *daoPolymer -//) -// -//func getDaoPolymer() dao.Interface { -// return d -//} -// -//type daoPolymer struct { -// cli *db.Cli -// group group.Dao -// agent instance.Dao -// log log.Dao -//} -// -//func initDaoPolymer(cli *db.Cli) { -// d = &daoPolymer{ -// cli: cli, -// group: group.New(cli), -// agent: instance.New(cli), -// log: log.New(cli), -// } -//} -// -//func (d *daoPolymer) GetGroupDao() group.Dao { -// return d.group -//} -// -//func (d *daoPolymer) GetInstanceDao() instance.Dao { -// return d.agent -//} -// -//func (d *daoPolymer) GetLogDao() log.Dao { -// return d.log -//} -// -//// 初始化数据库,通过 getDaoPolymer 得到聚合体 -//func initDB() (err error) { -// cfg := config.Get() -// -// if cfg == nil || cfg.DB == nil { -// return ErrorInitFundamental -// } -// -// var ( -// cli *db.Cli -// cfgDB = cfg.DB -// ) -// -// if cli, err = db.New(cfgDB); err != nil { -// return -// } -// -// initDaoPolymer(cli) -// return -//} -// -//func initDBTables() (err error) { -// orm := d.cli.Orm() -// err = orm.Exec(model.DBSQLInit).Error -// if config.Get().DB.Type == model.DBTypeSQLITE { -// orm.Exec(model.DBSQLConfigSQLite) -// } -// return -//} diff --git a/cmd/init/common.go b/cmd/inits/common.go similarity index 98% rename from cmd/init/common.go rename to cmd/inits/common.go index be6844f..27150cf 100644 --- a/cmd/init/common.go +++ b/cmd/inits/common.go @@ -1,4 +1,4 @@ -package init +package inits import ( "fmt" diff --git a/cmd/init/conf.go b/cmd/inits/conf.go similarity index 99% rename from cmd/init/conf.go rename to cmd/inits/conf.go index 0a1a96b..2bb09b0 100644 --- a/cmd/init/conf.go +++ b/cmd/inits/conf.go @@ -1,4 +1,4 @@ -package init +package inits import ( "demo-server/internal/config" diff --git a/cmd/inits/db.go b/cmd/inits/db.go new file mode 100644 index 0000000..9dbf39b --- /dev/null +++ b/cmd/inits/db.go @@ -0,0 +1,68 @@ +package inits + +import ( + "demo-server/internal/dao" +) + +var ( + d *daoPolymer +) + +func getDaoPolymer() dao.Interface { + return d +} + +type daoPolymer struct { + +} + +func initDaoPolymer() { + d = &daoPolymer{ + //cli: cli, + //group: group.New(cli), + //agent: instance.New(cli), + //log: log.New(cli), + } +} + +//func (d *daoPolymer) GetGroupDao() group.Dao { +// return d.group +//} +// +//func (d *daoPolymer) GetInstanceDao() instance.Dao { +// return d.agent +//} +// +//func (d *daoPolymer) GetLogDao() log.Dao { +// return d.log +//} + +// 初始化数据库,通过 getDaoPolymer 得到聚合体 +func initDB() (err error) { + //cfg := config.Get() + // + //if cfg == nil || cfg.DB == nil { + // return ErrorInitFundamental + //} + // + //var ( + // cli *db.Cli + // cfgDB = cfg.DB + //) + // + //if cli, err = db.New(cfgDB); err != nil { + // return + //} + // + //initDaoPolymer(cli) + return +} + +func initDBTables() (err error) { + //orm := d.cli.Orm() + //err = orm.Exec(model.DBSQLInit).Error + //if config.Get().DB.Type == model.DBTypeSQLITE { + // orm.Exec(model.DBSQLConfigSQLite) + //} + return +} diff --git a/cmd/init/logger.go b/cmd/inits/logger.go similarity index 99% rename from cmd/init/logger.go rename to cmd/inits/logger.go index 2710382..19d6c2d 100644 --- a/cmd/init/logger.go +++ b/cmd/inits/logger.go @@ -1,4 +1,4 @@ -package init +package inits import ( "demo-server/internal/config" diff --git a/cmd/inits/service.go b/cmd/inits/service.go new file mode 100644 index 0000000..a75077c --- /dev/null +++ b/cmd/inits/service.go @@ -0,0 +1,55 @@ +package inits + +import ( + "demo-server/internal/config" + "demo-server/internal/service" + + //"demo-server/internal/manager/kafka" + //"demo-server/internal/service" + //"demo-server/internal/service/group" + //"demo-server/internal/service/instance" +) + +var ( + svc *servicePolymer +) + +type servicePolymer struct { + //group *group.Service + //instance *instance.Service +} +// +//func (s servicePolymer) GetGroupService() *group.Service { +// return s.group +//} +// +//func (s servicePolymer) GetInstanceService() *instance.Service { +// return s.instance +//} +// +//func (s servicePolymer) SetKafka(ka kafka.Manager) { +// s.GetInstanceService().SetKafka(ka) +// s.GetGroupService().SetKafka(ka) +//} + +func GetSvcPolymer() service.Interface { + return svc +} + +func initService() (err error) { + dp := getDaoPolymer() + conf := config.Get() + + if dp == nil || conf == nil { + err = ErrorInitFundamental + return + } + + svc = &servicePolymer{ + //instance: instance.New(dp), + //group: group.New(dp), + } + + //svc.group.SetISvc(svc.instance) + return +} diff --git a/cmd/root.go b/cmd/root.go index 4f33256..bbc3250 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -1,6 +1,7 @@ package cmd import ( + "demo-server/cmd/inits" "os" "github.com/spf13/cobra" @@ -34,7 +35,7 @@ func Execute() { func init() { cobra.OnInitialize(func() { - err := InitFundamental() + err := inits.InitFundamental() if err != nil { panic(err) } diff --git a/cmd/svr.go b/cmd/svr.go index 64b091d..e7c9efa 100644 --- a/cmd/svr.go +++ b/cmd/svr.go @@ -2,71 +2,70 @@ package cmd import ( "context" + "demo-server/cmd/inits" + "demo-server/internal/config" "demo-server/internal/model" "demo-server/internal/server" + "fmt" "github.com/spf13/cobra" "go.uber.org/zap" - "net/http" "os" "os/signal" "syscall" ) + // svrCmd represents the svr command // go build -ldflags "-w -s" -o packet-admin.out . && ./packet-admin.out svr var svrCmd = &cobra.Command{ Use: "svr", Short: "server run", - Long: `server run,default on ` + model.DefaultServerAddress, - Run: RunSvr, + Long: `server run,default on ` + model.DefaultServerAddress + ` + flag: -d don't run stub' +`, + Run: runSvr, } func init() { rootCmd.AddCommand(svrCmd) } -// RunSvr 启动 server -func RunSvr(_ *cobra.Command, _ []string) { - if err := InitServer(); err != nil { - zap.S().Panicf("init svr err, cause: %v", err) +// runSvr 启动 server +func runSvr(_ *cobra.Command, _ []string) { + if err := inits.InitServer(); err != nil { + panic(fmt.Errorf("init svr err, cause: %w", err)) } - - runHttpServer() + runServer() } -func runHttpServer() { - var httpServer *http.Server +func runServer() { + conf := config.Get() + svc := inits.GetSvcPolymer() + if conf == nil || conf.Svr == nil || svc == nil { + zap.S().Error("server conf nil!", inits.ErrorInitFundamental) + return + } + ctx, cancel := context.WithCancel(context.Background()) - defer func() { - if httpServer == nil { - return - } - err := httpServer.Shutdown(ctx) + //ka := kafka.NewManager(ctx, conf.Kafka) + //svc.SetKafka(ka) + svr := server.New(conf) - if err != nil { - zap.S().Errorf("server stop error(%v)", err) + go svr.Run() + svr.SvrRunSuccessMsg() + + defer func() { + if err := svr.Shutdown(ctx); err != nil { + zap.S().Error(err) } }() - defer func() { - select { - case <-ctx.Done(): - default: - cancel() - } - }() - - config := config.GetConfig() - if config == nil || config.Svr == nil { - zap.S().Panic("server config nil!", ErrorInitFundamental) - } - httpServer = server.RunServer(config, cancel) - - SignalWatchWithContext(ctx, cancel) + signalWatch(ctx, cancel) } -func SignalWatchWithContext(ctx context.Context, cancel context.CancelFunc) { +// signalWatch 阻塞主进程 +func signalWatch(ctx context.Context, cancel context.CancelFunc) { sigterm := make(chan os.Signal, 1) signal.Notify(sigterm, syscall.SIGINT, syscall.SIGTERM) select { @@ -77,9 +76,3 @@ func SignalWatchWithContext(ctx context.Context, cancel context.CancelFunc) { zap.S().Infof("terminating: via signal") } } - -func SignalWatch() { - sigterm := make(chan os.Signal, 1) - sig := <-sigterm - zap.S().Infof("terminating: via signal, %v", sig) -} diff --git a/go.mod b/go.mod index 5d8cd7c..973c3e7 100644 --- a/go.mod +++ b/go.mod @@ -7,11 +7,14 @@ require ( github.com/gin-contrib/pprof v1.4.0 github.com/gin-contrib/zap v0.1.0 github.com/gin-gonic/gin v1.8.1 + github.com/goccy/go-json v0.10.0 github.com/google/uuid v1.3.0 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.14.0 + github.com/segmentio/kafka-go v0.4.40 github.com/spf13/cobra v1.6.1 github.com/spf13/viper v1.14.0 + github.com/swaggo/files v1.0.1 github.com/vearutop/statigz v1.2.0 go.uber.org/zap v1.24.0 gopkg.in/natefinch/lumberjack.v2 v2.0.0 @@ -26,13 +29,13 @@ require ( github.com/go-playground/locales v0.14.0 // indirect github.com/go-playground/universal-translator v0.18.0 // indirect github.com/go-playground/validator/v10 v10.11.1 // indirect - github.com/goccy/go-json v0.10.0 // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.0.1 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/compress v1.15.9 // indirect github.com/leodido/go-urn v1.2.1 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mattn/go-isatty v0.0.16 // indirect @@ -42,6 +45,7 @@ require ( github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml v1.9.5 // indirect github.com/pelletier/go-toml/v2 v2.0.6 // indirect + github.com/pierrec/lz4/v4 v4.1.15 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.37.0 // indirect github.com/prometheus/procfs v0.8.0 // indirect @@ -56,9 +60,9 @@ require ( go.uber.org/atomic v1.10.0 // indirect go.uber.org/multierr v1.8.0 // indirect golang.org/x/crypto v0.4.0 // indirect - golang.org/x/net v0.4.0 // indirect - golang.org/x/sys v0.3.0 // indirect - golang.org/x/text v0.5.0 // indirect + golang.org/x/net v0.7.0 // indirect + golang.org/x/sys v0.5.0 // indirect + golang.org/x/text v0.7.0 // indirect google.golang.org/protobuf v1.28.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/go.sum b/go.sum index 203cf4f..e66585c 100644 --- a/go.sum +++ b/go.sum @@ -200,6 +200,8 @@ github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/X github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.15.9 h1:wKRjX6JRtDdrE9qwa4b/Cip7ACOshUI4smpCQanqjSY= +github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= @@ -237,6 +239,8 @@ github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCko github.com/pelletier/go-toml/v2 v2.0.1/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOjgMj2KwnJFUo= github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU= github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= +github.com/pierrec/lz4/v4 v4.1.15 h1:MO0/ucJhngq7299dKLwIMtgTfbkoSPF6AoMYDd8Q4q0= +github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -276,6 +280,8 @@ github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTE github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/segmentio/kafka-go v0.4.40 h1:sszW7c0/uyv7+VcTW5trx2ZC7kMWDTxuR/6Zn8U1bm8= +github.com/segmentio/kafka-go v0.4.40/go.mod h1:naFEZc5MQKdeL3W6NkZIAn48Y6AazqjRFDhnXeg3h94= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= @@ -307,16 +313,25 @@ github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKs github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/subosito/gotenv v1.4.1 h1:jyEFiXpy21Wm81FBN71l9VoMMV8H8jG+qIK3GCpY6Qs= github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= +github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE= +github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg= github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M= github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0= github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY= github.com/vearutop/statigz v1.2.0 h1:GGBHsDF3KnJBE6UmhvYdRg58ok9boQX/R+nUGRWPMXM= github.com/vearutop/statigz v1.2.0/go.mod h1:jqlOPvLAdiQktMtYAkyguI3Ee0FA26iXKeEx2pS5l88= +github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= +github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -350,6 +365,7 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.4.0 h1:UVQgzMY87xqpKNgb+kDsll2Igd33HszWHFLmpaRMq/8= @@ -388,6 +404,7 @@ golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -426,8 +443,9 @@ golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/net v0.4.0 h1:Q5QPcMlvfxFTAPV0+07Xz/MpK9NTXu2VDUuy0FeMfaU= -golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -450,6 +468,7 @@ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -499,12 +518,15 @@ golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ= -golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -513,8 +535,9 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM= -golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -566,6 +589,7 @@ golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/internal/dao/interface.go b/internal/dao/interface.go new file mode 100644 index 0000000..e3b9d25 --- /dev/null +++ b/internal/dao/interface.go @@ -0,0 +1,5 @@ +package dao + +type Interface interface { + +} diff --git a/internal/server/init.go b/internal/server/init.go index 10ef189..f2a7f7f 100644 --- a/internal/server/init.go +++ b/internal/server/init.go @@ -2,22 +2,32 @@ package server import ( "demo-server/internal/model" - "github.com/gin-contrib/pprof" + "demo-server/internal/server/ext" + "demo-server/pkg/log" gzap "github.com/gin-contrib/zap" "github.com/gin-gonic/gin" "go.uber.org/zap" - "runtime" + "net/http" "time" ) type handler func(s *Server) -func (s *Server) Init(hs ...handler) { +func (s *Server) init(hs ...handler) { for _, h := range hs { h(s) } } +func (s *Server) Init() { + s.init( + InitEngine, // gin + InitHttpSvr, // http + InitExt, // ext + InitRouter, // router + ) +} + func InitEngine(s *Server) { config := s.cfg.Svr if config.Address == "" { @@ -29,11 +39,9 @@ func InitEngine(s *Server) { } eng := gin.New() - s.Engine = eng + s.engine = eng - gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { - zap.S().Infof("%v\t%v\t%v\t%v", httpMethod, absolutePath, handlerName, nuHandlers) - } + gin.DebugPrintRouteFunc = log.GinRouter eng.Use(gzap.Ginzap(zap.L(), time.RFC3339, true)) eng.Use(gzap.RecoveryWithZap(zap.L(), true)) @@ -42,12 +50,21 @@ func InitEngine(s *Server) { } func InitRouter(s *Server) { - if s.cfg.Svr.PprofOn { - runtime.SetMutexProfileFraction(1) - runtime.SetBlockProfileRate(1) - pprof.Register(s.Engine) + s.router(s.engine) +} + +func InitExt(s *Server) { + ext.Init(s.engine, s.GetCfg()) +} + +func InitHttpSvr(s *Server) { + httpSvr := &http.Server{ + Addr: s.cfg.Svr.Address, + Handler: s.engine, + ReadTimeout: 120 * time.Second, + WriteTimeout: 120 * time.Second, + MaxHeaderBytes: 1 << 20, } - API(s) - GUI(s) + s.httpSvr = httpSvr } diff --git a/internal/server/router.go b/internal/server/router.go index fc6e75b..45ead73 100644 --- a/internal/server/router.go +++ b/internal/server/router.go @@ -2,65 +2,57 @@ package server import ( "github.com/gin-gonic/gin" - "github.com/prometheus/client_golang/prometheus/promhttp" - "github.com/vearutop/statigz" - "go.uber.org/zap" - "io" - "io/fs" - "net/http" ) -func GUI(s *Server) { - r := s.Engine - webFS, err := fs.Sub(webRootFS, "web") - if err != nil { - zap.S().Panic("init gui err, cause: ", err) - } - - guiStaticResource(r, webFS) - guiIndexHTML(r, webFS) -} - -func guiStaticResource(r *gin.Engine, sfs fs.FS) { - - const ( - staticPrefix = "/assets" - stripPrefix = "" - ) - - staticResource := http.StripPrefix(stripPrefix, statigz.FileServer(sfs.(fs.ReadDirFS))) - r.GET(staticPrefix+"/*w", func(c *gin.Context) { - staticResource.ServeHTTP(c.Writer, c.Request) - }) - r.GET("/favicon.ico", func(c *gin.Context) { - staticResource.ServeHTTP(c.Writer, c.Request) - }) -} - -func guiIndexHTML(r *gin.Engine, sfs fs.FS) { - var indexHTML []byte +func (s *Server) router(e *gin.Engine) { + base := e.Group("/api") + apiV1 := base.Group("/v1") { - const indexFileName = "index.html" - index, err := sfs.Open(indexFileName) - if err != nil { - zap.S().Panicf("open [%s] err! cause: %e", indexFileName, err) - } - indexHTML, err = io.ReadAll(index) - if err != nil { - zap.S().Panicf("read [%s] err! cause: %e", indexFileName, err) - } + apiV1.GET("/ping", func(c *gin.Context) { + c.String(200, "alive") + }) } - r.GET("/", html(indexHTML)) + //s.bindGroupRouter(apiV1.Group("/group")) + //s.bindAgentRouter(apiV1.Group("/instance")) } -func API(s *Server) { - r := s.Engine - r.GET("/metrics", gin.WrapH(promhttp.Handler())) - - apiGroup := r.Group("/api") - { - v1 := apiGroup.Group("/v1") - _ = v1 - } -} +//func (s *Server) bindGroupRouter(r *gin.RouterGroup) { +// group := s.group +// +// r.GET("/list", api(group.List())) +// r.POST("/new", api(group.New())) +// +// byID := r.Group("/:id") +// // manage relation +// byID.PUT("/join", api(group.Join())) +// byID.DELETE("/delete", api(group.Delete())) +// byID.GET("/list", api(group.ListInstance())) +// // batch operation +// byID.POST("/up", api(group.Up())) +// byID.POST("/down", api(group.Down())) +// byID.POST("/update", api(group.Update())) +// // config +// byID.GET("/config", api(group.GetConfig())) +// byID.POST("/config", api(group.SaveConfig())) +// byID.POST("/save", api(group.Save())) +//} +// +//func (s *Server) bindAgentRouter(r *gin.RouterGroup) { +// agent := s.instance +// +// r.POST("/up", api(agent.BatchUp())) +// r.POST("/down", api(agent.BatchDown())) +// r.POST("/update", api(agent.Update())) +// r.DELETE("/delete", api(agent.Delete())) +// +// byID := r.Group("/:id") +// byID.GET("/config", api(agent.GetConfig())) +// byID.GET("/info", api(agent.Info())) +// byID.GET("/log", api(agent.Log())) +// // operation +// byID.POST("/up", api(agent.Up())) +// byID.POST("/down", api(agent.Down())) +// byID.POST("/update", api(agent.Update())) +// byID.DELETE("/delete", api(agent.Delete())) +//} diff --git a/internal/server/server.go b/internal/server/server.go index 357b600..1213e93 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -2,18 +2,17 @@ package server import ( "context" - "demo-server/internal/model" - "demo-server/internal/model/server" + "demo-server/internal/config" "github.com/gin-gonic/gin" "go.uber.org/zap" "net" "net/http" - "time" ) type Server struct { - cfg *model.Configuration - *gin.Engine + cfg *config.Configuration + engine *gin.Engine + httpSvr *http.Server } var ( @@ -24,53 +23,40 @@ func GetSvr() *Server { return svr } -func NewSvr(cfg *model.Configuration) *Server { +func New(cfg *config.Configuration) *Server { s := &Server{ cfg: cfg, } - s.Init(InitEngine, InitRouter) + s.Init() svr = s return s } -// RunServer 如果初始化失败 cancel -func RunServer(cfg *model.Configuration, cancel context.CancelFunc) (httpServer *http.Server) { - s := NewSvr(cfg) - - svrConfig := cfg.Svr - defer func() { - if r := recover(); r != nil { - cancel() - } else { - serverRunSuccess(svrConfig) - } - }() - - httpSvr := &http.Server{ - Addr: svrConfig.Address, - Handler: s.Engine, - ReadTimeout: 120 * time.Second, - WriteTimeout: 120 * time.Second, - MaxHeaderBytes: 1 << 20, +func (s *Server) Run() { + if err := s.httpSvr.ListenAndServe(); err != nil && err != http.ErrServerClosed { + panic(err) } +} - httpServer = httpSvr - - go func() { - if err := httpSvr.ListenAndServe(); err != nil && err != http.ErrServerClosed { - zap.S().Panicf("run server err! %v", err) - } - }() +func (s *Server) Shutdown(ctx context.Context) (err error) { + if s.httpSvr == nil { + return + } + err = s.httpSvr.Shutdown(ctx) return } -func serverRunSuccess(svr *server.Config) { +func (s *Server) SvrRunSuccessMsg() { + svr := s.cfg.Svr printIPInfo := func(adds ...string) { info := "svr running, via" for _, add := range adds { info += "\n\thttp://" + add } + if len(adds) > 0 { + info += "\n\tvia doc at http://" + adds[0] + "/swagger" + } zap.S().Info(info) } ip, port, _ := net.SplitHostPort(svr.Address) @@ -78,7 +64,7 @@ func serverRunSuccess(svr *server.Config) { if net.ParseIP(ip).IsUnspecified() && err == nil { var successAddress []string for _, addr := range adders { - if ipNet, ok := addr.(*net.IPNet); ok { + if ipNet, ok := addr.(*net.IPNet); ok && (ipNet.IP.IsPrivate()) { successAddress = append(successAddress, net.JoinHostPort(ipNet.IP.String(), port)) } } @@ -88,8 +74,12 @@ func serverRunSuccess(svr *server.Config) { } } +func (s *Server) GetCfg() *config.Configuration { + return s.cfg +} + // Dispatch 当配置文件更新的时候可以去调用 // 目前使用的全局 config 指针的方式如果发生更改,理论上 server 关联的 model 内置指针对象也会被更改 // 需要重新初始化的部分将由本函数予以实现 -func (s *Server) Dispatch(_ *model.Configuration) { +func (s *Server) Dispatch(_ *config.Configuration) { } diff --git a/internal/server/web.go b/internal/server/web.go deleted file mode 100644 index d9b657c..0000000 --- a/internal/server/web.go +++ /dev/null @@ -1,42 +0,0 @@ -package server - -import ( - "crypto/md5" - "demo-server/pkg" - "embed" - "fmt" - "github.com/gin-gonic/gin" - "net/http" - "strings" -) - -/* - embed static web learn from opensource license MIT - see "github.com/v2rayA/v2rayA/server/router/index.go" -*/ - -// webRootFS 嵌入静态文件 -// -//go:embed web -var webRootFS embed.FS - -// html 缓存 HTML 页面 -func html(html []byte) func(ctx *gin.Context) { - etag := fmt.Sprintf("W/%x", md5.Sum(html)) - h := pkg.B2S(html) - return func(ctx *gin.Context) { - if ctx.IsAborted() { - return - } - ctx.Header("Content-Type", "text/html; charset=utf-8") - ctx.Header("Cache-Control", "public, must-revalidate") - ctx.Header("ETag", etag) - if match := ctx.GetHeader("If-None-Match"); match != "" { - if strings.Contains(match, etag) { - ctx.Status(http.StatusNotModified) - return - } - } - ctx.String(http.StatusOK, h) - } -} diff --git a/internal/service/interface.go b/internal/service/interface.go new file mode 100644 index 0000000..ddc1214 --- /dev/null +++ b/internal/service/interface.go @@ -0,0 +1,5 @@ +package service + +type Interface interface { + +}