utils

package module
v0.0.0-...-d35fdca Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2019 License: Apache-2.0 Imports: 32 Imported by: 0

README

go-utils

Documentation

Index

Constants

View Source
const (
	HANDLER_CANCEL = "wing-handler-cancel"
)
View Source
const (
	XSESSION_KEY = "xsession"
)

Variables

View Source
var (
	ERR_REQUIRE_LOGIN = errors.New("require login")
	ERR_REQUIRE_ADMIN = errors.New("require admin")
	ERR_NO_ACCOUNT    = errors.New("no such account")
	ERR_NO_PERMISSION = errors.New("no permission")
	ERR_CANNOT_MODIFY = errors.New("cannot modify")
	ErrNoItem         = errors.New("no such item")
	ErrExisted        = errors.New("existed")
	ErrNotMatch       = errors.New("not match")
	ErrFormat         = errors.New("format error")

	UtilsErrList = []*errors.Error{ERR_REQUIRE_LOGIN, ERR_REQUIRE_ADMIN, ERR_NO_ACCOUNT,
		ERR_NO_PERMISSION, ERR_CANNOT_MODIFY, ErrNoItem, ErrExisted, ErrNotMatch}
)
View Source
var (
	DEBUG = true
)

Functions

func AddHandlerIgnoreErrors

func AddHandlerIgnoreErrors(errs ...interface{})

func AfterHandler

func AfterHandler(ictx context.Context, o interface{}, err error)

func ArrJoin

func ArrJoin(arrL interface{}, arrR interface{}, keyL, keyR interface{}, joinFunc interface{}) interface{}

func ArrayFilterNotEmpty

func ArrayFilterNotEmpty(arr interface{}) []interface{}

func ArrayGetColumnSet

func ArrayGetColumnSet(arr interface{}, key string) *hashset.Set

func ArrayToHashmap

func ArrayToHashmap(arr interface{}, mapKeyField interface{}) *hashmap.Map

数组转hashmap `mapKeyField`可以是`string`或者是`func`

func BinPath

func BinPath() string

func CancelAfterHandler

func CancelAfterHandler(ictx context.Context)

func ContainsUint32

func ContainsUint32(s []uint32, v uint32) bool

func DefaultString

func DefaultString(v, def string) string

func DefaultUint32

func DefaultUint32(v, def uint32) uint32

func EqualValUint32

func EqualValUint32(a *uint32, b uint32) bool

func FileGetBase64

func FileGetBase64(filenameOrURL string, timeout ...time.Duration) (out string, err error)

func FileRenameExt

func FileRenameExt(s, ext string) string

ext需要带上'.', eg: '.doc'

func FirstError

func FirstError(es ...error) error

获取第一个错误

func FixSetCookie

func FixSetCookie(ctx context.Context)

只保留最新的Set-Cookie

func FormHasValue

func FormHasValue(ctx context.Context, name string) bool

func FormatSqlError

func FormatSqlError(err error) error

func FromPrtZeroUint32

func FromPrtZeroUint32(ptr *uint32) uint32

func GetFileBaseName

func GetFileBaseName(s string) string

func GetIDs

func GetIDs(ms interface{}) []uint32

func GetItemString

func GetItemString(arr []string, index int) (out string, ok bool)

func GetScope

func GetScope(g *gorm.DB) *gorm.Scope

gorm

func GetSelectAttrs

func GetSelectAttrs(g *gorm.DB) []string

func GormAddSelect

func GormAddSelect(g *gorm.DB, fields ...string) *gorm.DB

func GormIn

func GormIn(g *gorm.DB, field string, arg interface{}) *gorm.DB

func GormNotIn

func GormNotIn(g *gorm.DB, field string, arg interface{}) *gorm.DB

func JsonMarshalToString

func JsonMarshalToString(obj interface{}) string

func MapGetColumn

func MapGetColumn(arr interface{}, key string) []interface{}

func MapGetColumnString

func MapGetColumnString(arr interface{}, key string) []string

func MapGetColumnUint32

func MapGetColumnUint32(arr interface{}, key string) []uint32

转换*uint32和uint32

func Md5Sum

func Md5Sum(s string) string

func MinInt

func MinInt(a, b int) int

func NewErrExisted

func NewErrExisted() *errors.Error

func NewErrNotFound

func NewErrNotFound() *errors.Error

