ソースを参照

完成项目demo的编写

yjp 1 年間 前
コミット
6bef62e26d

+ 18 - 5
application/application.go

@@ -5,6 +5,7 @@ import (
 	"git.sxidc.com/go-framework/baize/binding"
 	"git.sxidc.com/go-framework/baize/infrastructure"
 	"git.sxidc.com/go-framework/baize/infrastructure/logger"
+	"git.sxidc.com/go-tools/utils/strutils"
 )
 
 type App struct {
@@ -61,13 +62,25 @@ func (app *App) Logger() *logger.Logger {
 	return app.loggerInstance
 }
 
+const (
+	RouterRoot   = "root"
+	RouterPrefix = "prefix"
+)
+
 // Binder 创建Binder
-func (app *App) Binder(routerVersion string) *binding.Binder {
+func (app *App) Binder(routerType string, version string) *binding.Binder {
 	var router api.Router
-	if routerVersion == "" {
-		router = app.apiInstance.RootRouter()
-	} else {
-		router = app.apiInstance.PrefixRouter().VersionedRouter(routerVersion)
+	switch routerType {
+	case RouterRoot:
+		router = app.Api().RootRouter()
+	case RouterPrefix:
+		router = app.Api().PrefixRouter()
+	default:
+		router = app.Api().PrefixRouter()
+	}
+
+	if strutils.IsStringNotEmpty(version) {
+		router = router.VersionedRouter(version)
 	}
 
 	return binding.NewBinder(router, app.infrastructureInstance)

+ 19 - 0
application/info.go

@@ -0,0 +1,19 @@
+package application
+
+type InfoIDField struct {
+	ID string `json:"id" sqlresult:"column:id"`
+}
+
+type InfoTenantIDField struct {
+	TenantID string `json:"tenantId" sqlresult:"column:tenant_id"`
+}
+
+type InfoUserIDFields struct {
+	CreateUserID     string `json:"createUserId" sqlresult:"column:create_user_id;"`
+	LastUpdateUserID string `json:"lastUpdateUserId" sqlresult:"column:last_update_user_id;"`
+}
+
+type InfoTimeFields struct {
+	CreatedTime     string `json:"createdTime" sqlresult:"column:created_time;parseTime:'2006-01-02 15:04:05'"`
+	LastUpdatedTime string `json:"lastUpdatedTime" sqlresult:"column:last_updated_time;parseTime:'2006-01-02 15:04:05'"`
+}

+ 5 - 3
examples/example_domain/class/info.go

@@ -1,10 +1,12 @@
 package class
 
-import "git.sxidc.com/go-framework/baize/examples/example_domain/common"
+import (
+	"git.sxidc.com/go-framework/baize/application"
+)
 
 type Info struct {
-	common.InfoIDField
+	application.InfoIDField
 	Name       string `json:"name" sqlresult:"column:name"`
 	StudentNum int    `json:"studentNum" sqlresult:"column:student_num"`
-	common.InfoTimeFields
+	application.InfoTimeFields
 }

+ 0 - 10
examples/example_domain/common/info.go

@@ -1,10 +0,0 @@
-package common
-
-type InfoIDField struct {
-	ID string `json:"id" sqlresult:"column:id"`
-}
-
-type InfoTimeFields struct {
-	CreatedTime     string `json:"created_time" sqlresult:"column:created_time;parseTime:'2006-01-02 15:04:05'"`
-	LastUpdatedTime string `json:"last_updated_time" sqlresult:"column:last_updated_time;parseTime:'2006-01-02 15:04:05'"`
-}

+ 1 - 1
examples/examples/binding/main.go

@@ -46,7 +46,7 @@ func main() {
 		PrefixRouter().
 		RegisterVersionedRouter("v1")
 
-	entity.BindSimple[class.Info](app.Binder("v1"), &entity.Simple[class.Info]{
+	entity.BindSimple[class.Info](app.Binder(application.RouterPrefix, "v1"), &entity.Simple[class.Info]{
 		Entity:             &class.Entity{},
 		TableName:          class.TableName,
 		DomainPath:         "/class",

+ 1 - 1
examples/examples/binding_ds/main.go

@@ -45,7 +45,7 @@ func main() {
 		PrefixRouter().
 		RegisterVersionedRouter("v1")
 
-	entity.BindSimple[class.Info](app.Binder("v1"), &entity.Simple[class.Info]{
+	entity.BindSimple[class.Info](app.Binder(application.RouterPrefix, "v1"), &entity.Simple[class.Info]{
 		Entity:             &class.Entity{},
 		TableName:          class.TableName,
 		DomainPath:         "/class",

+ 72 - 0
examples/examples/project/application/application.go

@@ -0,0 +1,72 @@
+package application
+
+import (
+	"git.sxidc.com/go-framework/baize"
+	"git.sxidc.com/go-framework/baize/application"
+	"git.sxidc.com/go-framework/baize/examples/examples/project/application/service"
+	"git.sxidc.com/go-framework/baize/examples/examples/project/config"
+)
+
+var appInstance *application.App
+
+func NewApp() {
+	if appInstance != nil {
+		return
+	}
+
+	appInstance = baize.NewApplication(config.GetConfig().ApplicationConfig)
+
+	// 注册Router
+	appInstance.Api().PrefixRouter().RegisterVersionedRouter("v1")
+}
+
+func DestroyApp() {
+	if appInstance == nil {
+		return
+	}
+
+	baize.DestroyApplication(appInstance)
+}
+
+type Service interface {
+	Init(appInstance *application.App) error
+	Destroy() error
+}
+
+var applications = []Service{
+	&service.Version{}, &service.Class{},
+}
+
+func Start() error {
+	// 初始化服务
+	for _, app := range applications {
+		err := app.Init(appInstance)
+		if err != nil {
+			return err
+		}
+	}
+
+	err := appInstance.Start()
+	if err != nil {
+		return err
+	}
+
+	return nil
+}
+
+func Finish() error {
+	err := appInstance.Finish()
+	if err != nil {
+		return err
+	}
+
+	// 销毁服务
+	for _, app := range applications {
+		err := app.Destroy()
+		if err != nil {
+			return err
+		}
+	}
+
+	return nil
+}

+ 83 - 0
examples/examples/project/application/domain/class/entity.go

@@ -0,0 +1,83 @@
+package class
+
+import (
+	"git.sxidc.com/go-framework/baize/domain"
+	"git.sxidc.com/go-tools/utils/strutils"
+	"git.sxidc.com/service-supports/fserr"
+)
+
+const (
+	TableName = "test.classes"
+)
+
+const (
+	ColumnName       = "name"
+	ColumnStudentNum = "student_num"
+)
+
+const (
+	fieldNameMaxLen = 128
+)
+
+type Entity struct {
+	domain.BaseEntity
+	Name       string `sqlmapping:"column:name" sqlresult:"column:name"`
+	StudentNum int    `sqlmapping:"column:student_num;updateClear;" sqlresult:"column:student_num"`
+	domain.TimeFields
+}
+
+func (e *Entity) DomainCNName() string {
+	return "班级"
+}
+
+func (e *Entity) ForCreate() error {
+	err := e.CheckFieldID()
+	if err != nil {
+		return err
+	}
+
+	err = e.checkFieldName()
+	if err != nil {
+		return err
+	}
+
+	return nil
+}
+
+func (e *Entity) ForUpdate() error {
+	err := e.CheckFieldID()
+	if err != nil {
+		return err
+	}
+
+	err = e.checkUpdateFields()
+	if err != nil {
+		return err
+	}
+
+	return nil
+}
+
+func (e *Entity) checkFieldName() error {
+	if strutils.IsStringEmpty(e.Name) {
+		return fserr.New(e.DomainCNName() + "名称为空")
+	}
+
+	if len(e.Name) > fieldNameMaxLen {
+		return fserr.New(e.DomainCNName() + "名称超出限定长度")
+	}
+
+	return nil
+}
+
+func (e *Entity) checkUpdateFields() error {
+	if strutils.AllBlank(e.Name) {
+		return fserr.New(e.DomainCNName() + "没有传递需要更新的字段")
+	}
+
+	if strutils.IsStringNotEmpty(e.Name) && len(e.Name) > fieldNameMaxLen {
+		return fserr.New(e.DomainCNName() + "名称超出限定长度")
+	}
+
+	return nil
+}

+ 30 - 0
examples/examples/project/application/domain/class/request_params.go

@@ -0,0 +1,30 @@
+package class
+
+import "git.sxidc.com/go-framework/baize/binding/request"
+
+type (
+	CreateJsonBody struct {
+		Name       string `json:"name" binding:"required" assign:"toField:Name"`
+		StudentNum int    `json:"studentNum" binding:"required" assign:"toField:StudentNum"`
+	}
+
+	DeletePathParams struct {
+		request.IDPath
+	}
+
+	UpdateJsonBody struct {
+		request.IDJsonBody
+		Name       string `json:"name" assign:"toField:Name"`
+		StudentNum int    `json:"studentNum" assign:"toField:StudentNum"`
+	}
+
+	QueryQueryParams struct {
+		Name       string `form:"name" assign:"toField:Name"`
+		StudentNum int    `form:"studentNum" assign:"toField:StudentNum"`
+		request.BaseQuery
+	}
+
+	GetByIDQueryParams struct {
+		request.IDQuery
+	}
+)

+ 34 - 0
examples/examples/project/application/service/class.go

@@ -0,0 +1,34 @@
+package service
+
+import (
+	"git.sxidc.com/go-framework/baize/application"
+	"git.sxidc.com/go-framework/baize/convenient/entity"
+	"git.sxidc.com/go-framework/baize/examples/example_domain/class"
+	"git.sxidc.com/go-framework/baize/examples/examples/project/application/service/service_info"
+)
+
+type Class struct{}
+
+func (app *Class) Init(appInstance *application.App) error {
+	app.v1(appInstance)
+	return nil
+}
+
+func (app *Class) Destroy() error {
+	return nil
+}
+
+func (app *Class) v1(appInstance *application.App) {
+	v1Binder := appInstance.Binder(application.RouterPrefix, "v1")
+
+	entity.BindSimple[service_info.ClassInfo](v1Binder, &entity.Simple[service_info.ClassInfo]{
+		Entity:             &class.Entity{},
+		TableName:          class.TableName,
+		DomainPath:         "/class",
+		CreateJsonBody:     &class.CreateJsonBody{},
+		DeleteQueryParams:  &class.DeletePathParams{},
+		UpdateJsonBody:     &class.UpdateJsonBody{},
+		QueryQueryParams:   &class.QueryQueryParams{},
+		GetByIDQueryParams: &class.GetByIDQueryParams{},
+	})
+}

+ 12 - 0
examples/examples/project/application/service/service_info/class.go

@@ -0,0 +1,12 @@
+package service_info
+
+import (
+	"git.sxidc.com/go-framework/baize/application"
+)
+
+type ClassInfo struct {
+	application.InfoIDField
+	Name       string `json:"name" sqlresult:"column:name"`
+	StudentNum int    `json:"studentNum" sqlresult:"column:student_num"`
+	application.InfoTimeFields
+}

+ 36 - 0
examples/examples/project/application/service/version.go

@@ -0,0 +1,36 @@
+package service
+
+import (
+	"git.sxidc.com/go-framework/baize/api"
+	"git.sxidc.com/go-framework/baize/application"
+	"git.sxidc.com/go-framework/baize/binding"
+	"git.sxidc.com/go-framework/baize/binding/request"
+	"git.sxidc.com/go-framework/baize/binding/response"
+	"git.sxidc.com/go-framework/baize/domain"
+	"git.sxidc.com/go-framework/baize/infrastructure"
+)
+
+type Version struct{}
+
+func (app *Version) Init(appInstance *application.App) error {
+	app.prefixRoot(appInstance)
+	return nil
+}
+
+func (app *Version) Destroy() error {
+	return nil
+}
+
+func (app *Version) prefixRoot(appInstance *application.App) {
+	prefixRootBinder := appInstance.Binder(application.RouterPrefix, "")
+
+	binding.GetBind(prefixRootBinder, &binding.SimpleBindItem[map[string]any]{
+		Path:         "/version",
+		ResponseFunc: response.SendMapResponse,
+		ServiceFunc: func(c *api.Context, params request.Params, objects []domain.Object, i *infrastructure.Infrastructure) (map[string]any, error) {
+			return map[string]any{
+				"version": "v1.0.0",
+			}, nil
+		},
+	})
+}

+ 71 - 0
examples/examples/project/config/config.go

@@ -0,0 +1,71 @@
+package config
+
+import (
+	"fmt"
+	"git.sxidc.com/go-framework/baize/application"
+	"git.sxidc.com/go-tools/utils/strutils"
+	"git.sxidc.com/service-supports/fslog"
+	"git.sxidc.com/service-supports/scm-sdk"
+	"gopkg.in/yaml.v3"
+	"os"
+)
+
+type Config struct {
+	ApplicationConfig application.Config
+}
+
+var conf Config
+
+func init() {
+	useSCMEnv := os.Getenv("USE_SCM")
+	if useSCMEnv == "true" {
+		initConfigFromSCM()
+	} else {
+		initConfigFromConfigFile()
+	}
+}
+
+func GetConfig() Config {
+	return conf
+}
+
+func initConfigFromSCM() {
+	scmBaseUrl := loadEnvOrPanic("SCM_BASE_URL")
+	scmNamespace := loadEnvOrPanic("SCM_NAMESPACE")
+	scmName := loadEnvOrPanic("SCM_NAME")
+
+	info, err := scm_sdk.GetCurrentConfiguration(scmBaseUrl, scmNamespace, scmName)
+	if err != nil {
+		fslog.Error(err)
+		panic(err)
+	}
+
+	err = yaml.Unmarshal([]byte(info.Content), conf)
+	if err != nil {
+		fslog.Error(err)
+		panic(err)
+	}
+
+	fslog.Info("Load config from scm finish")
+}
+
+func initConfigFromConfigFile() {
+	configFilePath := os.Getenv("CONFIG_FILE_PATH")
+	applicationConfig, err := application.LoadFromYamlFile(configFilePath)
+	if err != nil {
+		panic(err)
+	}
+
+	conf.ApplicationConfig = applicationConfig
+
+	fmt.Println("Load config file finish")
+}
+
+func loadEnvOrPanic(envName string) string {
+	envValue := os.Getenv(envName)
+	if strutils.IsStringEmpty(envValue) {
+		panic("请配置" + envName)
+	}
+
+	return envValue
+}

+ 12 - 0
examples/examples/project/deployment/config/config.yaml

@@ -0,0 +1,12 @@
+api:
+  url_prefix: example
+  port: 31000
+infrastructure:
+  database:
+    user_name: test
+    password: "123456"
+    address: localhost
+    port: 30432
+    database: test
+    max_connections: 20
+    max_idle_connections: 5

+ 80 - 0
examples/examples/project/deployment/resources/resources.yaml

@@ -0,0 +1,80 @@
+kind: Namespace
+spec:
+  name: baize
+
+---
+
+kind: DataSource
+spec:
+  type: database
+  namespace: baize
+  name: baize-binding
+  spec:
+    type: postgres
+    user_name: test
+    password: "123456"
+    address: "10.0.0.84"
+    port: "30432"
+    database: test
+    max_connections: 40
+    max_idle_connections: 10
+
+---
+
+kind: DataContainer
+spec:
+  namespace: baize
+  data_source: baize-binding
+  name: test.classes
+  spec:
+    table_name: test.classes
+    columns:
+      - name: id
+        type: varchar(32)
+        comment: id
+        primary_key: true
+      - name: name
+        type: varchar(128)
+        comment: 班名
+        not_null: true
+        index: true
+      - name: student_num
+        type: integer
+        comment: 学生数量
+        not_null: true
+        index: true
+      - name: created_time
+        type: "timestamp with time zone"
+        comment: 创建时间
+        not_null: true
+      - name: last_updated_time
+        type: "timestamp with time zone"
+        comment: 最近更新时间
+        not_null: true
+
+---
+
+kind: DataContainer
+spec:
+  namespace: baize
+  data_source: baize-binding
+  name: test.configurations
+  spec:
+    table_name: test.configurations
+    columns:
+      - name: scope
+        type: varchar(256)
+        comment: 范围
+        not_null: true
+        primary_key: true
+      - name: group
+        type: varchar(256)
+        comment: 组
+        not_null: true
+        primary_key: true
+      - name: value
+        type: varchar(256)
+        comment: 值
+        not_null: true
+        index: true
+

+ 36 - 0
examples/examples/project/main.go

@@ -0,0 +1,36 @@
+package main
+
+import (
+	"git.sxidc.com/go-framework/baize/examples/examples/project/application"
+	DEATH "github.com/vrecan/death"
+	"syscall"
+)
+
+// curl -X GET "http://localhost:31000/example/version"
+// curl -X POST -H "Content-Type: application/json" -d '{"name":"test", "studentNum": 10}' "http://localhost:31000/example/v1/class/create"
+// curl -X PUT -H "Content-Type: application/json" -d '{"id":"1a8d5cf5c4574430903e7cfcf2f13e4f", "name":"test-new"}' "http://localhost:31000/example/v1/class/update"
+// curl -X GET "http://localhost:31000/example/v1/class/query?name=test-new&pageNo=1&pageSize=1"
+// curl -X GET "http://localhost:31000/example/v1/class/get?id=1a8d5cf5c4574430903e7cfcf2f13e4f"
+// curl -X DELETE "http://localhost:31000/example/v1/class/1a8d5cf5c4574430903e7cfcf2f13e4f/delete"
+
+func main() {
+	application.NewApp()
+	defer application.DestroyApp()
+
+	go func() {
+		err := application.Start()
+		if err != nil {
+			panic(err)
+		}
+	}()
+
+	defer func() {
+		err := application.Finish()
+		if err != nil {
+			panic(err)
+		}
+	}()
+
+	death := DEATH.NewDeath(syscall.SIGINT, syscall.SIGTERM)
+	_ = death.WaitForDeath()
+}

+ 1 - 0
go.mod

@@ -6,6 +6,7 @@ require (
 	git.sxidc.com/go-tools/utils v1.5.11
 	git.sxidc.com/service-supports/fserr v0.3.5
 	git.sxidc.com/service-supports/fslog v0.5.9
+	git.sxidc.com/service-supports/scm-sdk v0.1.0
 	git.sxidc.com/service-supports/websocket v1.3.1
 	github.com/gin-gonic/gin v1.10.0
 	github.com/golang/protobuf v1.5.4

+ 2 - 0
go.sum

@@ -4,6 +4,8 @@ git.sxidc.com/service-supports/fserr v0.3.5 h1:1SDC60r3FIDd2iRq/oHRLK4OMa1gf67h9
 git.sxidc.com/service-supports/fserr v0.3.5/go.mod h1:8U+W/ulZIGVPFojV6cE18shkGXqvaICuzaxIJpOcBqI=
 git.sxidc.com/service-supports/fslog v0.5.9 h1:q2XIK2o/fk/qmByy4x5kKLC+k7kolT5LrXHcWRSffXQ=
 git.sxidc.com/service-supports/fslog v0.5.9/go.mod h1:/m03ATmmOle75qtEgvEw8a1+Dcg6iHp08M1bGFXJTBU=
+git.sxidc.com/service-supports/scm-sdk v0.1.0 h1:198qs/XxffOrHioKEWXyPfsQLoO3E8Ifj4idOWJxIe0=
+git.sxidc.com/service-supports/scm-sdk v0.1.0/go.mod h1:F0DLFok92zElZZRxJujSk6KmRoVGN8bkrbXFdq19uwI=
 git.sxidc.com/service-supports/websocket v1.3.1 h1:1mRfUwvpg0QA2JVKVMK8YJ/B33HFpDhY9srqroIuNGc=
 git.sxidc.com/service-supports/websocket v1.3.1/go.mod h1:YqEZXkN8ZFzUp01tDlekgIJJ0Yz+67d6eTXyA0ZIkgM=
 github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=

+ 7 - 7
infrastructure/database/operations/operations.go

@@ -11,13 +11,13 @@ import (
 )
 
 type Config struct {
-	UserName           string
-	Password           string
-	Address            string
-	Port               string
-	Database           string
-	MaxConnections     int
-	MaxIdleConnections int
+	UserName           string `json:"user_name" yaml:"user_name"`
+	Password           string `json:"password" yaml:"password"`
+	Address            string `json:"address" yaml:"address"`
+	Port               string `json:"port" yaml:"port"`
+	Database           string `json:"database" yaml:"database"`
+	MaxConnections     int    `json:"max_connections" yaml:"max_connections"`
+	MaxIdleConnections int    `json:"max_idle_connections" yaml:"max_idle_connections"`
 }
 
 type Operations struct {