std

package
v0.0.0-...-3f61646 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2019 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ConfEnvDevelopment = "development"
	ConfEnvTest        = "ivktest"
	ConfEnvProduction  = "ivkprod"
	ConfEnvStage       = "ivkstage"
)
View Source
const (
	AppFlagStart = 1 * 1000 * 1000 * 1000 * 1000
	ResFlagStart = 100 * 1000 * 1000 * 1000 * 1000

	InvalidAppFlag = AppFlag(invalidAppID)
	SolarAppFlag   = AppFlag(solarAppId)
	MaxAppFlag     = SolarAppFlag

	NonspecificResFlag = ResFlag(nonspecificResTypeID)
)
View Source
const (
	// TagTopic flags the topic
	TagTopic = "topic"

	// TopicCodeTrace traces the running of code
	TopicCodeTrace = "code_trace"

	// TopicBugReport indicates the bug report topic
	TopicBugReport = "bug_report"

	// TopicCrash indicates the program's panics
	TopicCrash = "crash"

	// TopicUserActivity indicates the user activity like web access, user login/logout
	TopicUserActivity = "user_activity"

	// TagCategory tags the log category
	TagCategory = "category"

	// TagError tags the error category
	TagError = "error"

	// CategoryRPC indicates the rpc category
	CategoryRPC = "rpc"

	// CategoryRedis indicates the redis category
	CategoryRedis = "redis"

	// CategoryMySQL indicates the MySQL category
	CategoryMySQL = "mysql"

	// CategoryElasticsearch indicates the Elasticsearch category
	CategoryElasticsearch = "elasticsearch"
)
View Source
const (
	REMIND = 1
)
View Source
const (
	SolarApp = "solar"
)

Variables

View Source
var (
	AllErrors map[int]string = make(map[int]string)

	ErrOK                 = newErr(20000, "OK")
	ErrNotFound           = newErr(40400, "您访问的资源不存在")
	ErrTooManyRequests    = newErr(42900, "您的操作过于频繁,请稍后再试")
	ErrInternal           = newErr(50000, "Internal error")
	ErrInternalFromString = newErr(50001, "[Should never be returned]")
	ErrDatabase           = newErr(50002, "数据库提交数据失败")
	ErrIllegalJson        = newErr(50003, "json数据格式不正确")
	ErrParams             = newErr(50004, "参数不正确")
	ErrRpcCache           = newErr(50005, "RPC cache 错误")
	ErrRpcCacheMarshal    = newErr(50006, "RPC cache 序列化错误")
	ErrRpcCacheUnmarshal  = newErr(50007, "RPC cache 反序列化错误")
	ErrIllegalToken       = newErr(50008, "非法的token")
	ErrNotImplemented     = newErr(50009, "Not Implemented")
	ErrNoData             = newErr(50010, "No Data")
	ErrDumplicate         = newErr(50011, "记录已经存在")
	ErrOtherClientSignIn  = newErr(50012, "其他客户端登录了")
	ErrUserBan            = newErr(50013, "用户已被禁用")
	ErrTokenExpired       = newErr(50014, "登录过期")
	ErrRpcCacheTimeout    = newErr(50015, "RPC cache timeout")
	ErrServerTooBusy      = newErr(50016, "服务器正忙,请稍后再试")
	ErrBadFileToken       = newErr(50017, "Bad file token")
	ErrFileTokenExpired   = newErr(50018, "File token expired")
	ErrSearchNoDisplay    = newErr(50019, "相关搜索结果不予显示")
	ErrPubPriKeyWrong     = newErr(50020, "秘钥不正确")
	ErrIllegalCooperation = newErr(50021, "非白名单合作方")

	ErrUserNotExist = newErr(60001, "用户不存在")
	ErrPassword     = newErr(60002, "用户密码错误")

	ErrMicro = newErr(70000, "未定义的 Micro 错误")
	ErrEcho  = newErr(71000, "未定义的 Echo 错误")

	// 系统管理专用代码段
	ErrNotSysAdmin         = newErr(90001, "非系统管理员")
	ErrSysAdminHasBeenInit = newErr(90002, "系统管理员已初始化")
)

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes 这样定义错误码: 首先看可以归类到哪个HTTP Code, 把这个Code作为错误码的前三位 然后后面两位递增 如果无法/不想归类到HTTP Code, 请用600开头 500** 代表系统错误 依次类推f

Functions

func ConfEnv

func ConfEnv() string

ConfEnv fetches the current runtime environment

func InitLog

func InitLog(conf ConfigLog)

InitLog initializes the logger

func IsSysErr

func IsSysErr(err error, ivkerr *Err) bool

IsSysErr indicates if the error is error.

func LoadConf

func LoadConf(dest interface{}, path string)

LoadConf loads configuration from specified file

func LogDebugLn

func LogDebugLn(args ...interface{})