func NewErrParams

func NewErrParams() *errors.Error

func NewErrPermission

func NewErrPermission() *errors.Error

func Nothing

func Nothing(...interface{})

func NowPtr

func NowPtr() *time.Time

func ObjectGet

func ObjectGet(v, f interface{}) interface{}

func ParseForm

func ParseForm(v url.Values, outPtr interface{}) (err error)

params必须是ptr

func ParseFormIris

func ParseFormIris(ictx context.Context, params interface{}) (err error)

params必须是ptr

func PrintError

func PrintError(err error)

func PtrOf

func PtrOf(ob interface{}) (out interface{})

只获取类型指针,值不会拷贝

func RandStringRunes

func RandStringRunes(n int) string

func RowsLength

func RowsLength(rows *sql.Rows) (l int)

sql.Rows的长度

func ScopeOmitFields

func ScopeOmitFields(scope *gorm.Scope, fields ...string)

func SqlEscape

func SqlEscape(source string) string

func StrFromUint32

func StrFromUint32(u uint32) string

func StrIsEmpty

func StrIsEmpty(s string) bool

func StrToInt32

func StrToInt32(s string) (r int32)

func StrToUint32

func StrToUint32(s string) (r uint32)

func SubString

func SubString(s string, start, length int) (sub string)

func ToInterfaceArray

func ToInterfaceArray(m interface{}) []interface{}

func ToInterfaceArrayString

func ToInterfaceArrayString(t []string) []interface{}

func ToPrtZeroUint32

func ToPrtZeroUint32(ptr uint32) *uint32

func TrimSpaceArr

func TrimSpaceArr(s []string) (out []string)

Types

type ErrJson

type ErrJson struct {
	Err string `json:"err_msg"`
}

type ErrorList

type ErrorList struct {
	List *sll.List
}

func NewErrorList

func NewErrorList() *ErrorList

func (*ErrorList) AppendE

func (l *ErrorList) AppendE(errs ...error)

只添加非nil的error

func (*ErrorList) FirstError

func (l *ErrorList) FirstError() error

func (*ErrorList) Panic

func (l *ErrorList) Panic()

func (*ErrorList) Run

func (l *ErrorList) Run(fo func() error)

没有错误的时候运行

type IGetDB

type IGetDB interface {
	GetDB() *gorm.DB
}

type IModel

type IModel interface {
	New() interface{}
	GModel() *gorm.DB
	GetPK() interface{}
	GetTableName() string
	GetModel() *Model
	GetDB() *gorm.DB
	SetDB(g *gorm.DB)
	Begin() *gorm.DB
	Rollback() (err error)
	Commit() (err error)
	NewScope() (*gorm.Scope, error)
	Limit(limit interface{}) *gorm.DB
	IsLoaded() bool
	LoadAndSetId(id uint32) error
	Exist(where ...interface{}) bool
	ExistID() bool
	FetchColumnValue(keys ...string) (out interface{})
	Find(out interface{}, where ...interface{}) *gorm.DB
	MakePSlice() interface{}
	BatchInsertBad(items []*Model) (err error)
	Save() error
	FirstOrCreate(where ...interface{}) (err error)
	Update(attrs ...interface{}) error
	Upsert(attrs ...interface{}) error
	GetParent() interface{}
	SetParent(p interface{})
	IsValid() error
	FormatError(err error) error
	Delete() error
	Where(query interface{}, args ...interface{}) *gorm.DB
	FormatSql(sql string, args ...interface{}) string
	SetDBOpt(name string, value interface{}) *gorm.DB
	//连贯操作
	Select(query interface{}, args ...interface{}) *gorm.DB
	// 永久生效
	SetSaveAssociations(v bool)
	//Association(column string)
	Table() *gorm.DB
}

type IModelParent

type IModelParent interface {
	//检测该对象是否符合规则
	IsValid() error
	// 用户格式化数据库错误
	FormatError(err error) error
	FormatFields(str string) string
}

type IModelTime

type IModelTime interface {
	UnsetTime()
}

type MConfig

