Initial commit

This commit is contained in:
yan.y
2024-03-27 23:25:08 +08:00
commit 0884384e91
127 changed files with 9353 additions and 0 deletions
+129
View File
@@ -0,0 +1,129 @@
package operation
import (
"encoding/json"
"fmt"
"github.com/spf13/viper"
"pet-house.com/core/g"
"pet-house.com/core/server/viper_server"
"strings"
)
var CONFIG = Operation{
Except: Route{
Uri: "api/v1/upload;api/v1/upload",
Method: "post;put",
},
Include: Route{
Uri: "api/v1/menus",
Method: "get",
},
}
// IsExist config file is exist
func IsExist() bool {
return getViperConfig().IsFileExist()
}
// Remove remove config file
func Remove() error {
return getViperConfig().Remove()
}
// Recover
func Recover() error {
b, err := json.Marshal(CONFIG)
if err != nil {
return err
}
return getViperConfig().Recover(b)
}
// Operation
// Except set which routers don't generate system log, use ';' to separate.
// Include set which routers need to generate system log, use ';' to separate.
type Operation struct {
Except Route `mapstructure:"except" json:"except" yaml:"except"`
Include Route `mapstructure:"include" json:"include" yaml:"include"`
}
type Route struct {
Uri string `mapstructure:"uri" json:"uri" yaml:"uri"`
Method string `mapstructure:"method" json:"method" yaml:"method"`
}
// GetExcept return routers which need to excepted
func (op Operation) GetExcept() ([]string, []string) {
uri := strings.Split(op.Except.Uri, ";")
method := strings.Split(op.Except.Method, ";")
return uri, method
}
// GetInclude return routers which need to included
func (op Operation) GetInclude() ([]string, []string) {
uri := strings.Split(op.Include.Uri, ";")
method := strings.Split(op.Include.Method, ";")
return uri, method
}
// IsInclude check whether the current route needs to belong to the included data
func (op Operation) IsInclude(uri, method string) bool {
incUri, incMethod := op.GetInclude()
if len(incUri) != len(incMethod) {
return false
}
for i := 0; i < len(incUri); i++ {
if uri == incUri[i] && method == incMethod[i] {
return true
}
}
return false
}
// IsExcept check whether the current route needs to belong to the excepted data
func (op Operation) IsExcept(uri, method string) bool {
excUri, excMethod := op.GetExcept()
if len(excUri) != len(excMethod) {
return false
}
for i := 0; i < len(excUri); i++ {
if uri == excUri[i] && method == excMethod[i] {
return true
}
}
return false
}
// getViperConfig get viper config
func getViperConfig() viper_server.ViperConfig {
configName := "operation"
return viper_server.ViperConfig{
Debug: true,
Directory: g.ConfigDir,
Name: configName,
Type: g.ConfigType,
Watch: func(vi *viper.Viper) error {
if err := vi.Unmarshal(&CONFIG); err != nil {
return fmt.Errorf("get Unarshal error: %v", err)
}
// watch config file change
vi.SetConfigName(configName)
return nil
},
//
Default: []byte(`
{
"except":{
"uri": "` + CONFIG.Except.Uri + `",
"method": "` + CONFIG.Except.Method + `"
},
"include":
{
"uri": "` + CONFIG.Include.Uri + `",
"method": "` + CONFIG.Include.Method + `"
}
}`),
}
}
+71
View File
@@ -0,0 +1,71 @@
package operation
import (
"reflect"
"testing"
)
func TestGetExcept(t *testing.T) {
t.Run("test get except", func(t *testing.T) {
wantUri := []string{"api/v1/upload", "api/v1/upload"}
wantMethod := []string{"post", "put"}
uri, method := CONFIG.GetExcept()
if !reflect.DeepEqual(uri, wantUri) {
t.Errorf("get except want %+v but get %+v", wantUri, uri)
}
if !reflect.DeepEqual(method, wantMethod) {
t.Errorf("get except want %+v but get %+v", wantMethod, method)
}
})
}
func TestGetInclude(t *testing.T) {
t.Run("test get include", func(t *testing.T) {
wantUri := []string{"api/v1/menus"}
wantMethod := []string{"get"}
uri, method := CONFIG.GetInclude()
if !reflect.DeepEqual(uri, wantUri) {
t.Errorf("get include want %+v but get %+v", wantUri, uri)
}
if !reflect.DeepEqual(method, wantMethod) {
t.Errorf("get include want %+v but get %+v", wantMethod, method)
}
})
}
func TestGetIsInclude(t *testing.T) {
t.Run("test get include", func(t *testing.T) {
wantUri := "api/v1/menus"
wantMethod := "get"
if !CONFIG.IsInclude(wantUri, wantMethod) {
t.Errorf("[%s](%s) want include true but get false", wantMethod, wantUri)
}
wantUri = "api/v1/menus"
wantMethod = "post"
if CONFIG.IsInclude(wantUri, wantMethod) {
t.Errorf("[%s](%s) want include false but get true", wantMethod, wantUri)
}
wantUri = "api/v1/menu"
wantMethod = "get"
if CONFIG.IsInclude(wantUri, wantMethod) {
t.Errorf("[%s](%s) want include false but get true", wantMethod, wantUri)
}
})
}
func TestGetIsExcept(t *testing.T) {
t.Run("test get except", func(t *testing.T) {
wantUri := "api/v1/upload"
wantMethod := "post"
if !CONFIG.IsExcept(wantUri, wantMethod) {
t.Errorf("[%s](%s) want except true but get false", wantMethod, wantUri)
}
wantUri = "api/v1/upload"
wantMethod = "get"
if CONFIG.IsExcept(wantUri, wantMethod) {
t.Errorf("[%s](%s) want except false but get true", wantMethod, wantUri)
}
wantUri = "api/v1/menu"
wantMethod = "post"
if CONFIG.IsExcept(wantUri, wantMethod) {
t.Errorf("[%s](%s) want except false but get true", wantMethod, wantUri)
}
})
}
+41
View File
@@ -0,0 +1,41 @@
package operation
import (
"time"
"gorm.io/gorm"
"pet-house.com/core/server/database"
"pet-house.com/core/server/viper_server"
)
func init() {
err := viper_server.Init(getViperConfig())
if err != nil {
panic(err)
}
}
// CreateOplog
func CreateOplog(ol *Oplog) error {
err := database.Instance().Model(&Oplog{}).Create(ol).Error
if err != nil {
return err
}
return nil
}
// Oplog middleware model
type Oplog struct {
gorm.Model
Ip string `json:"ip" form:"ip" gorm:"column:ip;comment:ip"`
Method string `json:"method" form:"method" gorm:"column:method;comment:method" validate:"required"`
Path string `json:"path" form:"path" gorm:"column:path;comment:path" validate:"required"`
Status int `json:"status" form:"status" gorm:"column:status;comment:status" validate:"required"`
Latency time.Duration `json:"latency" form:"latency" gorm:"column:latency;comment:latency"`
Agent string `json:"agent" form:"agent" gorm:"column:agent;comment:agent"`
ErrorMessage string `json:"errorMessage" form:"errorMessage" gorm:"column:error_message;comment:error_message"`
Body string `json:"body" form:"body" gorm:"type:longtext;column:body;comment:body"`
Resp string `json:"resp" form:"resp" gorm:"type:longtext;column:resp;comment:resp"`
UserID uint `json:"userId" form:"userId" gorm:"column:user_id;comment:user_id"`
TenancyId uint `json:"tenancyId" form:"tenancyId" gorm:"column:tenancy_id;comment:tenancyId"`
}
+17
View File
@@ -0,0 +1,17 @@
package operation
import (
"testing"
"pet-house.com/core/server/database"
)
func TestCreateOplog(t *testing.T) {
database.Instance().AutoMigrate(&Oplog{})
t.Run("test create op log", func(t *testing.T) {
record := &Oplog{}
if err := CreateOplog(record); err != nil {
t.Errorf("test create op log get %s", err.Error())
}
})
}
+40
View File
@@ -0,0 +1,40 @@
package operation
import (
_ "embed"
"os"
"testing"
"github.com/bwmarrin/snowflake"
"pet-house.com/core/g"
"pet-house.com/core/helper/str"
"pet-house.com/core/server/database"
"pet-house.com/core/server/zap_server"
)
func TestMain(m *testing.M) {
node, _ := snowflake.NewNode(1)
uuid := str.Join("operation", "_", node.Generate().String())
database.CONFIG.DbName = uuid
database.CONFIG.Path = g.TestMysqlAddr
database.CONFIG.Password = g.TestMysqlPwd
database.Instance()
code := m.Run()
err := database.DorpDB(database.CONFIG.BaseDsn(), "mysql", uuid)
if err != nil {
zap_server.ZAPLOG.Error(err.Error())
}
db, _ := database.Instance().DB()
if db != nil {
db.Close()
}
database.Remove()
Remove()
zap_server.Remove()
os.Exit(code)
}
+17
View File
@@ -0,0 +1,17 @@
package operation
import (
"gorm.io/gorm"
)
func GetMigration() *gormigrate.Migration {
return &gormigrate.Migration{
ID: "20211214120700_create_oplogs_table",
Migrate: func(tx *gorm.DB) error {
return tx.AutoMigrate(&Oplog{})
},
Rollback: func(tx *gorm.DB) error {
return tx.Migrator().DropTable("oplogs")
},
}
}