LogDebugLn records debug information which helps trace the running of program

func LogDebugc

func LogDebugc(category string, message string)

LogDebugc records the running infos

func LogError

func LogError(fields LogFields, message string)

LogError records the running errors which are expected to be solved soon

func LogErrorLn

func LogErrorLn(args ...interface{})

LogErrorLn records the program error, go to fix it!

func LogErrorc

func LogErrorc(category string, err error, message string)

LogErrorc records the running errors which are expected to be solved soon

func LogFatalLn

func LogFatalLn(args ...interface{})

LogFatalLn records the program fatal error, developer should follow immediately

func LogInfo

func LogInfo(fields LogFields, message string)

LogInfo records Info level information which helps trace the running of program and moreover the production infos

func LogInfoLn

func LogInfoLn(args ...interface{})

LogInfoLn records Info level information which helps trace the running of program and moreover the production infos

func LogInfoc

func LogInfoc(category string, message string)

LogInfoc records the running infos

func LogPanic

func LogPanic(fields LogFields, message string)

LogPanic records the running errors which are expected to be severe soon

func LogPanicLn

func LogPanicLn(args ...interface{})

LogPanicLn records the program fatal error, developer should fix otherwise the company dies

func LogPanicc

func LogPanicc(category string, err error, message string)

LogPanicc records the running errors which are expected to be severe soon

func LogRecover

func LogRecover(e interface{})

LogRecover records when program crashes

func LogUserActivity

func LogUserActivity(fields LogFields, message string)

LogUserActivity records user activity, like user access page, login/logout

func LogWarn

func LogWarn(fields LogFields, message string)

LogWarn records the warnings which are expected to be removed, but not influence the running of the program

func LogWarnLn

func LogWarnLn(args ...interface{})

LogWarnLn records the program warning

func LogWarnc

func LogWarnc(category string, err error, message string)

LogWarnc records the running warnings which are expected to be noticed

Types

type APIRateLimit

type APIRateLimit struct {
	Path     string `yaml:"path"`
	Method   string `yaml:"method"`
	Max      int64  `yaml:"max"`
	Duration int64  `yaml:"duration"`
}

APIRateLimit defines the specified API's rate limit.

type AppFlag

type AppFlag int64

func AppFlagFromName

func AppFlagFromName(name string) AppFlag

func (AppFlag) Int64

func (a AppFlag) Int64() int64

func (AppFlag) Name

func (a AppFlag) Name() string

func (AppFlag) Valid

func (a AppFlag) Valid() bool

type ConfigAuthCode

type ConfigAuthCode struct {
	Url          string `yaml:"url"`
	Expiration   int64  `yaml:"expiration"`
	SendInterval int64  `yaml:"send_interval"`
}

type ConfigCassandra

type ConfigCassandra struct {
	Hosts    []string `yaml:"hosts"`
	Keyspace string   `yaml:"keyspace"`
	Port     string   `yaml:"port"`
}

ConfigCassandra sets the Cassandra

type ConfigFormulaService

type ConfigFormulaService struct {
	BaseUrl string `yaml:"base_url"`
}

type ConfigHystrix

type ConfigHystrix struct {
	Enabled              bool        `yaml:"enabled"`
	DashboardPort        int         `yaml:"dashboard_port"`
	ServiceName          string      `yaml:"service_name"`
	ConsulAddrs          []string    `yaml:"consul_addrs"`
	Redis                ConfigRedis `yaml:"redis"`
	CacheExpiration      int         `yaml:"cache_expiration"`
	CacheRefreshInterval int         `yaml:"cache_refresh_interval"`

	DefaultTimeout               int `yaml:"default_timeout"`
	DefaultMaxConcurrent         int `yaml:"default_max_concurrent"`
	DefaultErrorPercentThreshold int `yaml:"default_error_percent_threshold"`
	DefaultSleepWindow           int `yaml:"default_sleep_window"`
	DefaultVolumeThreshold       int `yaml:"default_volume_threshold"`
}

ConfigHystrix sets RPC client error handler and circuit breaker

type ConfigLog

type ConfigLog struct {
	Level            int      `yaml:"level"`
	Path             string   `yaml:"path"`
	FileName         string   `yaml:"file_name"`
	RotationDuration string   `yaml:"rotation_duration"`
	RotationCount    uint     `yaml:"rotation_count"`
	OutputDest       string   `yaml:"output_dest"`
	CIDRs            []string `yaml:"cidrs"`
	SentryDSN        string   `yaml:"sentry_dsn"`
}

ConfigLog sets the logger level and destination

type ConfigMiniProgramAccount

type ConfigMiniProgramAccount struct {
	AppId     string `yaml:"mp_id"`
	AppSecret string `yaml:"mp_secret"`
}

config wechat mp account

type ConfigMysql