type MConfig struct {
	AppPath         string //运行路径,一般不设置,测试使用
	Debug           bool
	Addr            string //服务地址
	Host            string
	Mysql           string
	MysqlDebug      bool
	Mongodb         string
	DefaultPassword string `yaml:"default_password"` //默认密码
	MediaPath       string
	WebApps         string
	MaxMediaSize    string `yaml:"max_media_size"`
	CookieExpires   int64  `yaml:"cookie_expires"`
	SiteCreator     struct {
		Mysql string
		WpDir string
	}
	WxConfig WxConfig `yaml:"wechat"`
	Redis    RedisConf
	Task     tconfig.Config

	Cms struct {
	}

	YunCourseTemplate string

	LibreOfficePath    string `yaml:"libreoffice_path"`
	TestAdminSession   string
	TestStudentSession string
	TestTeacherSession string

	Wing struct {
		FaceKey string
		FaceSec string
	}

	Exam struct {
		Mysql string
	}
	// contains filtered or unexported fields
}

main config

var (
	DefaultConfig MConfig
)

func LoadConfig

func LoadConfig(confPath string) (MConfig, error)

func NewConfigFromFile

func NewConfigFromFile(confPath string) (conf MConfig, err error)

func (MConfig) AbsPath

func (m MConfig) AbsPath(apath string) string

获得相对于配置文件的绝对路径

func (MConfig) Get

func (m MConfig) Get(key string) interface{}

func (MConfig) GetConfigPath

func (m MConfig) GetConfigPath() string

func (MConfig) GetString

func (m MConfig) GetString(key, def string) string

type Model

type Model struct {
	ID uint32   `gorm:"primary_key" bson:"ID" orm:"pk;auto;"`
	DB *gorm.DB `gorm:"-" json:"-" bson:"-" form:"-"`

	OmitFields []string `gorm:"-" json:"-" bson:"-" form:"-"`
	// contains filtered or unexported fields
}

func (*Model) AfterDelete

func (m *Model) AfterDelete(scope *gorm.Scope) error

func (*Model) AutoEnd

func (m *Model) AutoEnd(commit bool) (err error)

func (*Model) BatchDelete

func (m *Model) BatchDelete(ids []uint32) (err error)

批量删除

func (*Model) BatchInsertBad

func (m *Model) BatchInsertBad(items []*Model) (err error)

deprecated 最蛋疼的多插入

func (*Model) BeforeDelete

func (m *Model) BeforeDelete(scope *gorm.Scope) error

func (*Model) BeforeUpdate

func (m *Model) BeforeUpdate(scope *gorm.Scope) (err error)

func (*Model) Begin

func (m *Model) Begin() *gorm.DB

func (*Model) Commit

func (m *Model) Commit() (err error)

func (*Model) Delete

func (m *Model) Delete() error

只能删除自己

func (*Model) Exist

func (m *Model) Exist(where ...interface{}) bool

最好ID必须设置,不然会查询全部;如果没有定义的时候没有ID,则无法生效

func (*Model) ExistID

func (m *Model) ExistID() bool

func (*Model) FSave

func (m *Model) FSave() (err error)

会更新全部flied, 强制调用Save方法

func (*Model) FetchColumnValue

func (m *Model) FetchColumnValue(keys ...string) (out interface{})

只返回第一个

func (*Model) Find

func (m *Model) Find(out interface{}, where ...interface{}) (db *gorm.DB)

用了scan的方法

func (*Model) FindList

func (m *Model) FindList(where ...interface{}) (interface{}, error)

返回 *[]*ParentType

func (*Model) First

func (m *Model) First(out interface{}, where ...interface{}) (err error)

func (*Model) FirstOrCreate

func (m *Model) FirstOrCreate(where ...interface{}) (err error)

func (*Model) FormatColumns

func (m *Model) FormatColumns(keys ...string) []string

func (*Model) FormatError

func (m *Model) FormatError(err error) error

格式化错误 IMPORTANT: 记得最后调用 err = p.Model.FormatError(err)

func (*Model) FormatFields

func (m *Model) FormatFields(str string) string

func (*Model) FormatSql

func (m *Model) FormatSql(sql string, args ...interface{}) string

格式化sql,添加自定义变量 $MTABLE = 当前表名

func (*Model) GModel

func (m *Model) GModel() *gorm.DB

func (*Model) GetDB

func (m *Model) GetDB() *gorm.DB

Model.DB 是原始数据库,修改后的都应该通过这个函数读取,列入事务

func (*Model) GetModel

func (m *Model) GetModel() *Model

func (*Model) GetPK

