dsg

package module
v2.0.26 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 12, 2024 License: MIT Imports: 17 Imported by: 0

README

dsg

recommend

dsg is an open source toolkit based on iris, which is mainly used for rapid development and provides some common functions such as: logging, configuration, database, cache, g RPC, etc

install

go get -u github.com/xgpc/dsg/v2

use


//initialize
package main

import (
    "github.com/kataras/iris/v12"
    "github.com/xgpc/dsg/v2"
)

func main() {

    
    // Read the configuration file
    dsg.Load("config.yaml")
    dsg.Default(
        dsg.OptionMysql(dsg.Conf.DBInfo), // start mysql
        dsg.OptionRedis(dsg.Conf.Redis),  // start redis
        dsg.OptionAes(dsg.Conf.AesKey),   // start aes
        dsg.OptionJwt(dsg.Conf.JwtKey),   // start jwt
        dsg.OptionEtcd(dsg.Conf.Etcd),    // start etcd
    )
    // Service code

    api := iris.New()
    
    // api Route loading
    
    
    if dsg.Conf.TLS != "" {
        api.Run(iris.TLS(":8080", "server.crt", "server.key"))
    }else {
        api.Run(iris.Addr(":8080"))    
    }
    
}

use mysql

package main

import "github.com/xgpc/dsg/v2"

func main() {
    // init
    //Read configuration file
    dsg.Load("config.yaml")
    dsg.Default(
        dsg.OptionMysql(dsg.Conf.DBInfo), // use mysql
    )
    // Service code
    // select
    var user User
    err := dsg.DB().Model(user).First(&user, userID).Error
    if err != nil {
        panic(err)
    }

    // install
    user := User{
        Name: "test",
    }
    err := dsg.DB().Model(user).Create(&user).Error
    if err != nil {
        panic(err)
    }

    // delete
    err := dsg.DB().Model(user).Delete(&user, userID).Error
    if err != nil {
        panic(err)
    }

    // update
    err := dsg.DB().Model(user).Where("id", userID).Update(&user).Error
    if err != nil {
        panic(err)
    }
}

type User struct {
    ID   int64  `gorm:"column:id;primaryKey;autoIncrement;not null" json:"id"`
    Name string `gorm:"column:name;type:varchar(255);not null" json:"name"`
}

func (User) TableName() string {
    return "user"
}

use redis

package main

import (
    "context"
    "github.com/xgpc/dsg/v2"
)

func main() {
    redisConn := dsg.Redis()
    background := context.Background()

    redisConn.Set(background, "test", "test", 0)
    redisConn.Get(background, "test")

    redisConn.HSet(background, "test", "test", "test")
    redisConn.HGet(background, "test", "test")

    redisConn.HMSet(background, "test", map[string]interface{}{"test": "test"})
    redisConn.HMGet(background, "test", "test")

    redisConn.HGetAll(background, "test")

    redisConn.LPush(background, "test", "test")
    redisConn.LRange(background, "test", 0, 1)

    redisConn.SAdd(background, "test", "test")
    redisConn.SMembers(background, "test")

    redisConn.ZAdd(background, "test", 1, "test")
    redisConn.ZRange(background, "test", 0, 1)
    
}

use AES and JWT

package main

import (
    "fmt"
    "github.com/kataras/iris/v12"
    "time"
    "github.com/xgpc/dsg/v2"
)

func main() {
    // init
    //Read configuration file
    dsg.Load("config.yaml")
    dsg.Default(
        dsg.OptionAes(dsg.Conf.AesKey), // use aes
        dsg.OptionJwt(dsg.Conf.JwtKey), // use jwt
    )
    // Service code
    // aes
    aesStr := dsg.AESEnCode("test")

    deStr := dsg.AESDeCode(aesStr)
    fmt.Println(deStr)

    // jwt
    var userID uint32 = 1
    token := dsg.CreateToken(userID, time.Hour*24*7)
    fmt.Println(token)

    MapClaims := dsg.ParseToken(token)
    fmt.Println(MapClaims)

    if MapClaims.UserID == userID {
        fmt.Println("success")
    }
    
    // Use with iris
    api := iris.New()
    
    
    // api Route loading
    // dsg.Login is a middleware that verifies the token
    // dsg.Login After successful verification, the user information is stored in the context
    // dsg.NewBase(ctx) is used to get the user ID in the token
    api.Get("/test", dsg.Login, func(ctx iris.Context) {
        
        p := dsg.NewBase(ctx)
        if p.MyId() != UserID {
            panic("error")
        }
        fmt.Println(userID)
    })
    
    // api.Run(iris.Addr(":8080")) ....
}