type ConfigMysql struct {
	Username       string `yaml:"username"`
	Password       string `yaml:"password"`
	Host           string `yaml:"host"`
	Port           int    `yaml:"port"`
	DBName         string `yaml:"db_name"`
	MaxIdle        int    `yaml:"max_idle"`
	MaxConn        int    `yaml:"max_conn"`
	LogType        string `yaml:"log_type"`
	NotPrintSql    bool   `yaml:"not_print_sql"`
	NotCreateTable bool   `yaml:"not_create_table"`
}

ConfigMysql sets the MySQL

type ConfigNSQ

type ConfigNSQ struct {
	LookupAddress []string `yaml:"lookup_address_list"`
	NsqdAddress   string   `yaml:"addr"`
}

ConfigNSQ sets the NSQ address

type ConfigNsqConsumer

type ConfigNsqConsumer struct {
	TopicName    string   `yaml:"topic_name"`
	ChannelName  string   `yaml:"channel_name"`
	IsLookupAddr bool     `yaml:"is_lookup_addr"`
	AddressList  []string `yaml:"address_list"`
}

config nsq consumer

type ConfigPicService

type ConfigPicService struct {
	ThumbUrl string `yaml:"thumb_url"`
}

type ConfigPrometheus

type ConfigPrometheus struct {
	Enabled       bool   `yaml:"enabled"`
	Namespace     string `yaml:"namespace"`
	BatchInterval int    `yaml:"batch_interval"`
	Collectors    []struct {
		Addr string `yaml:"addr"`
	} `yaml:"collectors"`
}

ConfigPrometheus sets server metrics collectors

type ConfigPubnoService

type ConfigPubnoService struct {
	BaseUrl string `yaml:"base_url"`
}

type ConfigRateLimiter

type ConfigRateLimiter struct {
	// Enabled controls the rate limiter's switch
	Enabled bool `yaml:"enabled"`

	// Redis indicates the rate limiter's redis.
	Redis rate.ConfigRedis `yaml:"redis"`

	// HTTP message when limit is reached.
	Message string `yaml:"message"`

	// Content-Type for Message
	MessageContentType string `yaml:"message_content_type"`

	// HTTP status code when limit is reached.
	StatusCode int `yaml:"status_code"`

	// Maximum number of requests to limit per duration.
	Max int64 `yaml:"max"`

	// Duration of rate-limiter.
	TTL time.Duration `yaml:"ttl"`

	// List of places to look up IP address.
	// Default is "RemoteAddr", "X-Forwarded-For", "X-Real-IP".
	// You can rearrange the order as you like.
	IPLookups []string `yaml:"ip_lookups"`

	// List of HTTP Methods to limit (GET, POST, PUT, etc.).
	// Empty means limit all methods.
	Methods []string `yaml:"methods"`

	// List of HTTP headers to limit.
	// Empty means skip headers checking.
	Headers []string `yaml:"headers"`

	APISettings []APIRateLimit `yaml:"api_settings"`
}

ConfigRateLimiter defines the rate limiter

type ConfigRedis

type ConfigRedis struct {
	Enabled     bool   `yaml:"enabled"`
	Host        string `yaml:"host"`
	Port        int    `yaml:"port"`
	Auth        string `yaml:"auth"`
	IdleTimeout int    `yaml:"idle_timeout"`
}

ConfigRedis sets the Redis

type ConfigRpcCacheRedis

type ConfigRpcCacheRedis struct {
	Enabled     bool              `yaml:"enabled"`
	Addrs       map[string]string `yaml:"addrs"`
	Password    string            `yaml:"password"`
	IdleTimeout int               `yaml:"idle_timeout"`
}

ConfigRpcCacheRedis sets the RPC cache backend by Redis

type ConfigService

type ConfigService struct {
	SvcName          string   `yaml:"svc_name"`
	SvcAddr          string   `yaml:"svc_addr"`
	AdvertiseSubnets []string `yaml:"advertise_subnets"`
	EtcdAddrs        []string `yaml:"etcd_addrs"`
	Consul           []struct {
		Addr string `yaml:"addr"`
	} `yaml:"consul"`
	ZookeeperAddrs []string            `yaml:"zookeeper_addrs"`
	RpcCacheRedis  ConfigRpcCacheRedis `yaml:"rpc_cache_redis"`
	Redis          ConfigRedis         `yaml:"redis"`
	Prometheus     ConfigPrometheus    `yaml:"prometheus"`
	Hystrix        ConfigHystrix       `yaml:"hystrix"`
	Zipkin         ConfigZipkin        `yaml:"zipkin"`
	RateLimiter    ConfigRateLimiter   `yaml:"rate_limiter"`
	RPCServer      string              `yaml:"rpc_server"`
}

ConfigService sets the service's configurations

type ConfigTestToken

type ConfigTestToken struct {
	AppId string `yaml:"app_id"`
}

