Browse Source

update

tags/v0.0.2
dengbiao 4 months ago
parent
commit
16531d9c66
71 changed files with 1635 additions and 281 deletions
  1. +19
    -0
      enum/enum_permission_group.go
  2. +1
    -1
      src/dao/admin_dao.go
  3. +1
    -1
      src/dao/admin_role_dao.go
  4. +1
    -1
      src/dao/agent_dao.go
  5. +1
    -1
      src/dao/agent_permission_group_dao.go
  6. +1
    -1
      src/dao/agent_role_dao.go
  7. +1
    -1
      src/dao/agent_role_permission_group_dao.go
  8. +1
    -1
      src/dao/agent_with_role_dao.go
  9. +1
    -1
      src/dao/medium_dao.go
  10. +1
    -1
      src/dao/medium_domain_dao.go
  11. +1
    -1
      src/dao/medium_permission_group_dao.go
  12. +1
    -1
      src/dao/medium_role_dao.go
  13. +1
    -1
      src/dao/medium_role_permission_group_dao.go
  14. +1
    -1
      src/dao/medium_with_role_dao.go
  15. +1
    -2
      src/dao/permission_group_dao.go
  16. +1
    -1
      src/dao/role_dao.go
  17. +1
    -1
      src/dao/role_permission_group_dao.go
  18. +0
    -14
      src/dao/sys_cfg_dao.go
  19. +1
    -1
      src/db_sys_cfg.go
  20. +1
    -1
      src/dbs.go
  21. +3
    -3
      src/dbs_map.go
  22. +6
    -6
      src/implement/admin_implement.go
  23. +2
    -3
      src/implement/admin_role_implement.go
  24. +1
    -1
      src/implement/agent_domain_implement.go
  25. +4
    -4
      src/implement/agent_implement.go
  26. +6
    -6
      src/implement/agent_permission_group_implement.go
  27. +1
    -1
      src/implement/agent_permission_group_permission_implement.go
  28. +1
    -1
      src/implement/agent_permission_implement.go
  29. +5
    -5
      src/implement/agent_role_implement.go
  30. +2
    -2
      src/implement/agent_role_permission_group_implement.go
  31. +6
    -6
      src/implement/agent_with_role_implement.go
  32. +4
    -4
      src/implement/medium_domain_implement.go
  33. +4
    -4
      src/implement/medium_implement.go
  34. +6
    -6
      src/implement/medium_permission_group_implement.go
  35. +1
    -1
      src/implement/medium_permission_group_permission_implement.go
  36. +1
    -1
      src/implement/medium_permission_implement.go
  37. +5
    -5
      src/implement/medium_role_implement.go
  38. +2
    -2
      src/implement/medium_role_permission_group_implement.go
  39. +6
    -6
      src/implement/medium_with_role_implement.go
  40. +6
    -6
      src/implement/permission_group_implement.go
  41. +1
    -1
      src/implement/permission_group_permission_implement.go
  42. +1
    -1
      src/implement/permission_implement.go
  43. +5
    -5
      src/implement/role_implement.go
  44. +2
    -2
      src/implement/role_permission_group_implement.go
  45. +0
    -124
      src/implement/sys_cfg_implement.go
  46. +1
    -1
      src/super/dao/admin_dao.go
  47. +1
    -1
      src/super/dao/admin_role_dao.go
  48. +1
    -1
      src/super/dao/agent_list_dao.go
  49. +1
    -1
      src/super/dao/medium_list_dao.go
  50. +1
    -1
      src/super/dao/permission_group_dao.go
  51. +1
    -1
      src/super/dao/role_dao.go
  52. +1
    -1
      src/super/dao/role_permission_group_dao.go
  53. +6
    -6
      src/super/implement/admin_implement.go
  54. +6
    -6
      src/super/implement/admin_role_implement.go
  55. +4
    -4
      src/super/implement/agent_list_implement.go
  56. +4
    -4
      src/super/implement/medium_list_implement.go
  57. +6
    -6
      src/super/implement/permission_group_implement.go
  58. +1
    -1
      src/super/implement/permission_group_permission_implement.go
  59. +1
    -1
      src/super/implement/permission_implement.go
  60. +5
    -5
      src/super/implement/role_implement.go
  61. +2
    -2
      src/super/implement/role_permission_group_implement.go
  62. +388
    -0
      utils/convert.go
  63. +209
    -0
      utils/curl.go
  64. +22
    -0
      utils/file.go
  65. +59
    -0
      utils/format.go
  66. +245
    -0
      utils/logx/log.go
  67. +105
    -0
      utils/logx/output.go
  68. +192
    -0
      utils/logx/sugar.go
  69. +23
    -0
      utils/serialize.go
  70. +203
    -0
      utils/string.go
  71. +29
    -0
      utils/time2s.go

+ 19
- 0
enum/enum_permission_group.go View File

@@ -0,0 +1,19 @@
package enum

type PermissionGroupState int32

const (
PermissionGroupStateForNormal = 1
PermissionGroupStateForDiscard = 2
)

func (gt PermissionGroupState) String() string {
switch gt {
case PermissionGroupStateForNormal:
return "正常"
case PermissionGroupStateForDiscard:
return "废弃"
default:
return "未知"
}
}

+ 1
- 1
src/dao/admin_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/model"
"xorm.io/xorm"
)



+ 1
- 1
src/dao/admin_role_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/model"
"xorm.io/xorm"
)



+ 1
- 1
src/dao/agent_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/model"
"xorm.io/xorm"
)



+ 1
- 1
src/dao/agent_permission_group_dao.go View File

@@ -1,6 +1,6 @@
package dao

import "applet/app/db/model"
import "code.fnuoos.com/zhimeng/model.git/src/model"

type AgentPermissionGroupDao interface {
FindAgentPermissionGroup() (*[]model.AgentPermissionGroup, error)


+ 1
- 1
src/dao/agent_role_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/model"
"xorm.io/xorm"
)



+ 1
- 1
src/dao/agent_role_permission_group_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/model"
"xorm.io/xorm"
)



+ 1
- 1
src/dao/agent_with_role_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/model"
"xorm.io/xorm"
)



+ 1
- 1
src/dao/medium_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/model"
"xorm.io/xorm"
)



+ 1
- 1
src/dao/medium_domain_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/model"
)

type MediumDomainDao interface {


+ 1
- 1
src/dao/medium_permission_group_dao.go View File

@@ -1,6 +1,6 @@
package dao

import "applet/app/db/model"
import "code.fnuoos.com/zhimeng/model.git/src/model"

type MediumPermissionGroupDao interface {
FindMediumPermissionGroup() (*[]model.MediumPermissionGroup, error)


+ 1
- 1
src/dao/medium_role_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/model"
"xorm.io/xorm"
)



+ 1
- 1
src/dao/medium_role_permission_group_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/model"
"xorm.io/xorm"
)



+ 1
- 1
src/dao/medium_with_role_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/model"
"xorm.io/xorm"
)



+ 1
- 2
src/dao/permission_group_dao.go View File

@@ -1,9 +1,8 @@
package dao

import "applet/app/db/model"
import "code.fnuoos.com/zhimeng/model.git/src/model"

type PermissionGroupDao interface {
PermissionGroup
FindPermissionGroup() (*[]model.PermissionGroup, error)
FindPermissionGroupV2() (*[]model.PermissionGroup, error)
}

+ 1
- 1
src/dao/role_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/model"
"xorm.io/xorm"
)



+ 1
- 1
src/dao/role_permission_group_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/model"
"xorm.io/xorm"
)



+ 0
- 14
src/dao/sys_cfg_dao.go View File

@@ -1,14 +0,0 @@
package dao

import "applet/app/db/model"

type SysCfgDao interface {
SysCfgGetAll() (*[]model.SysCfg, error)
SysCfgGetOneNoDataNoErr(key string) (*model.SysCfg, error)
SysCfgGetOne(key string) (*model.SysCfg, error)
SysCfgInsert(key, val, memo string) bool
SysCfgUpdate(key, val string) bool
SysCfgGetWithDb(HKey string) string
SysCfgDel(HKey string) error
SysCfgFindWithDb(keys ...string) map[string]string
}

+ 1
- 1
src/db_sys_cfg.go View File

@@ -1,10 +1,10 @@
package db

import (
"applet/app/db/model"
"applet/app/md"
"applet/app/utils/cache"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/model"
"fmt"
"xorm.io/xorm"
)


+ 1
- 1
src/dbs.go View File

@@ -9,8 +9,8 @@ import (
"xorm.io/xorm/log"

"applet/app/cfg"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/model"
)

var DBs map[string]*xorm.Engine