func (m *Model) GetPK() interface{}

func (*Model) GetParent

func (m *Model) GetParent() interface{}

func (*Model) GetTableName

func (m *Model) GetTableName() string

func (*Model) IsLoaded

func (m *Model) IsLoaded() bool

判断是否加载,需要重写

func (*Model) IsValid

func (m *Model) IsValid() (err error)

用法

func (p *Term) IsValid() error {
	errs := make([]error, 1)
	if cutils.IsValidSlug(p.Slug) {
		errs = append(errs, errors.New("Slug not valid"))
	}
	return utils.FirstError(errs...)
}

func (*Model) JoinBy

func (m *Model) JoinBy(g *gorm.DB, selectKeysMap interface{}, lkey, rkey, jtype string) *gorm.DB

被JOIN selectKeysMap = nil | map[string]string k:to SELECT <map> FROM ... JOIN <m.TableName> ON <m.TableName>.<rkey> == <g.Table>.<lkey>

func (*Model) JoinIBy

func (m *Model) JoinIBy(g *gorm.DB, selectKeysMap interface{}, lkey, rkey string) *gorm.DB

inner

func (*Model) JoinLBy

func (m *Model) JoinLBy(g *gorm.DB, selectKeysMap interface{}, lkey, rkey string) *gorm.DB

left

func (*Model) Limit

func (m *Model) Limit(limit interface{}) *gorm.DB

func (*Model) LoadAndSetId

func (m *Model) LoadAndSetId(id uint32) error

func (*Model) LoadById

func (m *Model) LoadById() error

func (*Model) LoadByKey

func (m *Model) LoadByKey(key string, val interface{}) error

func (*Model) MakePSlice

func (m *Model) MakePSlice() interface{}

创建对应父Slice切片的地址,指针 *[]*ParentType

func (*Model) New

func (m *Model) New() interface{}

得到一个基础父类,可以被重写,值不复制

func (*Model) NewScope

func (m *Model) NewScope() (*gorm.Scope, error)

func (*Model) Related

func (m *Model) Related(value interface{}, foreignKeys ...string) error

func (*Model) Rollback

func (m *Model) Rollback() (err error)

func (*Model) Save

func (m *Model) Save() (err error)

会更新全部flied

func (*Model) Select

func (m *Model) Select(query interface{}, args ...interface{}) *gorm.DB

连贯操作

func (*Model) SetDB

func (m *Model) SetDB(g *gorm.DB)

func (*Model) SetDBOpt

func (m *Model) SetDBOpt(name string, value interface{}) *gorm.DB

func (*Model) SetParent

func (m *Model) SetParent(p interface{})

func (*Model) SetSaveAssociations

func (m *Model) SetSaveAssociations(v bool)

TODO 默认应该关闭关联存储

func (*Model) Table

func (m *Model) Table() *gorm.DB

func (*Model) ToMap

func (m *Model) ToMap() map[string]interface{}

使用的时候需要注意标签的导出 `structs:",flatten"`

func (*Model) Update

func (m *Model) Update(attrs ...interface{}) error

func (*Model) Updates

func (m *Model) Updates(values interface{}, ignoreProtectedAttrs ...bool) error

func (*Model) Upsert

func (m *Model) Upsert(attrs ...interface{}) (err error)

func (*Model) Where

func (m *Model) Where(query interface{}, args ...interface{}) *gorm.DB

type ModelTime

type ModelTime struct {
	CreatedAt *time.Time `json:",omitempty"`
	UpdatedAt *time.Time `json:",omitempty"` //updated_at

}

func (*ModelTime) UnsetTime

func (m *ModelTime) UnsetTime()

type RedisConf

type RedisConf struct {
	Addr        string
	Password    string
	Database    string
	UniqueIdKey string
	Prefix      string
}

type WError

type WError struct {
	Err    *errors.Error
	Frames []errors.StackFrame
}

func NewWError

func NewWError(e interface{}) *WError

func (*WError) ErrorStack

func (e *WError) ErrorStack() string

func (*WError) Fmt

func (e *WError) Fmt()

我们只需要知道最短路径

func (*WError) Stack

func (e *WError) Stack() []byte

type WxConfig

type WxConfig struct {
	AppId     string
	MchId     string
	ApiKey    string
	NotifyUrl string
	Token     string //缓存用
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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