config wechat test token account

type ConfigUpload

type ConfigUpload struct {
	Path    string `yaml:"path"`
	Url     string `yaml:"url"`
	CdnUrl  string `yaml:"cdn_url"`
	FakeCDN bool   `yaml:"fake_cdn"`
}

type ConfigWebPageShare

type ConfigWebPageShare struct {
	BaseUrl string `yaml:"base_url"`
}

type ConfigWechatAccount

type ConfigWechatAccount struct {
	AppId     string `yaml:"app_id"`
	AppSecret string `yaml:"app_secret"`
	Token     string `yaml:"token"`
	AesKey    string `yaml:"aes_key"`
}

config wechat pa account

type ConfigZipkin

type ConfigZipkin struct {
	Enabled     bool     `yaml:"enabled"`
	BrokerAddrs []string `yaml:"broker_addrs"`
}

ConfigZipkin configures the rpc call tracing system

type DBExtension

type DBExtension struct {
	*gorm.DB
}

func NewDBWrapper

func NewDBWrapper(db *gorm.DB) *DBExtension

func (*DBExtension) Count

func (dw *DBExtension) Count(count *int, query interface{}) error

func (*DBExtension) CountBy

func (dw *DBExtension) CountBy(count *int, byField string, query interface{}) error

func (*DBExtension) ExecSql

func (dw *DBExtension) ExecSql(result interface{}, sql string, args ...interface{}) error

func (*DBExtension) GetFirstNRecords

func (dw *DBExtension) GetFirstNRecords(result interface{}, order string, limit int, query interface{}, args ...interface{}) error

func (*DBExtension) GetList

func (dw *DBExtension) GetList(result interface{}, query interface{}, args ...interface{}) error

func (*DBExtension) GetOne

func (dw *DBExtension) GetOne(result interface{}, query interface{}, args ...interface{}) (found bool, err error)

func (*DBExtension) GetOrderedList

func (dw *DBExtension) GetOrderedList(result interface{}, order string, query interface{}, args ...interface{}) error

func (*DBExtension) GetPageRangeList

func (dw *DBExtension) GetPageRangeList(result interface{}, order string, limit, offset int, query interface{}, args ...interface{}) error

func (*DBExtension) SaveOne

func (dw *DBExtension) SaveOne(value interface{}) error

Update All Fields

func (*DBExtension) SetDB

func (dw *DBExtension) SetDB(db *gorm.DB)

func (*DBExtension) Update

func (dw *DBExtension) Update(attrs interface{}, query interface{}, args ...interface{}) error

Update selected Fields, if attrs is an object, it will ignore default value field; if attrs is map, it will ignore unchanged field.

type Err

type Err struct {
	Code    int
	Message string
}

Err represents the error.

func ErrFromGoErr

func ErrFromGoErr(err error) *Err

ErrFromGoErr transforms the golang error object to error.

func ErrFromString

func ErrFromString(str string) *Err

ErrFromString assembles an error from string.

func NewErr

func NewErr(code int, msg string) *Err

NewErr registers a new error.

func (*Err) Error

func (e *Err) Error() string

func (Err) GetMessage

func (e Err) GetMessage() string

GetMessage fetches message from error.

type LogFields

type LogFields map[string]interface{}

LogFields indicates the log's tags

type ResFlag

type ResFlag int64

func ResFlagFromName

func ResFlagFromName(name string) ResFlag

func (ResFlag) Int64

func (r ResFlag) Int64() int64

func (ResFlag) Name

func (r ResFlag) Name() string

func (ResFlag) Valid

func (r ResFlag) Valid() bool

type Sbool

type Sbool struct {
	Str   string
	Valid bool
}

func NewSbool

func NewSbool(s string) *Sbool

func (*Sbool) String

func (b *Sbool) String() string

Stringer interface

func (*Sbool) Value

func (b *Sbool) Value() bool

type TableNameAble

type TableNameAble interface {
	TableName() string
}

type UpdateAttrs

type UpdateAttrs map[string]interface{}

func NewUpdateAttrs

func NewUpdateAttrs(tableName string) UpdateAttrs

Directories

Path Synopsis
ec
Package ec is an interface for event tracker
Package ec is an interface for event tracker
pb
Package pb is a generated protocol buffer package.
Package pb is a generated protocol buffer package.
msg
Package msg is a generated protocol buffer package.
Package msg is a generated protocol buffer package.
user
Package user is a generated protocol buffer package.
Package user is a generated protocol buffer package.
registry
Package etcdv3 provides an etcd version 3 registry
Package etcdv3 provides an etcd version 3 registry
jsonpb
Package jsonpb provides marshaling and unmarshaling between protocol buffers and JSON.
Package jsonpb provides marshaling and unmarshaling between protocol buffers and JSON.
net

Jump to

Keyboard shortcuts

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