+ 3
- 3
src/dbs_map.go View File

@@ -7,8 +7,8 @@ import (
"xorm.io/xorm"

"applet/app/cfg"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/model"
)

func MapBaseExists() (bool, error) {
@@ -105,7 +105,7 @@ func GetAllDatabaseDev() *[]model.DbMapping {
return &m
}

//GetDatabaseByMasterID is 根据站长id 获取对应的的数据库信息
// GetDatabaseByMasterID is 根据站长id 获取对应的的数据库信息
func GetDatabaseByMasterID(Db *xorm.Engine, id string) (*model.DbMapping, error) {
var m model.DbMapping
has, err := Db.Where("db_master_id=?", id).Get(&m)
@@ -123,7 +123,7 @@ func GetDatabaseByMasterID(Db *xorm.Engine, id string) (*model.DbMapping, error)
return &m, nil
}

//SessionGetDatabaseByMasterID is 根据站长id 获取对应的的数据库信息
// SessionGetDatabaseByMasterID is 根据站长id 获取对应的的数据库信息
func SessionGetDatabaseByMasterID(Db *xorm.Session, id string) (*model.DbMapping, error) {
var m model.DbMapping
has, err := Db.Where("db_master_id=?", id).Get(&m)


+ 6
- 6
src/implement/admin_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"reflect"
"xorm.io/xorm"
)
@@ -20,7 +20,7 @@ func (a AdminDb) CreateAdminId() (admId int, err error) {
m := new(model.Admin)
has, err := a.Db.Desc("adm_id").Get(m)
if err != nil {
return 0, logx.Error(err)
return 0, zhios_order_relate_logx.Error(err)
}
if has == false {
return 0, nil
@@ -41,7 +41,7 @@ func (a AdminDb) GetAdmin(id int) (m *model.Admin, err error) {
m = new(model.Admin)
has, err := a.Db.Where("adm_id =?", id).Get(m)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil
@@ -53,7 +53,7 @@ func (a AdminDb) GetAdminByUserName(userName string) (m *model.Admin, err error)
m = new(model.Admin)
has, err := a.Db.Where("username =?", userName).Get(m)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 2
- 3
src/implement/admin_role_implement.go View File

@@ -1,9 +1,8 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
"reflect"
"xorm.io/xorm"
)


+ 1
- 1
src/implement/agent_domain_implement.go View File

@@ -1,7 +1,7 @@
package implement

import (
"applet/app/db/dao"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"xorm.io/xorm"
)



+ 4
- 4
src/implement/agent_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"reflect"
"xorm.io/xorm"
)
@@ -20,7 +20,7 @@ func (a AgentDb) GetAgentByUsername(username string) (agent *model.Agent, err er
agent = new(model.Agent)
has, err := a.Db.Where("username =?", username).Get(agent)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 6
- 6
src/implement/agent_permission_group_implement.go View File

@@ -1,10 +1,10 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/enum"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/enum"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"xorm.io/xorm"
)

@@ -19,7 +19,7 @@ type AgentPermissionGroupDb struct {
func (a AgentPermissionGroupDb) FindAgentPermissionGroup() (*[]model.AgentPermissionGroup, error) {
var mm []model.AgentPermissionGroup
if err := a.Db.Where("state = ?", enum.PermissionGroupStateForNormal).Asc("id").Find(&mm); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &mm, nil
}
@@ -27,7 +27,7 @@ func (a AgentPermissionGroupDb) FindAgentPermissionGroup() (*[]model.AgentPermis
func (a AgentPermissionGroupDb) FindAgentPermissionGroupV2() (*[]model.AgentPermissionGroup, error) {
var mm []model.AgentPermissionGroup
if err := a.Db.Asc("id").Find(&mm); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &mm, nil
}

+ 1
- 1
src/implement/agent_permission_group_permission_implement.go View File

@@ -1,7 +1,7 @@
package implement

import (
"applet/app/db/dao"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"xorm.io/xorm"
)



+ 1
- 1
src/implement/agent_permission_implement.go View File

@@ -1,7 +1,7 @@
package implement

import (
"applet/app/db/dao"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"xorm.io/xorm"
)



+ 5
- 5
src/implement/agent_role_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"reflect"
"xorm.io/xorm"
)
@@ -19,7 +19,7 @@ type AgentRoleDb struct {
func (a AgentRoleDb) FindAgentRole() (*[]model.AgentRole, error) {
var mm []model.AgentRole
if err := a.Db.Desc("id").Find(&mm); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &mm, nil
}
@@ -28,7 +28,7 @@ func (a AgentRoleDb) GetAgentRole() (m *model.AgentRole, err error) {
m = new(model.AgentRole)
has, err := a.Db.Where("id = ?", m.Id).Get(m)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 2
- 2
src/implement/agent_role_permission_group_implement.go View File

@@ -1,8 +1,8 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
"reflect"
"xorm.io/xorm"
)


+ 6
- 6
src/implement/agent_with_role_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"reflect"
"xorm.io/xorm"
)
@@ -19,7 +19,7 @@ type AgentWithRoleDb struct {
func (a AgentWithRoleDb) FindAgentWithRole(id int) (*[]model.AgentWithRole, error) {
var mm []model.AgentWithRole
if err := a.Db.Where("adm_id =?", id).Find(&mm); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &mm, nil
}
@@ -27,7 +27,7 @@ func (a AgentWithRoleDb) FindAgentWithRole(id int) (*[]model.AgentWithRole, erro
func (a AgentWithRoleDb) FindAgentWithRoleByRoleId(id int) (*[]model.AgentWithRole, error) {
var mm []model.AgentWithRole
if err := a.Db.Where("role_id =?", id).Find(&mm); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &mm, nil
}
@@ -44,7 +44,7 @@ func (a AgentWithRoleDb) GetAgentWithRoleByRole(id int) (mm *model.AgentWithRole
mm = new(model.AgentWithRole)
has, err := a.Db.Where("role_id =?", id).Get(mm)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 4
- 4
src/implement/medium_domain_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"xorm.io/xorm"
)

@@ -19,7 +19,7 @@ func (m MediumDomainDb) GetMediumDomain(mediumId int) (medium *model.MediumDomai
medium = new(model.MediumDomain)
has, err := m.Db.Where("medium_id =?", mediumId).Get(medium)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 4
- 4
src/implement/medium_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"reflect"
"xorm.io/xorm"
)
@@ -28,7 +28,7 @@ func (m MediumDb) GetMediumByUsername(username string) (medium *model.Medium, er
medium = new(model.Medium)
has, err := m.Db.Where("username =?", username).Get(medium)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 6
- 6
src/implement/medium_permission_group_implement.go View File

@@ -1,10 +1,10 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/enum"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/enum"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"xorm.io/xorm"
)

@@ -19,7 +19,7 @@ type MediumPermissionGroupDb struct {
func (m MediumPermissionGroupDb) FindMediumPermissionGroup() (*[]model.MediumPermissionGroup, error) {
var mm []model.MediumPermissionGroup
if err := m.Db.Where("state = ?", enum.PermissionGroupStateForNormal).Asc("id").Find(&mm); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &mm, nil
}
@@ -27,7 +27,7 @@ func (m MediumPermissionGroupDb) FindMediumPermissionGroup() (*[]model.MediumPer
func (m MediumPermissionGroupDb) FindMediumPermissionGroupV2() (*[]model.MediumPermissionGroup, error) {
var mm []model.MediumPermissionGroup
if err := m.Db.Asc("id").Find(&mm); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &mm, nil
}

+ 1
- 1
src/implement/medium_permission_group_permission_implement.go View File

@@ -1,7 +1,7 @@
package implement

import (
"applet/app/db/dao"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"xorm.io/xorm"
)



+ 1
- 1
src/implement/medium_permission_implement.go View File

@@ -1,7 +1,7 @@
package implement

import (
"applet/app/db/dao"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"xorm.io/xorm"
)



+ 5
- 5
src/implement/medium_role_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"reflect"
"xorm.io/xorm"
)
@@ -19,7 +19,7 @@ type MediumRoleDb struct {
func (m MediumRoleDb) FindMediumRole() (*[]model.MediumRole, error) {
var mm []model.MediumRole
if err := m.Db.Desc("id").Find(&mm); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &mm, nil
}
@@ -28,7 +28,7 @@ func (m MediumRoleDb) GetMediumRole() (mm *model.MediumRole, err error) {
mm = new(model.MediumRole)
has, err := m.Db.Where("id = ?", mm.Id).Get(mm)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 2
- 2
src/implement/medium_role_permission_group_implement.go View File

@@ -1,8 +1,8 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
"reflect"
"xorm.io/xorm"
)


+ 6
- 6
src/implement/medium_with_role_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"reflect"
"xorm.io/xorm"
)
@@ -19,7 +19,7 @@ type MediumWithRoleDb struct {
func (m MediumWithRoleDb) FindMediumWithRole(id int) (*[]model.MediumWithRole, error) {
var mm []model.MediumWithRole
if err := m.Db.Where("adm_id =?", id).Find(&mm); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &mm, nil
}
@@ -27,7 +27,7 @@ func (m MediumWithRoleDb) FindMediumWithRole(id int) (*[]model.MediumWithRole, e
func (m MediumWithRoleDb) FindMediumWithRoleByRoleId(id int) (*[]model.MediumWithRole, error) {
var mm []model.MediumWithRole
if err := m.Db.Where("role_id =?", id).Find(&mm); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &mm, nil
}
@@ -44,7 +44,7 @@ func (m MediumWithRoleDb) GetMediumWithRoleByRole(id int) (mm *model.MediumWithR
mm = new(model.MediumWithRole)
has, err := m.Db.Where("role_id =?", id).Get(mm)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 6
- 6
src/implement/permission_group_implement.go View File

@@ -1,10 +1,10 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/enum"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/enum"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"xorm.io/xorm"
)

@@ -19,7 +19,7 @@ type PermissionGroupDb struct {
func (p PermissionGroupDb) FindPermissionGroup() (*[]model.PermissionGroup, error) {
var m []model.PermissionGroup
if err := p.Db.Where("state = ?", enum.PermissionGroupStateForNormal).Asc("id").Find(&m); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}
@@ -27,7 +27,7 @@ func (p PermissionGroupDb) FindPermissionGroup() (*[]model.PermissionGroup, erro
func (p PermissionGroupDb) FindPermissionGroupV2() (*[]model.PermissionGroup, error) {
var m []model.PermissionGroup
if err := p.Db.Asc("id").Find(&m); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

+ 1
- 1
src/implement/permission_group_permission_implement.go View File

@@ -1,7 +1,7 @@
package implement

import (
"applet/app/db/dao"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"xorm.io/xorm"
)



+ 1
- 1
src/implement/permission_implement.go View File

@@ -1,7 +1,7 @@
package implement

import (
"applet/app/db/dao"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"xorm.io/xorm"
)



+ 5
- 5
src/implement/role_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"reflect"
"xorm.io/xorm"
)
@@ -23,7 +23,7 @@ type RoleDb struct {
func (r RoleDb) FindRole() (*[]model.Role, error) {
var m []model.Role
if err := r.Db.Desc("id").Find(&m); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}
@@ -32,7 +32,7 @@ func (r RoleDb) GetRole() (m *model.Role, err error) {
m = new(model.Role)
has, err := r.Db.Where("id = ?", r.Id).Get(m)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 2
- 2
src/implement/role_permission_group_implement.go View File

@@ -1,8 +1,8 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/dao"
"code.fnuoos.com/zhimeng/model.git/src/model"
"reflect"
"xorm.io/xorm"
)


+ 0
- 124
src/implement/sys_cfg_implement.go View File

@@ -1,124 +0,0 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/md"
"applet/app/utils/cache"
"applet/app/utils/logx"
"fmt"
"xorm.io/xorm"
)

func NewSysCfgDb(engine *xorm.Engine, masterId string) dao.SysCfgDao {
return &SysCfgDb{
Db: engine,
MasterId: masterId,
}
}

type SysCfgDb struct {
Db *xorm.Engine
MasterId string
}

func (s SysCfgDb) SysCfgGetAll() (*[]model.SysCfg, error) {
var cfgList []model.SysCfg
if err := s.Db.Cols("key,val,memo").Find(&cfgList); err != nil {
return nil, logx.Error(err)
}
return &cfgList, nil
}

func (s SysCfgDb) SysCfgGetOneNoDataNoErr(key string) (*model.SysCfg, error) {
var cfgList model.SysCfg
has, err := s.Db.Where("`key`=?", key).Get(&cfgList)
if err != nil {
return nil, logx.Error(err)
}
if !has {
return nil, nil
}
return &cfgList, nil
}

func (s SysCfgDb) SysCfgGetOne(key string) (*model.SysCfg, error) {
var cfgList model.SysCfg
if has, err := s.Db.Where("`key`=?", key).Get(&cfgList); err != nil || has == false {
return nil, logx.Error(err)
}
return &cfgList, nil
}

func (s SysCfgDb) SysCfgInsert(key, val, memo string) bool {
cfg := model.SysCfg{Key: key, Val: val, Memo: memo}
_, err := s.Db.InsertOne(&cfg)
if err != nil {
logx.Error(err)
return false
}
return true
}

func (s SysCfgDb) SysCfgUpdate(key, val string) bool {
cfg := model.SysCfg{Key: key, Val: val}
_, err := s.Db.Where("`key`=?", key).Cols("val").Update(&cfg)
if err != nil {
logx.Error(err)
return false
}
s.SysCfgDel(key)
return true
}

func (s SysCfgDb) SysCfgGetWithDb(HKey string) string {
cacheKey := fmt.Sprintf(md.AppCfgCacheKey, s.MasterId, HKey[0:1])
get, err := cache.HGetString(cacheKey, HKey)
if err != nil || get == "" {
cfg, err := s.SysCfgGetOne(HKey)
if err != nil || cfg == nil {
_ = logx.Error(err)
return ""
}

// key是否存在
cacheKeyExist := false
if cache.Exists(cacheKey) {
cacheKeyExist = true
}

// 设置缓存
_, err = cache.HSet(cacheKey, HKey, cfg.Val)
if err != nil {
_ = logx.Error(err)
return ""
}
if !cacheKeyExist { // 如果是首次设置 设置过期时间
_, err := cache.Expire(cacheKey, md.CfgCacheTime)
if err != nil {
_ = logx.Error(err)
return ""
}
}
return cfg.Val
}
return get
}

func (s SysCfgDb) SysCfgDel(HKey string) error {
cacheKey := fmt.Sprintf(md.AppCfgCacheKey, s.MasterId, HKey[0:1])
_, err := cache.HDel(cacheKey, HKey)
if err != nil {
return err
}
return nil
}

func (s SysCfgDb) SysCfgFindWithDb(keys ...string) map[string]string {
res := map[string]string{}
for _, v := range keys {
val := s.SysCfgGetWithDb(v)
res[v] = val
}
return res
}

+ 1
- 1
src/super/dao/admin_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/super/model"
"xorm.io/xorm"
)



+ 1
- 1
src/super/dao/admin_role_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/super/model"
"xorm.io/xorm"
)



+ 1
- 1
src/super/dao/agent_list_dao.go View File

@@ -1,6 +1,6 @@
package dao

import "applet/app/db/super/model"
import "code.fnuoos.com/zhimeng/model.git/src/super/model"

type AgentListDao interface {
GetAgentList(agentId int) (medium *model.AgentList, err error)


+ 1
- 1
src/super/dao/medium_list_dao.go View File

@@ -1,6 +1,6 @@
package dao

import "applet/app/db/super/model"
import "code.fnuoos.com/zhimeng/model.git/src/super/model"

type MediumListDao interface {
GetMediumList(mediumId int) (medium *model.MediumList, err error)


+ 1
- 1
src/super/dao/permission_group_dao.go View File

@@ -1,6 +1,6 @@
package dao

import "applet/app/db/model"
import "code.fnuoos.com/zhimeng/model.git/src/super/model"

type PermissionGroupDao interface {
FindPermissionGroup() (*[]model.PermissionGroup, error)


+ 1
- 1
src/super/dao/role_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/super/model"
"xorm.io/xorm"
)



+ 1
- 1
src/super/dao/role_permission_group_dao.go View File

@@ -1,7 +1,7 @@
package dao

import (
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/super/model"
"xorm.io/xorm"
)



+ 6
- 6
src/super/implement/admin_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/super/dao"
"code.fnuoos.com/zhimeng/model.git/src/super/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"reflect"
"xorm.io/xorm"
)
@@ -20,7 +20,7 @@ func (a AdminDb) CreateAdminId() (admId int, err error) {
m := new(model.Admin)
has, err := a.Db.Desc("adm_id").Get(m)
if err != nil {
return 0, logx.Error(err)
return 0, zhios_order_relate_logx.Error(err)
}
if has == false {
return 0, nil
@@ -41,7 +41,7 @@ func (a AdminDb) GetAdmin(id int) (m *model.Admin, err error) {
m = new(model.Admin)
has, err := a.Db.Where("adm_id =?", id).Get(m)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil
@@ -53,7 +53,7 @@ func (a AdminDb) GetAdminByUserName(userName string) (m *model.Admin, err error)
m = new(model.Admin)
has, err := a.Db.Where("username =?", userName).Get(m)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 6
- 6
src/super/implement/admin_role_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/super/dao"
"code.fnuoos.com/zhimeng/model.git/src/super/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"reflect"
"xorm.io/xorm"
)
@@ -19,7 +19,7 @@ type AdminRoleDb struct {
func (a AdminRoleDb) FindAdminRole(id int) (*[]model.AdminRole, error) {
var m []model.AdminRole
if err := a.Db.Where("adm_id =?", id).Find(&m); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}
@@ -27,7 +27,7 @@ func (a AdminRoleDb) FindAdminRole(id int) (*[]model.AdminRole, error) {
func (a AdminRoleDb) FindAdminRoleByRoleId(id int) (*[]model.AdminRole, error) {
var m []model.AdminRole
if err := a.Db.Where("role_id =?", id).Find(&m); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}
@@ -44,7 +44,7 @@ func (a AdminRoleDb) GetAdminRoleByRole(id int) (m *model.AdminRole, err error)
m = new(model.AdminRole)
has, err := a.Db.Where("role_id =?", id).Get(m)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 4
- 4
src/super/implement/agent_list_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/super/dao"
"applet/app/db/super/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/super/dao"
"code.fnuoos.com/zhimeng/model.git/src/super/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"xorm.io/xorm"
)

@@ -19,7 +19,7 @@ func (a AgentListDb) GetAgentList(agentId int) (medium *model.AgentList, err err
medium = new(model.AgentList)
has, err := a.Db.Where("agent_id =?", agentId).Get(medium)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 4
- 4
src/super/implement/medium_list_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/super/dao"
"applet/app/db/super/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/super/dao"
"code.fnuoos.com/zhimeng/model.git/src/super/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"xorm.io/xorm"
)

@@ -19,7 +19,7 @@ func (m MediumListDb) GetMediumList(mediumId int) (medium *model.MediumList, err
medium = new(model.MediumList)
has, err := m.Db.Where("medium_id =?", mediumId).Get(medium)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 6
- 6
src/super/implement/permission_group_implement.go View File

@@ -1,10 +1,10 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/enum"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/enum"
"code.fnuoos.com/zhimeng/model.git/src/super/dao"
"code.fnuoos.com/zhimeng/model.git/src/super/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"xorm.io/xorm"
)

@@ -19,7 +19,7 @@ type PermissionGroupDb struct {
func (p PermissionGroupDb) FindPermissionGroup() (*[]model.PermissionGroup, error) {
var m []model.PermissionGroup
if err := p.Db.Where("state = ?", enum.PermissionGroupStateForNormal).Asc("id").Find(&m); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}
@@ -27,7 +27,7 @@ func (p PermissionGroupDb) FindPermissionGroup() (*[]model.PermissionGroup, erro
func (p PermissionGroupDb) FindPermissionGroupV2() (*[]model.PermissionGroup, error) {
var m []model.PermissionGroup
if err := p.Db.Asc("id").Find(&m); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

+ 1
- 1
src/super/implement/permission_group_permission_implement.go View File

@@ -1,7 +1,7 @@
package implement

import (
"applet/app/db/dao"
"code.fnuoos.com/zhimeng/model.git/src/super/dao"
"xorm.io/xorm"
)



+ 1
- 1
src/super/implement/permission_implement.go View File

@@ -1,7 +1,7 @@
package implement

import (
"applet/app/db/dao"
"code.fnuoos.com/zhimeng/model.git/src/super/dao"
"xorm.io/xorm"
)



+ 5
- 5
src/super/implement/role_implement.go View File

@@ -1,9 +1,9 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"applet/app/utils/logx"
"code.fnuoos.com/zhimeng/model.git/src/super/dao"
"code.fnuoos.com/zhimeng/model.git/src/super/model"
zhios_order_relate_logx "code.fnuoos.com/zhimeng/model.git/utils/logx"
"reflect"
"xorm.io/xorm"
)
@@ -23,7 +23,7 @@ type RoleDb struct {
func (r RoleDb) FindRole() (*[]model.Role, error) {
var m []model.Role
if err := r.Db.Desc("id").Find(&m); err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}
@@ -32,7 +32,7 @@ func (r RoleDb) GetRole() (m *model.Role, err error) {
m = new(model.Role)
has, err := r.Db.Where("id = ?", r.Id).Get(m)
if err != nil {
return nil, logx.Error(err)
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil


+ 2
- 2
src/super/implement/role_permission_group_implement.go View File

@@ -1,8 +1,8 @@
package implement

import (
"applet/app/db/dao"
"applet/app/db/model"
"code.fnuoos.com/zhimeng/model.git/src/super/dao"
"code.fnuoos.com/zhimeng/model.git/src/super/model"
"reflect"
"xorm.io/xorm"
)


+ 388
- 0
utils/convert.go View File

@@ -0,0 +1,388 @@
package zhios_order_relate_utils

import (
"encoding/binary"
"encoding/json"
"fmt"
"math"
"reflect"
"strconv"
"strings"
)

func ToString(raw interface{}, e error) (res string) {
if e != nil {
return ""
}
return AnyToString(raw)
}

func ToInt64(raw interface{}, e error) int64 {
if e != nil {
return 0
}
return AnyToInt64(raw)
}
func IsNil(i interface{}) bool {
vi := reflect.ValueOf(i)
if vi.Kind() == reflect.Ptr {
return vi.IsNil()
}
return false
}
func AnyToBool(raw interface{}) bool {
switch i := raw.(type) {
case float32, float64, int, int64, uint, uint8, uint16, uint32, uint64, int8, int16, int32:
return i != 0
case []byte:
return i != nil
case string:
if i == "false" {
return false
}
return i != ""
case error:
return false
case nil:
return true
}
val := fmt.Sprint(raw)
val = strings.TrimLeft(val, "&")
if strings.TrimLeft(val, "{}") == "" {
return false
}
if strings.TrimLeft(val, "[]") == "" {
return false
}
// ptr type
b, err := json.Marshal(raw)
if err != nil {
return false
}
if strings.TrimLeft(string(b), "\"\"") == "" {
return false
}
if strings.TrimLeft(string(b), "{}") == "" {
return false
}
return true
}

func AnyToInt64(raw interface{}) int64 {
switch i := raw.(type) {
case string:
res, _ := strconv.ParseInt(i, 10, 64)
return res
case []byte:
return BytesToInt64(i)
case int:
return int64(i)
case int64:
return i
case uint:
return int64(i)
case uint8:
return int64(i)
case uint16:
return int64(i)
case uint32:
return int64(i)
case uint64:
return int64(i)
case int8:
return int64(i)
case int16:
return int64(i)
case int32:
return int64(i)
case float32:
return int64(i)
case float64:
return int64(i)
case error:
return 0
case bool:
if i {
return 1
}
return 0
}
return 0
}

func AnyToString(raw interface{}) string {
switch i := raw.(type) {
case []byte:
return string(i)
case int:
return strconv.FormatInt(int64(i), 10)
case int64:
return strconv.FormatInt(i, 10)
case float32:
return Float64ToStr(float64(i))
case float64:
return Float64ToStr(i)
case uint:
return strconv.FormatInt(int64(i), 10)
case uint8:
return strconv.FormatInt(int64(i), 10)
case uint16:
return strconv.FormatInt(int64(i), 10)
case uint32:
return strconv.FormatInt(int64(i), 10)
case uint64:
return strconv.FormatInt(int64(i), 10)
case int8:
return strconv.FormatInt(int64(i), 10)
case int16:
return strconv.FormatInt(int64(i), 10)
case int32:
return strconv.FormatInt(int64(i), 10)
case string:
return i
case error:
return i.Error()
case bool:
return strconv.FormatBool(i)
}
return fmt.Sprintf("%#v", raw)
}

func AnyToFloat64(raw interface{}) float64 {
switch i := raw.(type) {
case []byte:
f, _ := strconv.ParseFloat(string(i), 64)
return f
case int:
return float64(i)
case int64:
return float64(i)
case float32:
return float64(i)
case float64:
return i
case uint:
return float64(i)
case uint8:
return float64(i)
case uint16:
return float64(i)
case uint32:
return float64(i)
case uint64:
return float64(i)
case int8:
return float64(i)
case int16:
return float64(i)
case int32:
return float64(i)
case string:
f, _ := strconv.ParseFloat(i, 64)
return f
case bool:
if i {
return 1
}
}
return 0
}

func ToByte(raw interface{}, e error) []byte {
if e != nil {
return []byte{}
}
switch i := raw.(type) {
case string:
return []byte(i)
case int:
return Int64ToBytes(int64(i))
case int64:
return Int64ToBytes(i)
case float32:
return Float32ToByte(i)
case float64:
return Float64ToByte(i)
case uint:
return Int64ToBytes(int64(i))
case uint8:
return Int64ToBytes(int64(i))
case uint16:
return Int64ToBytes(int64(i))
case uint32:
return Int64ToBytes(int64(i))
case uint64:
return Int64ToBytes(int64(i))
case int8:
return Int64ToBytes(int64(i))
case int16:
return Int64ToBytes(int64(i))
case int32:
return Int64ToBytes(int64(i))
case []byte:
return i
case error:
return []byte(i.Error())
case bool:
if i {
return []byte("true")
}
return []byte("false")
}
return []byte(fmt.Sprintf("%#v", raw))
}

func Int64ToBytes(i int64) []byte {
var buf = make([]byte, 8)
binary.BigEndian.PutUint64(buf, uint64(i))
return buf
}

func BytesToInt64(buf []byte) int64 {
return int64(binary.BigEndian.Uint64(buf))
}

func StrToInt(s string) int {
res, _ := strconv.Atoi(s)
return res
}

func StrToInt64(s string) int64 {
res, _ := strconv.ParseInt(s, 10, 64)
return res
}

func Float32ToByte(float float32) []byte {
bits := math.Float32bits(float)
bytes := make([]byte, 4)
binary.LittleEndian.PutUint32(bytes, bits)

return bytes
}

func ByteToFloat32(bytes []byte) float32 {
bits := binary.LittleEndian.Uint32(bytes)
return math.Float32frombits(bits)
}

func Float64ToByte(float float64) []byte {
bits := math.Float64bits(float)
bytes := make([]byte, 8)
binary.LittleEndian.PutUint64(bytes, bits)
return bytes
}

func ByteToFloat64(bytes []byte) float64 {
bits := binary.LittleEndian.Uint64(bytes)
return math.Float64frombits(bits)
}

func Float64ToStr(f float64) string {
return strconv.FormatFloat(f, 'f', 2, 64)
}
func Float64ToStrPrec1(f float64) string {
return strconv.FormatFloat(f, 'f', 1, 64)
}

func Float64ToStrPrec4(f float64) string {
return strconv.FormatFloat(f, 'f', 4, 64)
}
func Float64ToStrPrec10(f float64) string {
return strconv.FormatFloat(f, 'f', 10, 64)
}
func Float64ToStrPrec8(f float64) string {
return strconv.FormatFloat(f, 'f', 8, 64)
}

func Float64ToStrPrec6(f float64) string {
return strconv.FormatFloat(f, 'f', 6, 64)
}

func Float64ToStrByPrec(f float64, prec int) string {
return strconv.FormatFloat(f, 'f', prec, 64)
}

func Float32ToStr(f float32) string {
return Float64ToStr(float64(f))
}

func StrToFloat64(s string) float64 {
res, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0
}
return res
}
func StrToFormat(s string, prec int) string {
ex := strings.Split(s, ".")
if len(ex) == 2 {
if StrToFloat64(ex[1]) == 0 { //小数点后面为空就是不要小数点了
return ex[0]
}
//看取多少位
str := ex[1]
str1 := str
if prec < len(str) {
str1 = str[0:prec]
} else {
for i := 0; i < prec-len(str); i++ {
str1 += "0"
}
}
if prec > 0 {
return ex[0] + "." + str1
} else {
return ex[0]
}
}
return s
}

func StrToFloat32(s string) float32 {
res, err := strconv.ParseFloat(s, 32)
if err != nil {
return 0
}
return float32(res)
}

func StrToBool(s string) bool {
b, _ := strconv.ParseBool(s)
return b
}

func BoolToStr(b bool) string {
if b {
return "true"
}
return "false"
}

func FloatToInt64(f float64) int64 {
return int64(f)
}

func IntToStr(i int) string {
return strconv.Itoa(i)
}

func Int64ToStr(i int64) string {
return strconv.FormatInt(i, 10)
}

func IntToFloat64(i int) float64 {
s := strconv.Itoa(i)
res, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0
}
return res
}
func Int64ToFloat64(i int64) float64 {
s := strconv.FormatInt(i, 10)
res, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0
}
return res
}

+ 209
- 0
utils/curl.go View File

@@ -0,0 +1,209 @@
package zhios_order_relate_utils

import (
"bytes"
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strings"
"time"
)

var CurlDebug bool

func CurlGet(router string, header map[string]string) ([]byte, error) {
return curl(http.MethodGet, router, nil, header)
}
func CurlGetJson(router string, body interface{}, header map[string]string) ([]byte, error) {
return curl_new(http.MethodGet, router, body, header)
}

// 只支持form 与json 提交, 请留意body的类型, 支持string, []byte, map[string]string
func CurlPost(router string, body interface{}, header map[string]string) ([]byte, error) {
return curl(http.MethodPost, router, body, header)
}

func CurlPut(router string, body interface{}, header map[string]string) ([]byte, error) {
return curl(http.MethodPut, router, body, header)
}

// 只支持form 与json 提交, 请留意body的类型, 支持string, []byte, map[string]string
func CurlPatch(router string, body interface{}, header map[string]string) ([]byte, error) {
return curl(http.MethodPatch, router, body, header)
}

// CurlDelete is curl delete
func CurlDelete(router string, body interface{}, header map[string]string) ([]byte, error) {
return curl(http.MethodDelete, router, body, header)
}

func curl(method, router string, body interface{}, header map[string]string) ([]byte, error) {
var reqBody io.Reader
contentType := "application/json"
switch v := body.(type) {
case string:
reqBody = strings.NewReader(v)
case []byte:
reqBody = bytes.NewReader(v)
case map[string]string:
val := url.Values{}
for k, v := range v {
val.Set(k, v)
}
reqBody = strings.NewReader(val.Encode())
contentType = "application/x-www-form-urlencoded"
case map[string]interface{}:
val := url.Values{}
for k, v := range v {
val.Set(k, v.(string))
}
reqBody = strings.NewReader(val.Encode())
contentType = "application/x-www-form-urlencoded"
}
if header == nil {
header = map[string]string{"Content-Type": contentType}
}
if _, ok := header["Content-Type"]; !ok {
header["Content-Type"] = contentType
}
resp, er := CurlReq(method, router, reqBody, header)
if er != nil {
return nil, er
}
res, err := ioutil.ReadAll(resp.Body)
if CurlDebug {
blob := SerializeStr(body)
if contentType != "application/json" {
blob = HttpBuild(body)
}
fmt.Printf("\n\n=====================\n[url]: %s\n[time]: %s\n[method]: %s\n[content-type]: %v\n[req_header]: %s\n[req_body]: %#v\n[resp_err]: %v\n[resp_header]: %v\n[resp_body]: %v\n=====================\n\n",
router,
time.Now().Format("2006-01-02 15:04:05.000"),
method,
contentType,
HttpBuildQuery(header),
blob,
err,
SerializeStr(resp.Header),
string(res),
)
}
resp.Body.Close()
return res, err
}

func curl_new(method, router string, body interface{}, header map[string]string) ([]byte, error) {
var reqBody io.Reader
contentType := "application/json"

if header == nil {
header = map[string]string{"Content-Type": contentType}
}
if _, ok := header["Content-Type"]; !ok {
header["Content-Type"] = contentType
}
resp, er := CurlReq(method, router, reqBody, header)
if er != nil {
return nil, er
}
res, err := ioutil.ReadAll(resp.Body)
if CurlDebug {
blob := SerializeStr(body)
if contentType != "application/json" {
blob = HttpBuild(body)
}
fmt.Printf("\n\n=====================\n[url]: %s\n[time]: %s\n[method]: %s\n[content-type]: %v\n[req_header]: %s\n[req_body]: %#v\n[resp_err]: %v\n[resp_header]: %v\n[resp_body]: %v\n=====================\n\n",
router,
time.Now().Format("2006-01-02 15:04:05.000"),
method,
contentType,
HttpBuildQuery(header),
blob,
err,
SerializeStr(resp.Header),
string(res),
)
}
resp.Body.Close()
return res, err
}

func CurlReq(method, router string, reqBody io.Reader, header map[string]string) (*http.Response, error) {
req, _ := http.NewRequest(method, router, reqBody)
if header != nil {
for k, v := range header {
req.Header.Set(k, v)
}
}
// 绕过github等可能因为特征码返回503问题
// https://www.imwzk.com/posts/2021-03-14-why-i-always-get-503-with-golang/
defaultCipherSuites := []uint16{0xc02f, 0xc030, 0xc02b, 0xc02c, 0xcca8, 0xcca9, 0xc013, 0xc009,
0xc014, 0xc00a, 0x009c, 0x009d, 0x002f, 0x0035, 0xc012, 0x000a}
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
CipherSuites: append(defaultCipherSuites[8:], defaultCipherSuites[:8]...),
},
},
// 获取301重定向
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
return client.Do(req)
}

// 组建get请求参数,sortAsc true为小到大,false为大到小,nil不排序 a=123&b=321
func HttpBuildQuery(args map[string]string, sortAsc ...bool) string {
str := ""
if len(args) == 0 {
return str
}
if len(sortAsc) > 0 {
keys := make([]string, 0, len(args))
for k := range args {
keys = append(keys, k)
}
if sortAsc[0] {
sort.Strings(keys)
} else {
sort.Sort(sort.Reverse(sort.StringSlice(keys)))
}
for _, k := range keys {
str += "&" + k + "=" + args[k]
}
} else {
for k, v := range args {
str += "&" + k + "=" + v
}
}
return str[1:]
}

func HttpBuild(body interface{}, sortAsc ...bool) string {
params := map[string]string{}
if args, ok := body.(map[string]interface{}); ok {
for k, v := range args {
params[k] = AnyToString(v)
}
return HttpBuildQuery(params, sortAsc...)
}
if args, ok := body.(map[string]string); ok {
for k, v := range args {
params[k] = AnyToString(v)
}
return HttpBuildQuery(params, sortAsc...)
}
if args, ok := body.(map[string]int); ok {
for k, v := range args {
params[k] = AnyToString(v)
}
return HttpBuildQuery(params, sortAsc...)
}
return AnyToString(body)
}

+ 22
- 0
utils/file.go View File

@@ -0,0 +1,22 @@
package zhios_order_relate_utils

import (
"os"
"path"
"strings"
"time"
)

// 获取文件后缀
func FileExt(fname string) string {
return strings.ToLower(strings.TrimLeft(path.Ext(fname), "."))
}

func FilePutContents(fileName string, content string) {
fd, _ := os.OpenFile("./tmp/"+fileName+".logs", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
fd_time := time.Now().Format("2006-01-02 15:04:05")
fd_content := strings.Join([]string{"[", fd_time, "] ", content, "\n"}, "")
buf := []byte(fd_content)
fd.Write(buf)
fd.Close()
}

+ 59
- 0
utils/format.go View File

@@ -0,0 +1,59 @@
package zhios_order_relate_utils

import (
"math"
)

func CouponFormat(data string) string {
switch data {
case "0.00", "0", "":
return ""
default:
return Int64ToStr(FloatToInt64(StrToFloat64(data)))
}
}
func CommissionFormat(data string) string {
if data != "" && data != "0" {
return data
}

return ""
}

func HideString(src string, hLen int) string {
str := []rune(src)
if hLen == 0 {
hLen = 4
}
hideStr := ""
for i := 0; i < hLen; i++ {
hideStr += "*"
}
hideLen := len(str) / 2
showLen := len(str) - hideLen
if hideLen == 0 || showLen == 0 {
return hideStr
}
subLen := showLen / 2
if subLen == 0 {
return string(str[:showLen]) + hideStr
}
s := string(str[:subLen])
s += hideStr
s += string(str[len(str)-subLen:])
return s
}

//SaleCountFormat is 格式化销量
func SaleCountFormat(s string) string {
return s + "已售"
}

// 小数格式化
func FloatFormat(f float64, i int) float64 {
if i > 14 {
return f
}
p := math.Pow10(i)
return float64(int64((f+0.000000000000009)*p)) / p
}

+ 245
- 0
utils/logx/log.go View File

@@ -0,0 +1,245 @@
package zhios_order_relate_logx

import (
"os"
"strings"
"time"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

type LogConfig struct {
AppName string `yaml:"app_name" json:"app_name" toml:"app_name"`
Level string `yaml:"level" json:"level" toml:"level"`
StacktraceLevel string `yaml:"stacktrace_level" json:"stacktrace_level" toml:"stacktrace_level"`
IsStdOut bool `yaml:"is_stdout" json:"is_stdout" toml:"is_stdout"`
TimeFormat string `yaml:"time_format" json:"time_format" toml:"time_format"` // second, milli, nano, standard, iso,
Encoding string `yaml:"encoding" json:"encoding" toml:"encoding"` // console, json
Skip int `yaml:"skip" json:"skip" toml:"skip"`

IsFileOut bool `yaml:"is_file_out" json:"is_file_out" toml:"is_file_out"`
FileDir string `yaml:"file_dir" json:"file_dir" toml:"file_dir"`
FileName string `yaml:"file_name" json:"file_name" toml:"file_name"`
FileMaxSize int `yaml:"file_max_size" json:"file_max_size" toml:"file_max_size"`
FileMaxAge int `yaml:"file_max_age" json:"file_max_age" toml:"file_max_age"`
}

var (
l *LogX = defaultLogger()
conf *LogConfig
)

// default logger setting
func defaultLogger() *LogX {
conf = &LogConfig{
Level: "debug",
StacktraceLevel: "error",
IsStdOut: true,
TimeFormat: "standard",
Encoding: "console",
Skip: 2,
}
writers := []zapcore.WriteSyncer{os.Stdout}
lg, lv := newZapLogger(setLogLevel(conf.Level), setLogLevel(conf.StacktraceLevel), conf.Encoding, conf.TimeFormat, conf.Skip, zapcore.NewMultiWriteSyncer(writers...))
zap.RedirectStdLog(lg)
return &LogX{logger: lg, atomLevel: lv}
}

// initial standard log, if you don't init, it will use default logger setting
func InitDefaultLogger(cfg *LogConfig) {
var writers []zapcore.WriteSyncer
if cfg.IsStdOut || (!cfg.IsStdOut && !cfg.IsFileOut) {
writers = append(writers, os.Stdout)
}
if cfg.IsFileOut {
writers = append(writers, NewRollingFile(cfg.FileDir, cfg.FileName, cfg.FileMaxSize, cfg.FileMaxAge))
}

lg, lv := newZapLogger(setLogLevel(cfg.Level), setLogLevel(cfg.StacktraceLevel), cfg.Encoding, cfg.TimeFormat, cfg.Skip, zapcore.NewMultiWriteSyncer(writers...))
zap.RedirectStdLog(lg)
if cfg.AppName != "" {
lg = lg.With(zap.String("app", cfg.AppName)) // 加上应用名称
}
l = &LogX{logger: lg, atomLevel: lv}
}

// create a new logger
func NewLogger(cfg *LogConfig) *LogX {
var writers []zapcore.WriteSyncer
if cfg.IsStdOut || (!cfg.IsStdOut && !cfg.IsFileOut) {
writers = append(writers, os.Stdout)
}
if cfg.IsFileOut {
writers = append(writers, NewRollingFile(cfg.FileDir, cfg.FileName, cfg.FileMaxSize, cfg.FileMaxAge))
}

lg, lv := newZapLogger(setLogLevel(cfg.Level), setLogLevel(cfg.StacktraceLevel), cfg.Encoding, cfg.TimeFormat, cfg.Skip, zapcore.NewMultiWriteSyncer(writers...))
zap.RedirectStdLog(lg)
if cfg.AppName != "" {
lg = lg.With(zap.String("app", cfg.AppName)) // 加上应用名称
}
return &LogX{logger: lg, atomLevel: lv}
}

// create a new zaplog logger
func newZapLogger(level, stacktrace zapcore.Level, encoding, timeType string, skip int, output zapcore.WriteSyncer) (*zap.Logger, *zap.AtomicLevel) {
encCfg := zapcore.EncoderConfig{
TimeKey: "T",
LevelKey: "L",
NameKey: "N",
CallerKey: "C",
MessageKey: "M",
StacktraceKey: "S",
LineEnding: zapcore.DefaultLineEnding,
EncodeCaller: zapcore.ShortCallerEncoder,
EncodeDuration: zapcore.NanosDurationEncoder,
EncodeLevel: zapcore.LowercaseLevelEncoder,
}
setTimeFormat(timeType, &encCfg) // set time type
atmLvl := zap.NewAtomicLevel() // set level
atmLvl.SetLevel(level)
encoder := zapcore.NewJSONEncoder(encCfg) // 确定encoder格式
if encoding == "console" {
encoder = zapcore.NewConsoleEncoder(encCfg)
}
return zap.New(zapcore.NewCore(encoder, output, atmLvl), zap.AddCaller(), zap.AddStacktrace(stacktrace), zap.AddCallerSkip(skip)), &atmLvl
}

// set log level
func setLogLevel(lvl string) zapcore.Level {
switch strings.ToLower(lvl) {
case "panic":
return zapcore.PanicLevel
case "fatal":
return zapcore.FatalLevel
case "error":
return zapcore.ErrorLevel
case "warn", "warning":
return zapcore.WarnLevel
case "info":
return zapcore.InfoLevel
default:
return zapcore.DebugLevel
}
}

// set time format
func setTimeFormat(timeType string, z *zapcore.EncoderConfig) {
switch strings.ToLower(timeType) {
case "iso": // iso8601 standard
z.EncodeTime = zapcore.ISO8601TimeEncoder
case "sec": // only for unix second, without millisecond
z.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendInt64(t.Unix())
}
case "second": // unix second, with millisecond
z.EncodeTime = zapcore.EpochTimeEncoder
case "milli", "millisecond": // millisecond
z.EncodeTime = zapcore.EpochMillisTimeEncoder
case "nano", "nanosecond": // nanosecond
z.EncodeTime = zapcore.EpochNanosTimeEncoder
default: // standard format
z.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
}
}
}

func GetLevel() string {
switch l.atomLevel.Level() {
case zapcore.PanicLevel:
return "panic"
case zapcore.FatalLevel:
return "fatal"
case zapcore.ErrorLevel:
return "error"
case zapcore.WarnLevel:
return "warn"
case zapcore.InfoLevel:
return "info"
default:
return "debug"
}
}

func SetLevel(lvl string) {
l.atomLevel.SetLevel(setLogLevel(lvl))
}

// temporary add call skip
func AddCallerSkip(skip int) *LogX {
l.logger.WithOptions(zap.AddCallerSkip(skip))
return l
}

// permanent add call skip
func AddDepth(skip int) *LogX {
l.logger = l.logger.WithOptions(zap.AddCallerSkip(skip))
return l
}

// permanent add options
func AddOptions(opts ...zap.Option) *LogX {
l.logger = l.logger.WithOptions(opts...)
return l
}

func AddField(k string, v interface{}) {
l.logger.With(zap.Any(k, v))
}

func AddFields(fields map[string]interface{}) *LogX {
for k, v := range fields {
l.logger.With(zap.Any(k, v))
}
return l
}

// Normal log
func Debug(e interface{}, args ...interface{}) error {
return l.Debug(e, args...)
}
func Info(e interface{}, args ...interface{}) error {
return l.Info(e, args...)
}
func Warn(e interface{}, args ...interface{}) error {
return l.Warn(e, args...)
}
func Error(e interface{}, args ...interface{}) error {
return l.Error(e, args...)
}
func Panic(e interface{}, args ...interface{}) error {
return l.Panic(e, args...)
}
func Fatal(e interface{}, args ...interface{}) error {
return l.Fatal(e, args...)
}

// Format logs
func Debugf(format string, args ...interface{}) error {
return l.Debugf(format, args...)
}
func Infof(format string, args ...interface{}) error {
return l.Infof(format, args...)
}
func Warnf(format string, args ...interface{}) error {
return l.Warnf(format, args...)
}
func Errorf(format string, args ...interface{}) error {
return l.Errorf(format, args...)
}
func Panicf(format string, args ...interface{}) error {
return l.Panicf(format, args...)
}
func Fatalf(format string, args ...interface{}) error {
return l.Fatalf(format, args...)
}

func formatFieldMap(m FieldMap) []Field {
var res []Field
for k, v := range m {
res = append(res, zap.Any(k, v))
}
return res
}

+ 105
- 0
utils/logx/output.go View File

@@ -0,0 +1,105 @@
package zhios_order_relate_logx

import (
"bytes"
"io"
"os"
"path/filepath"
"time"

"gopkg.in/natefinch/lumberjack.v2"
)

// output interface
type WriteSyncer interface {
io.Writer
Sync() error
}

// split writer
func NewRollingFile(dir, filename string, maxSize, MaxAge int) WriteSyncer {
s, err := os.Stat(dir)
if err != nil || !s.IsDir() {
os.RemoveAll(dir)
if err := os.MkdirAll(dir, 0766); err != nil {
panic(err)
}
}
return newLumberjackWriteSyncer(&lumberjack.Logger{
Filename: filepath.Join(dir, filename),
MaxSize: maxSize, // megabytes, MB
MaxAge: MaxAge, // days
LocalTime: true,
Compress: false,
})
}

type lumberjackWriteSyncer struct {
*lumberjack.Logger
buf *bytes.Buffer
logChan chan []byte
closeChan chan interface{}
maxSize int
}

func newLumberjackWriteSyncer(l *lumberjack.Logger) *lumberjackWriteSyncer {
ws := &lumberjackWriteSyncer{
Logger: l,
buf: bytes.NewBuffer([]byte{}),
logChan: make(chan []byte, 5000),
closeChan: make(chan interface{}),
maxSize: 1024,
}
go ws.run()
return ws
}

func (l *lumberjackWriteSyncer) run() {
ticker := time.NewTicker(1 * time.Second)

for {
select {
case <-ticker.C:
if l.buf.Len() > 0 {
l.sync()
}
case bs := <-l.logChan:
_, err := l.buf.Write(bs)
if err != nil {
continue
}
if l.buf.Len() > l.maxSize {
l.sync()
}
case <-l.closeChan:
l.sync()
return
}
}
}

func (l *lumberjackWriteSyncer) Stop() {
close(l.closeChan)
}

func (l *lumberjackWriteSyncer) Write(bs []byte) (int, error) {
b := make([]byte, len(bs))
for i, c := range bs {
b[i] = c
}
l.logChan <- b
return 0, nil
}

func (l *lumberjackWriteSyncer) Sync() error {
return nil
}

func (l *lumberjackWriteSyncer) sync() error {
defer l.buf.Reset()
_, err := l.Logger.Write(l.buf.Bytes())
if err != nil {
return err
}
return nil
}

+ 192
- 0
utils/logx/sugar.go View File

@@ -0,0 +1,192 @@
package zhios_order_relate_logx

import (
"errors"
"fmt"
"strconv"

"go.uber.org/zap"
)

type LogX struct {
logger *zap.Logger
atomLevel *zap.AtomicLevel
}

type Field = zap.Field
type FieldMap map[string]interface{}

// 判断其他类型--start
func getFields(msg string, format bool, args ...interface{}) (string, []Field) {
var str []interface{}
var fields []zap.Field
if len(args) > 0 {
for _, v := range args {
if f, ok := v.(Field); ok {
fields = append(fields, f)
} else if f, ok := v.(FieldMap); ok {
fields = append(fields, formatFieldMap(f)...)
} else {
str = append(str, AnyToString(v))
}
}
if format {
return fmt.Sprintf(msg, str...), fields
}
str = append([]interface{}{msg}, str...)
return fmt.Sprintln(str...), fields
}
return msg, []Field{}
}

func (l *LogX) Debug(s interface{}, args ...interface{}) error {
es, e := checkErr(s)
if es != "" {
msg, field := getFields(es, false, args...)
l.logger.Debug(msg, field...)
}
return e
}
func (l *LogX) Info(s interface{}, args ...interface{}) error {
es, e := checkErr(s)
if es != "" {
msg, field := getFields(es, false, args...)
l.logger.Info(msg, field...)
}
return e
}
func (l *LogX) Warn(s interface{}, args ...interface{}) error {
es, e := checkErr(s)
if es != "" {
msg, field := getFields(es, false, args...)
l.logger.Warn(msg, field...)
}
return e
}
func (l *LogX) Error(s interface{}, args ...interface{}) error {
es, e := checkErr(s)
if es != "" {
msg, field := getFields(es, false, args...)
l.logger.Error(msg, field...)
}
return e
}
func (l *LogX) DPanic(s interface{}, args ...interface{}) error {
es, e := checkErr(s)
if es != "" {
msg, field := getFields(es, false, args...)
l.logger.DPanic(msg, field...)
}
return e
}
func (l *LogX) Panic(s interface{}, args ...interface{}) error {
es, e := checkErr(s)
if es != "" {
msg, field := getFields(es, false, args...)
l.logger.Panic(msg, field...)
}
return e
}
func (l *LogX) Fatal(s interface{}, args ...interface{}) error {
es, e := checkErr(s)
if es != "" {
msg, field := getFields(es, false, args...)
l.logger.Fatal(msg, field...)
}
return e
}

func checkErr(s interface{}) (string, error) {
switch e := s.(type) {
case error:
return e.Error(), e
case string:
return e, errors.New(e)
case []byte:
return string(e), nil
default:
return "", nil
}
}

func (l *LogX) LogError(err error) error {
return l.Error(err.Error())
}

func (l *LogX) Debugf(msg string, args ...interface{}) error {
s, f := getFields(msg, true, args...)
l.logger.Debug(s, f...)
return errors.New(s)
}

func (l *LogX) Infof(msg string, args ...interface{}) error {
s, f := getFields(msg, true, args...)
l.logger.Info(s, f...)
return errors.New(s)
}

func (l *LogX) Warnf(msg string, args ...interface{}) error {
s, f := getFields(msg, true, args...)
l.logger.Warn(s, f...)
return errors.New(s)
}

func (l *LogX) Errorf(msg string, args ...interface{}) error {
s, f := getFields(msg, true, args...)
l.logger.Error(s, f...)
return errors.New(s)
}

func (l *LogX) DPanicf(msg string, args ...interface{}) error {
s, f := getFields(msg, true, args...)
l.logger.DPanic(s, f...)
return errors.New(s)
}

func (l *LogX) Panicf(msg string, args ...interface{}) error {
s, f := getFields(msg, true, args...)
l.logger.Panic(s, f...)
return errors.New(s)
}

func (l *LogX) Fatalf(msg string, args ...interface{}) error {
s, f := getFields(msg, true, args...)
l.logger.Fatal(s, f...)
return errors.New(s)
}

func AnyToString(raw interface{}) string {
switch i := raw.(type) {
case []byte:
return string(i)
case int:
return strconv.FormatInt(int64(i), 10)
case int64:
return strconv.FormatInt(i, 10)
case float32:
return strconv.FormatFloat(float64(i), 'f', 2, 64)
case float64:
return strconv.FormatFloat(i, 'f', 2, 64)
case uint:
return strconv.FormatInt(int64(i), 10)
case uint8:
return strconv.FormatInt(int64(i), 10)
case uint16:
return strconv.FormatInt(int64(i), 10)
case uint32:
return strconv.FormatInt(int64(i), 10)
case uint64:
return strconv.FormatInt(int64(i), 10)
case int8:
return strconv.FormatInt(int64(i), 10)
case int16:
return strconv.FormatInt(int64(i), 10)
case int32:
return strconv.FormatInt(int64(i), 10)
case string:
return i
case error:
return i.Error()
}
return fmt.Sprintf("%#v", raw)
}

+ 23
- 0
utils/serialize.go View File

@@ -0,0 +1,23 @@
package zhios_order_relate_utils

import (
"encoding/json"
)

func Serialize(data interface{}) []byte {
res, err := json.Marshal(data)
if err != nil {
return []byte{}
}
return res
}

func Unserialize(b []byte, dst interface{}) {
if err := json.Unmarshal(b, dst); err != nil {
dst = nil
}
}

func SerializeStr(data interface{}, arg ...interface{}) string {
return string(Serialize(data))
}

+ 203
- 0
utils/string.go View File

@@ -0,0 +1,203 @@
package zhios_order_relate_utils

import (
"fmt"
"github.com/syyongx/php2go"
"math/rand"
"reflect"
"sort"
"strings"
"time"
)

func Implode(glue string, args ...interface{}) string {
data := make([]string, len(args))
for i, s := range args {
data[i] = fmt.Sprint(s)
}
return strings.Join(data, glue)
}

//字符串是否在数组里
func InArr(target string, str_array []string) bool {
for _, element := range str_array {
if target == element {
return true
}
}
return false
}
func InArrToInt(target int, str_array []int) bool {
for _, element := range str_array {
if target == element {
return true
}
}
return false
}

//把数组的值放到key里
func ArrayColumn(array interface{}, key string) (result map[string]interface{}, err error) {
result = make(map[string]interface{})
t := reflect.TypeOf(array)
v := reflect.ValueOf(array)
if t.Kind() != reflect.Slice {
return nil, nil
}
if v.Len() == 0 {
return nil, nil
}
for i := 0; i < v.Len(); i++ {
indexv := v.Index(i)
if indexv.Type().Kind() != reflect.Struct {
return nil, nil
}
mapKeyInterface := indexv.FieldByName(key)
if mapKeyInterface.Kind() == reflect.Invalid {
return nil, nil
}
mapKeyString, err := InterfaceToString(mapKeyInterface.Interface())
if err != nil {
return nil, err
}
result[mapKeyString] = indexv.Interface()
}
return result, err
}

//转string
func InterfaceToString(v interface{}) (result string, err error) {
switch reflect.TypeOf(v).Kind() {
case reflect.Int64, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:
result = fmt.Sprintf("%v", v)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
result = fmt.Sprintf("%v", v)
case reflect.String:
result = v.(string)
default:
err = nil
}
return result, err
}

func HideTrueName(name string) string {
res := "**"
if name != "" {
runs := []rune(name)
leng := len(runs)
if leng <= 3 {
res = string(runs[0:1]) + res
} else if leng < 5 {
res = string(runs[0:2]) + res
} else if leng < 10 {
res = string(runs[0:2]) + "***" + string(runs[leng-2:leng])
} else if leng < 16 {
res = string(runs[0:3]) + "****" + string(runs[leng-3:leng])
} else {
res = string(runs[0:4]) + "*****" + string(runs[leng-4:leng])
}
}
return res
}

func GetQueryParam(uri string) map[string]string {
//根据问号分割路由还是query参数
uriList := strings.Split(uri, "?")
var query = make(map[string]string, 0)
//有参数才处理
if len(uriList) == 2 {
//分割query参数
var queryList = strings.Split(uriList[1], "&")
if len(queryList) > 0 {
//key value 分别赋值
for _, v := range queryList {
var valueList = strings.Split(v, "=")
if len(valueList) == 2 {
value, _ := php2go.URLDecode(valueList[1])
if value == "" {
value = valueList[1]
}
query[valueList[0]] = value
}
}
}
}
return query
}

//JoinStringsInASCII 按照规则,参数名ASCII码从小到大排序后拼接
//data 待拼接的数据
//sep 连接符
//onlyValues 是否只包含参数值,true则不包含参数名,否则参数名和参数值均有
//includeEmpty 是否包含空值,true则包含空值,否则不包含,注意此参数不影响参数名的存在
//exceptKeys 被排除的参数名,不参与排序及拼接
func JoinStringsInASCII(data map[string]string, sep string, onlyValues, includeEmpty bool, exceptKeys ...string) string {
var list []string
var keyList []string
m := make(map[string]int)
if len(exceptKeys) > 0 {
for _, except := range exceptKeys {
m[except] = 1
}
}
for k := range data {
if _, ok := m[k]; ok {
continue
}
value := data[k]
if !includeEmpty && value == "" {
continue
}
if onlyValues {
keyList = append(keyList, k)
} else {
list = append(list, fmt.Sprintf("%s=%s", k, value))
}
}
if onlyValues {
sort.Strings(keyList)
for _, v := range keyList {
list = append(list, AnyToString(data[v]))
}
} else {
sort.Strings(list)
}
return strings.Join(list, sep)
}

//x的y次方
func RandPow(l int) string {
var i = "1"
for j := 0; j < l; j++ {
i += "0"
}
k := StrToInt64(i)
n := rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(k)
ls := "%0" + IntToStr(l) + "v"
str := fmt.Sprintf(ls, n)
//min := int(math.Pow10(l - 1))
//max := int(math.Pow10(l) - 1)
return str
}

//根据显示长度截取字符串
func ShowSubstr(s string, l int) string {
if len(s) <= l {
return s
}
ss, sl, rl, rs := "", 0, 0, []rune(s)
for _, r := range rs {
rint := int(r)
if rint < 128 {
rl = 1
} else {
rl = 2
}
if sl+rl > l {
break
}
sl += rl
ss += string(r)
}
return ss
}

+ 29
- 0
utils/time2s.go View File

@@ -0,0 +1,29 @@
package zhios_order_relate_utils

import "time"

func Time2String(date time.Time, format string) string {
if format == "" {
format = "2006-01-02 15:04:05"
}
timeS := date.Format(format)
if timeS == "0001-01-01 00:00:00" {
return ""
}
return timeS
}
func String2Time(timeStr string) time.Time {
toTime, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local)
if err != nil {
return time.Now()
}
return toTime
}

//GetDiffDays 获取两个时间相差的天数,0表同一天,正数表t1>t2,负数表t1<t2
func GetDiffDays(t1, t2 time.Time) int {
t1 = time.Date(t1.Year(), t1.Month(), t1.Day(), 0, 0, 0, 0, time.Local)
t2 = time.Date(t2.Year(), t2.Month(), t2.Day(), 0, 0, 0, 0, time.Local)

return int(t1.Sub(t2).Hours() / 24)
}

Loading…
Cancel
Save