作者 tangxuhui

新建项目

不能预览此文件类型
#!/bin/bash
export PATH=/root/local/bin:$PATH
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
if [ "$?" == "1" ];then
kubectl create -f /tmp/dev/project/project.yaml --record
kubectl -n <replace-your-k8s-namespace> get svc | grep -q project
if [ "$?" == "0" ];then
echo "project service install success!"
else
echo "project service install fail!"
fi
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
if [ "$?" == "0" ];then
echo "project deployment install success!"
else
echo "project deployment install fail!"
fi
else
kubectl delete -f /tmp/dev/project/project.yaml
kubectl -n <replace-your-k8s-namespace> get svc | grep -q project
while [ "$?" == "0" ]
do
kubectl -n <replace-your-k8s-namespace> get svc | grep -q project
done
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
while [ "$?" == "0" ]
do
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
done
kubectl create -f /tmp/dev/project/project.yaml --record
kubectl -n <replace-your-k8s-namespace> get svc | grep -q project
if [ "$?" == "0" ];then
echo "project service update success!"
else
echo "project service update fail!"
fi
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
if [ "$?" == "0" ];then
echo "project deployment update success!"
else
echo "project deployment update fail!"
fi
fi
\ No newline at end of file
... ...
apiVersion: v1
kind: Service
metadata:
name: project
namespace: <replace-your-k8s-namespace>
labels:
k8s-app: project
spec:
ports:
- name: "http"
port: 80
targetPort: 8082
selector:
k8s-app: project
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: project
namespace: <replace-your-k8s-namespace>
labels:
k8s-app: project
spec:
replicas: 1
template:
metadata:
labels:
k8s-app: project
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- preference: {}
weight: 100
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/hostname
operator: In
values:
- cn-hangzhou.i-bp1djh1xn7taumbue1ze
- cn-hangzhou.i-bp1djh1xn7taumbue1zd
- cn-hangzhou.i-bp1euf5u1ph9kbhtndhb
- cn-hangzhou.i-bp1hyp5oips9cdwxxgxy
containers:
- name: project
image: 192.168.0.243:5000/mmm/project:dev
imagePullPolicy: Always
ports:
- containerPort: 8082
volumeMounts:
- mountPath: /opt/logs
name: accesslogs
env:
- name: LOG_LEVEL
value: "debug"
- name: ERROR_BASE_CODE
value: "1"
- name: ERROR_BASE_CODE_MULTIPLE
value: "1000"
volumes:
- name: accesslogs
emptyDir: {}
\ No newline at end of file
... ...
module gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway
module gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic
go 1.16
require github.com/beego/beego/v2 v2.0.1
require (
github.com/beego/beego/v2 v2.0.1
github.com/go-pg/pg/v10 v10.10.2
github.com/linmadan/egglib-go v0.0.0-20210527091316-06b0732fb5f6
)
... ...
... ... @@ -5,5 +5,6 @@ import (
)
func main() {
web.Run()
}
... ...
package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type CreateDictionaryCommand struct {
// 字典编号 主键
DictionaryId int `json:"dictionaryId,omitempty"`
// 字典编码
DictCode string `json:"dictCode,omitempty"`
// 字典名称
DictName string `json:"dictName,omitempty"`
// 备注信息
Desc string `json:"desc,omitempty"`
// 是否可见【1:不可以】【2:可以】
IsShow int `json:"isShow,omitempty"`
// 字典值列表
DictItems []*DictionaryItem `json:"dictItems,omitempty"`
}
func (createDictionaryCommand *CreateDictionaryCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (createDictionaryCommand *CreateDictionaryCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(createDictionaryCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type RemoveDictionaryCommand struct {
// 字典编号 主键
DictionaryId int `json:"dictionaryId,omitempty"`
}
func (removeDictionaryCommand *RemoveDictionaryCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (removeDictionaryCommand *RemoveDictionaryCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(removeDictionaryCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type UpdateDictionaryCommand struct {
// 字典编号 主键
DictionaryId int `json:"dictionaryId,omitempty"`
// 字典编码
DictCode string `json:"dictCode,omitempty"`
// 字典名称
DictName string `json:"dictName,omitempty"`
// 备注信息
Desc string `json:"desc,omitempty"`
// 是否可见【1:不可以】【2:可以】
IsShow int `json:"isShow,omitempty"`
// 字典值列表
DictItems []*DictionaryItem `json:"dictItems,omitempty"`
}
func (updateDictionaryCommand *UpdateDictionaryCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (updateDictionaryCommand *UpdateDictionaryCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(updateDictionaryCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type GetDictionaryQuery struct {
// 字典编码
DictCode string `json:"dictCode,omitempty"`
}
func (getDictionaryQuery *GetDictionaryQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (getDictionaryQuery *GetDictionaryQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getDictionaryQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type ListDictionaryQuery struct {
// 查询偏离量
Offset int `json:"offset" valid:"Required"`
// 查询限制
Limit int `json:"limit" valid:"Required"`
}
func (listDictionaryQuery *ListDictionaryQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listDictionaryQuery *ListDictionaryQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listDictionaryQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/application/dictionary/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/application/dictionary/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/application/factory"
)
// 数据字典设置
type DictionaryService struct {
}
// 创建数据字典设置
func (dictionaryService *DictionaryService) CreateDictionary(createDictionaryCommand *command.CreateDictionaryCommand) (interface{}, error) {
if err := createDictionaryCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
newDictionary := &dictionary.Dictionary{
Dictionary: createDictionaryCommand.Dictionary,
}
var dictionaryRepository dictionary.DictionaryRepository
if value, err := factory.CreateDictionaryRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
dictionaryRepository = value
}
if dictionary, err := dictionaryRepository.Save(newDictionary); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return dictionary, nil
}
}
// 返回数据字典设置
func (dictionaryService *DictionaryService) GetDictionary(getDictionaryQuery *query.GetDictionaryQuery) (interface{}, error) {
if err := getDictionaryQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var dictionaryRepository dictionary.DictionaryRepository
if value, err := factory.CreateDictionaryRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
dictionaryRepository = value
}
dictionary, err := dictionaryRepository.FindOne(map[string]interface{}{"dictionaryId": getDictionaryQuery.DictionaryId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if dictionary == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(getDictionaryQuery.DictionaryId)))
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return dictionary, nil
}
}
// 返回数据字典设置列表
func (dictionaryService *DictionaryService) ListDictionary(listDictionaryQuery *query.ListDictionaryQuery) (interface{}, error) {
if err := listDictionaryQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var dictionaryRepository dictionary.DictionaryRepository
if value, err := factory.CreateDictionaryRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
dictionaryRepository = value
}
if count, dictionarys, err := dictionaryRepository.Find(tool_funs.SimpleStructToMap(listDictionaryQuery)); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return map[string]interface{}{
"count": count,
"dictionarys": dictionarys,
}, nil
}
}
// 移除数据字典设置
func (dictionaryService *DictionaryService) RemoveDictionary(removeDictionaryCommand *command.RemoveDictionaryCommand) (interface{}, error) {
if err := removeDictionaryCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var dictionaryRepository dictionary.DictionaryRepository
if value, err := factory.CreateDictionaryRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
dictionaryRepository = value
}
dictionary, err := dictionaryRepository.FindOne(map[string]interface{}{"dictionaryId": removeDictionaryCommand.DictionaryId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if dictionary == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(removeDictionaryCommand.DictionaryId)))
}
if dictionary, err := dictionaryRepository.Remove(dictionary); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return dictionary, nil
}
}
// 更新数据字典设置
func (dictionaryService *DictionaryService) UpdateDictionary(updateDictionaryCommand *command.UpdateDictionaryCommand) (interface{}, error) {
if err := updateDictionaryCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var dictionaryRepository dictionary.DictionaryRepository
if value, err := factory.CreateDictionaryRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
dictionaryRepository = value
}
dictionary, err := dictionaryRepository.FindOne(map[string]interface{}{"dictionaryId": updateDictionaryCommand.DictionaryId})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if dictionary == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(updateDictionaryCommand.DictionaryId)))
}
if err := dictionary.Update(tool_funs.SimpleStructToMap(updateDictionaryCommand)); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
if dictionary, err := dictionaryRepository.Save(dictionary); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return dictionary, nil
}
}
func NewDictionaryService(options map[string]interface{}) *DictionaryService {
newDictionaryService := &DictionaryService{}
return newDictionaryService
}
... ...
package factory
import (
"github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/infrastructure/repository"
)
func CreateDictionaryRepository(options map[string]interface{}) (domain.DictionaryRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewDictionaryRepository(transactionContext)
}
... ...
package factory
import (
"github.com/linmadan/egglib-go/core/application"
pG "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/infrastructure/pg"
)
func CreateTransactionContext(options map[string]interface{}) (application.TransactionContext, error) {
return pG.NewPGTransactionContext(pg.DB), nil
}
... ...
package constant
import "os"
const SERVICE_NAME = "project"
var LOG_LEVEL = "debug"
func init() {
if os.Getenv("LOG_LEVEL") != "" {
LOG_LEVEL = os.Getenv("LOG_LEVEL")
}
}
... ...
package constant
import "os"
var POSTGRESQL_DB_NAME = "project"
var POSTGRESQL_USER = "postgres"
var POSTGRESQL_PASSWORD = ""
var POSTGRESQL_HOST = "127.0.0.1"
var POSTGRESQL_PORT = "32432"
var DISABLE_CREATE_TABLE = false
var DISABLE_SQL_GENERATE_PRINT = false
func init() {
if os.Getenv("POSTGRESQL_DB_NAME") != "" {
POSTGRESQL_DB_NAME = os.Getenv("POSTGRESQL_DB_NAME")
}
if os.Getenv("POSTGRESQL_USER") != "" {
POSTGRESQL_USER = os.Getenv("POSTGRESQL_USER")
}
if os.Getenv("POSTGRESQL_PASSWORD") != "" {
POSTGRESQL_PASSWORD = os.Getenv("POSTGRESQL_PASSWORD")
}
if os.Getenv("POSTGRESQL_HOST") != "" {
POSTGRESQL_HOST = os.Getenv("POSTGRESQL_HOST")
}
if os.Getenv("POSTGRESQL_PORT") != "" {
POSTGRESQL_PORT = os.Getenv("POSTGRESQL_PORT")
}
if os.Getenv("DISABLE_CREATE_TABLE") != "" {
DISABLE_CREATE_TABLE = true
}
if os.Getenv("DISABLE_SQL_GENERATE_PRINT") != "" {
DISABLE_SQL_GENERATE_PRINT = true
}
}
... ...
package domain
// 字典
type Dictionary struct {
// 字典编号 主键
DictionaryId int `json:"dictionaryId"`
// 字典编码
DictCode string `json:"dictCode"`
// 字典名称
DictName string `json:"dictName"`
// 备注信息
Desc string `json:"desc"`
// 是否可见【1:不可以】【2:可以】
IsShow int `json:"isShow"`
// 字典值列表
DictItems []*DictionaryItem `json:"dictItems"`
}
type DictionaryRepository interface {
Save(dictionary *Dictionary) (*Dictionary, error)
Remove(dictionary *Dictionary) (*Dictionary, error)
FindOne(queryOptions map[string]interface{}) (*Dictionary, error)
Find(queryOptions map[string]interface{}) (int64, []*Dictionary, error)
}
func (dictionary *Dictionary) Identify() interface{} {
if dictionary.DictionaryId == 0 {
return nil
}
return dictionary.DictionaryId
}
func (dictionary *Dictionary) Update(data map[string]interface{}) error {
if dictionaryId, ok := data["dictionaryId"]; ok {
dictionary.DictionaryId = dictionaryId.(int)
}
if dictCode, ok := data["dictCode"]; ok {
dictionary.DictCode = dictCode.(string)
}
if dictName, ok := data["dictName"]; ok {
dictionary.DictName = dictName.(string)
}
if desc, ok := data["desc"]; ok {
dictionary.Desc = desc.(string)
}
if isShow, ok := data["isShow"]; ok {
dictionary.IsShow = isShow.(int)
}
if dictItems, ok := data["dictItems"]; ok {
dictionary.DictItems = dictItems.([]*DictionaryItem)
}
return nil
}
... ...
package domain
// 字典明细项
type DictionaryItem struct {
// 项编码
ItemCode string `json:"itemCode"`
// 项标签
ItemLabel string `json:"itemLabel"`
// 值
ItemValue string `json:"itemValue"`
// 启用状态(启用:1 禁用:2)
EnableStatus string `json:"enableStatus"`
// 显示序号
Sort int `json:"sort"`
}
... ...
package pg
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/constant"
//_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/infrastructure/pg/models"
"github.com/linmadan/egglib-go/persistent/pg/hooks"
)
var DB *pg.DB
func init() {
DB = pg.Connect(&pg.Options{
User: constant.POSTGRESQL_USER,
Password: constant.POSTGRESQL_PASSWORD,
Database: constant.POSTGRESQL_DB_NAME,
Addr: fmt.Sprintf("%s:%s", constant.POSTGRESQL_HOST, constant.POSTGRESQL_PORT),
})
if !constant.DISABLE_SQL_GENERATE_PRINT {
DB.AddQueryHook(hooks.SqlGeneratePrintHook{})
}
if !constant.DISABLE_CREATE_TABLE {
for _, model := range []interface{}{} {
err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: false,
IfNotExists: true,
FKConstraints: true,
})
if err != nil {
panic(err)
}
}
}
}
... ...
package models
type Dictionary struct {
tableName string `pg:"dictionarys,alias:dictionary"`
// 字典编号 主键
DictionaryId int
// 字典编码
DictCode string
// 字典名称
DictName string
// 备注信息
Desc string
// 是否可见【1:不可以】【2:可以】
IsShow int
// 字典值列表
DictItems []*DictionaryItem `pg:",array"`
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/infrastructure/pg/models"
)
func TransformToDictionaryDomainModelFromPgModels(dictionaryModel *models.Dictionary) (*domain.Dictionary, error) {
return &domain.Dictionary{
DictionaryId: dictionaryModel.DictionaryId,
DictCode: dictionaryModel.DictCode,
DictName: dictionaryModel.DictName,
Desc: dictionaryModel.Desc,
IsShow: dictionaryModel.IsShow,
DictItems: dictionaryModel.DictItems,
}, nil
}
... ...
package repository
import (
"fmt"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/infrastructure/pg/transform"
)
type DictionaryRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *DictionaryRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *DictionaryRepository) Save(dictionary *domain.Dictionary) (*domain.Dictionary, error) {
sqlBuildFields := []string{
"dictionary_id",
"dict_code",
"dict_name",
"desc",
"is_show",
"dict_items",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "dictionary_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if dictionary.Identify() == nil {
dictionaryId, err := repository.nextIdentify()
if err != nil {
return dictionary, err
} else {
dictionary.DictionaryId = dictionaryId
}
if _, err := tx.QueryOne(
pg.Scan(
&dictionary.DictionaryId,
&dictionary.DictCode,
&dictionary.DictName,
&dictionary.Desc,
&dictionary.IsShow,
pg.Array(&dictionary.DictItems),
),
fmt.Sprintf("INSERT INTO dictionarys (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
dictionary.DictionaryId,
dictionary.DictCode,
dictionary.DictName,
dictionary.Desc,
dictionary.IsShow,
pg.Array(dictionary.DictItems),
); err != nil {
return dictionary, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&dictionary.DictionaryId,
&dictionary.DictCode,
&dictionary.DictName,
&dictionary.Desc,
&dictionary.IsShow,
pg.Array(&dictionary.DictItems),
),
fmt.Sprintf("UPDATE dictionarys SET %s WHERE dictionary_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
dictionary.DictionaryId,
dictionary.DictCode,
dictionary.DictName,
dictionary.Desc,
dictionary.IsShow,
pg.Array(dictionary.DictItems),
dictionary.Identify(),
); err != nil {
return dictionary, err
}
}
return dictionary, nil
}
func (repository *DictionaryRepository) Remove(dictionary *domain.Dictionary) (*domain.Dictionary, error) {
tx := repository.transactionContext.PgTx
dictionaryModel := new(models.Dictionary)
dictionaryModel.DictionaryId = dictionary.Identify().(int64)
if _, err := tx.Model(dictionaryModel).WherePK().Delete(); err != nil {
return dictionary, err
}
return dictionary, nil
}
func (repository *DictionaryRepository) FindOne(queryOptions map[string]interface{}) (*domain.Dictionary, error) {
tx := repository.transactionContext.PgTx
dictionaryModel := new(models.Dictionary)
query := sqlbuilder.BuildQuery(tx.Model(dictionaryModel), queryOptions)
query.SetWhereByQueryOption("dictionary.dictionary_id = ?", "dictionaryId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if dictionaryModel.DictionaryId == 0 {
return nil, nil
} else {
return transform.TransformToDictionaryDomainModelFromPgModels(dictionaryModel)
}
}
func (repository *DictionaryRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Dictionary, error) {
tx := repository.transactionContext.PgTx
var dictionaryModels []*models.Dictionary
dictionarys := make([]*domain.Dictionary, 0)
query := sqlbuilder.BuildQuery(tx.Model(&dictionaryModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("dictionary_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, dictionarys, err
} else {
for _, dictionaryModel := range dictionaryModels {
if dictionary, err := transform.TransformToDictionaryDomainModelFromPgModels(dictionaryModel); err != nil {
return 0, dictionarys, err
} else {
dictionarys = append(dictionarys, dictionary)
}
}
return int64(count), dictionarys, nil
}
}
func NewDictionaryRepository(transactionContext *pgTransaction.TransactionContext) (*DictionaryRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &DictionaryRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package log
import (
"github.com/linmadan/egglib-go/log"
"github.com/linmadan/egglib-go/log/logrus"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/constant"
)
var Logger log.Logger
func init() {
Logger = logrus.NewLogrusLogger()
Logger.SetServiceName(constant.SERVICE_NAME)
Logger.SetLevel(constant.LOG_LEVEL)
}
... ...
package beego
import (
"github.com/beego/beego/v2/server/web"
"github.com/linmadan/egglib-go/web/beego/filters"
//_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/port/beego/routers"
. "gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/log"
)
func init() {
web.BConfig.AppName = "project"
web.BConfig.CopyRequestBody = true
web.BConfig.RunMode = "dev"
web.BConfig.Listen.HTTPPort = 8080
web.BConfig.Listen.EnableAdmin = false
web.BConfig.WebConfig.CommentRouterPath = "/pkg/port/beego"
if os.Getenv("RUN_MODE") != "" {
web.BConfig.RunMode = os.Getenv("RUN_MODE")
}
if os.Getenv("HTTP_PORT") != "" {
portStr := os.Getenv("HTTP_PORT")
if port, err := strconv.Atoi(portStr); err == nil {
web.BConfig.Listen.HTTPPort = port
}
}
web.InsertFilter("/*", web.BeforeExec, filters.AllowCors())
web.InsertFilter("/*", web.BeforeExec, filters.CreateRequstLogFilter(Logger))
web.InsertFilter("/*", web.AfterExec, filters.CreateResponseLogFilter(Logger), web.WithReturnOnOutput(false))
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/application/dictionary/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/application/dictionary/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/application/dictionary/service"
)
type DictionaryController struct {
beego.BaseController
}
func (controller *DictionaryController) CreateDictionary() {
dictionaryService := service.NewDictionaryService(nil)
createDictionaryCommand := &command.CreateDictionaryCommand{}
controller.Unmarshal(createDictionaryCommand)
data, err := dictionaryService.CreateDictionary(createDictionaryCommand)
controller.Response(data, err)
}
func (controller *DictionaryController) UpdateDictionary() {
dictionaryService := service.NewDictionaryService(nil)
updateDictionaryCommand := &command.UpdateDictionaryCommand{}
controller.Unmarshal(updateDictionaryCommand)
dictionaryId, _ := controller.GetString(":dictionaryId")
updateDictionaryCommand.DictionaryId = dictionaryId
data, err := dictionaryService.UpdateDictionary(updateDictionaryCommand)
controller.Response(data, err)
}
func (controller *DictionaryController) GetDictionary() {
dictionaryService := service.NewDictionaryService(nil)
getDictionaryQuery := &query.GetDictionaryQuery{}
dictionaryId, _ := controller.GetString(":dictionaryId")
getDictionaryQuery.DictionaryId = dictionaryId
data, err := dictionaryService.GetDictionary(getDictionaryQuery)
controller.Response(data, err)
}
func (controller *DictionaryController) ListDictionary() {
dictionaryService := service.NewDictionaryService(nil)
listDictionaryQuery := &query.ListDictionaryQuery{}
offset, _ := controller.GetInt("offset")
listDictionaryQuery.Offset = offset
limit, _ := controller.GetInt("limit")
listDictionaryQuery.Limit = limit
data, err := dictionaryService.ListDictionary(listDictionaryQuery)
controller.Response(data, err)
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-basic/pkg/port/beego/controllers"
)
func init() {
web.Router("/dictionarys/", &controllers.DictionaryController{}, "Post:CreateDictionary")
web.Router("/dictionarys/:dictionaryId", &controllers.DictionaryController{}, "Put:UpdateDictionary")
web.Router("/dictionarys/:dictionaryId", &controllers.DictionaryController{}, "Get:GetDictionary")
web.Router("/dictionarys/", &controllers.DictionaryController{}, "Get:ListDictionary")
}
... ...