mysql cond

Database operation
cond use
  package main

import "github.com/xgpc/dsg/v2"

func main() {
    // init
    //Read configuration file
    dsg.Load("config.yaml")
    dsg.Default(
        dsg.OptionMysql(dsg.Conf.DBInfo), // use mysql
    )
    // Service code
    // conditionQuery
    // Paging query
    var list []User
    err = dsg.DB().Scopes(cond.Page(1, 10)).Find(&list).Error
    if err != nil {
        panic(err)
    }

    var ctx iris.Context
    // PageByQuery 
    // 从URLParamIntDefault中获取page和page_size
    dsg.DB().Scopes(cond.PageByQuery(ctx)).Find(&list)
    
    // PageByParams
    // 从GetIntDefault中获取page和page_size
    dsg.DB().Scopes(cond.PageByParams(ctx)).Find(&list)
    
    // cond.Eq id = 1
    dsg.DB().Scopes(cond.Eq("id", 1)).Find(&list)
    
    // cond.NotEq id != 1
    dsg.DB().Scopes(cond.NotEq("id", 1)).Find(&list)
    
    // cond.Gt id > 1
    dsg.DB().Scopes(cond.Gt("id", 1)).Find(&list)
    
    // cond.Gte id >= 1
    dsg.DB().Scopes(cond.Gte("id", 1)).Find(&list)
    
    // cond.Lt id < 1
    dsg.DB().Scopes(cond.Lt("id", 1)).Find(&list)
    
    // cond.Lte id <= 1
    dsg.DB().Scopes(cond.Lte("id", 1)).Find(&list)
    
    // cond.Like name like '%test%'
    dsg.DB().Scopes(cond.Like("name", "test")).Find(&list)
    
    // cond.Starting name like 'test%'
    dsg.DB().Scopes(cond.Starting("name", "test")).Find(&list)
    
    // cond.Ending name like '%test'
    dsg.DB().Scopes(cond.Ending("name", "test")).Find(&list)
    
    // cond.In id in (1,2,3)
    dsg.DB().Scopes(cond.In("id", []int{1, 2, 3})).Find(&list)
    
    // cond.NotIn  id not in (1,2,3)
    dsg.DB().Scopes(cond.NotIn("id", []int{1, 2, 3})).Find(&list)
    
    // cond.Between id between 1 and 10
    dsg.DB().Scopes(cond.Between("id", 1, 10)).Find(&list)
    
    
}

type User struct {
    ID   int64  `gorm:"column:id;primaryKey;autoIncrement;not null" json:"id"`
    Name string `gorm:"column:name;type:varchar(255);not null" json:"name"`
}

func (User) TableName() string {
    return "user"
}      


Error handling

// 报错
// {
//	"code" : exce.CodeSysBusy
//	"msg" : "错误信息"
// }
exce.ThrowSys(exce.CodeSysBusy, "错误信息")

// 中间件 使用
// ExceptionLog 会捕获异常并返回
api := iris.Default()
api.Use(middleware.ExceptionLog)

gRPC

go install google.golang.org/protobuf/cmd/remote-gen-go@v1.26
go install google.golang.org/grpc/cmd/remote-gen-go-grpc@v1.1

Thank you jetbrains for your financial support of this project

Documentation

Overview

Package dsg @Author: asus @Description: $ @File: New @Data: 2022/2/2118:09

Index

Constants

View Source
const (
	CodeSuccess = 0
)

Variables

Functions

func AESDeCode

func AESDeCode(data []byte) string

func AESEnCode

func AESEnCode(data string) []byte

func CheckIDCard

func CheckIDCard(idCard string) bool

func CheckMobile

func CheckMobile(mobile string) bool

func CreateToken

func CreateToken(UserID uint32, ExpiresAt time.Duration) string

CreateToken 创建Token

func DB added in v2.0.9

func DB() *gorm.DB

DB 默认

func Default

func Default(list ...option)

Default dsg初始化后,可以通过dsg.xxx调用各个子功能

func EnMobile

func EnMobile(mobile string) string

func GetEtcdLocalHost added in v2.0.13

func GetEtcdLocalHost() string

func GetServiceList added in v2.0.8

func GetServiceList(serverName string) []etcd.Service

func Listening

func Listening(Port int, Tls string, app *iris.Application)

Listening 开始监听端口

func Load

func Load(configPath string)

func LoadYml added in v2.0.8

func LoadYml(out interface{}, configPath string)

func Login

func Login(ctx iris.Context)

Login 中间件 login

func MaskFirstPartIDCard added in v2.0.19

func MaskFirstPartIDCard(idCard string) string

func MaskMiddlePartIDCard added in v2.0.19

func MaskMiddlePartIDCard(idCard string) string

func MiddlewareJwt

func MiddlewareJwt(ctx iris.Context)

MiddlewareJwt 中间件 login

func OptionAes

func OptionAes(aesKey string) option

func OptionEtcd

func OptionEtcd(conf etcd.Config) func() error

func OptionJwt

func OptionJwt(JwtKey string) func() error

func OptionMysql

func OptionMysql(info mysql.DBInfo) func() error

func OptionRedis

func OptionRedis(config redis.Config) func() error

func ParseToken

func ParseToken(token string) *jwt.MapClaims

ParseToken 解析Token

func Redis added in v2.0.9

func Redis() *redis2.Client

Types

type Base

type Base struct {
	// contains filtered or unexported fields
}

func NewBase

func NewBase(ctx iris.Context) *Base

func (*Base) Ctx

func (p *Base) Ctx() iris.Context

func (*Base) DB

func (p *Base) DB() *gorm.DB

DB 默认

func (*Base) Init

func (p *Base) Init(data interface{})

func (*Base) InitAndBackParam

func (p *Base) InitAndBackParam(data interface{}) (param map[string]interface{})

InitAndBackParam Init返回前端传回的参数

func (*Base) Key

func (p *Base) Key() (rsa []byte)

Key 从header中获取前端公钥

func (*Base) MyId

func (p *Base) MyId() uint32

func (*Base) MyIdToString

func (p *Base) MyIdToString() string

func (*Base) Now added in v2.0.26

func (p *Base) Now() time.Time

func (*Base) NowUnix added in v2.0.26

func (p *Base) NowUnix() int64

func (*Base) Page

func (p *Base) Page() int64

func (*Base) PageSize

func (p *Base) PageSize() int64

func (*Base) Redis

func (p *Base) Redis() *redis.Client

func (*Base) ReplaceParamColumn

func (p *Base) ReplaceParamColumn(data, old interface{}, requestParam map[string]interface{}) map[string]interface{}

func (*Base) SetMyId

func (p *Base) SetMyId(id uint32)

func (*Base) Skip

func (p *Base) Skip() int64

func (*Base) Success

func (p *Base) Success()

func (*Base) SuccessWithData

func (p *Base) SuccessWithData(data interface{})

func (*Base) SuccessWithList

func (p *Base) SuccessWithList(list interface{}, total interface{})

func (*Base) Token

func (p *Base) Token() (token string)

func (*Base) ValidateParam

func (p *Base) ValidateParam(data interface{})

ValidateParam 参数校验

type Config added in v2.0.8

type Config struct {
	TLS    string       `mapstructure:"tls"`
	Etcd   etcd.Config  `mapstructure:"etcd"`
	DBInfo mysql.DBInfo `mapstructure:"db_info"`
	Redis  redis.Config `mapstructure:"redis"`
	JwtKey string       `mapstructure:"jwt_key"`
	AesKey string       `mapstructure:"aes_key"`
}
var Conf Config

type ResJson

type ResJson struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

type ResSign

type ResSign struct {
	RandomStr string
	SignAt    int64
	Sign      string
}

type Response

type Response struct {
	Code  int
	Msg   string
	Data  interface{}
	List  []interface{}
	Total int
}

Directories

Path Synopsis
example
test
Description: etcd demo
Description: etcd demo
cond
Package cond @Author: asus @Description: $ @File: cond @Data: 2022/4/129:54
Package cond @Author: asus @Description: $ @File: cond @Data: 2022/4/129:54
pkg
aes/ecb_aes
Package ecb_aes @Author: asus @Description: $ @File: aes_decrypt @Data: 2022/8/1917:12
Package ecb_aes @Author: asus @Description: $ @File: aes_decrypt @Data: 2022/8/1917:12
guzzle
Package guzzle @Author: asus @Description: $ @File: client @Data: 2022/1/2016:41
Package guzzle @Author: asus @Description: $ @File: client @Data: 2022/1/2016:41
jwt
log
util
Package service @Author: asus @Description: $ @File: random @Data: 2021/12/2318:44
Package service @Author: asus @Description: $ @File: random @Data: 2021/12/2318:44
validator
Package validator @Author: asus @Description: $ @File: registerValidation @Data: 2021/12/311:16
Package validator @Author: asus @Description: $ @File: registerValidation @Data: 2021/12/311:16
zip

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL