utils

package
v0.0.0-...-593c55d Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2019 License: BSD-3-Clause Imports: 53 Imported by: 0

Documentation

Overview

Common and useful utils for the Go project development.

Inclusion criteria:

  • Only rely on the Go standard package
  • Functions or lightweight packages
  • Non-business related general tools

Index

Constants

View Source
const (
	CONNECT  = "CONNECT"
	DELETE   = "DELETE"
	GET      = "GET"
	HEAD     = "HEAD"
	OPTIONS  = "OPTIONS"
	PATCH    = "PATCH"
	POST     = "POST"
	PROPFIND = "PROPFIND"
	PUT      = "PUT"
	TRACE    = "TRACE"
)

HTTP methods

View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + charsetUTF8
	MIMETextXML                          = "text/xml"
	MIMETextXMLCharsetUTF8               = MIMETextXML + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEApplicationMsgpack               = "application/msgpack"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
)

MIME types

View Source
const (
	HeaderAccept              = "Accept"
	HeaderAcceptEncoding      = "Accept-Encoding"
	HeaderAllow               = "Allow"
	HeaderAuthorization       = "Authorization"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderLastModified        = "Last-Modified"
	HeaderLocation            = "Location"
	HeaderUpgrade             = "Upgrade"
	HeaderVary                = "Vary"
	HeaderWWWAuthenticate     = "WWW-Authenticate"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXForwardedProtocol  = "X-Forwarded-Protocol"
	HeaderXForwardedSsl       = "X-Forwarded-Ssl"
	HeaderXUrlScheme          = "X-Url-Scheme"
	HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
	HeaderXRealIP             = "X-Real-IP"
	HeaderXRequestID          = "X-Request-ID"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderServer              = "Server"
	HeaderOrigin              = "Origin"
	HeaderExpires             = "Expires"
	HeaderCacheControl        = "Cache-Control"
	HeaderPragma              = "Pragma"

	// Access control
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	// Security
	HeaderStrictTransportSecurity = "Strict-Transport-Security"
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderXXSSProtection          = "X-XSS-Protection"
	HeaderXFrameOptions           = "X-Frame-Options"
	HeaderContentSecurityPolicy   = "Content-Security-Policy"
	HeaderXCSRFToken              = "X-CSRF-Token"
)

Headers

View Source
const (
	KB int64 = 1 << (10 * iota) // 1 << (10*1)
	MB                          // 1 << (10*2)
	GB                          // 1 << (10*3)
	TB                          // 1 << (10*4)

	LogPackSize   = 1 * MB
	LogBackUpDays = 3
)
View Source
const (
	Version   = "v2.0.0"
	ServeName = "ty-chat"
)
View Source
const (
	Crs = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
)
View Source
const (
	Custom = "2006-01-02 15:04:05"
)
View Source
const (
	ErrCodeNotFound = iota + 1
)
View Source
const (
	UTF8 = "UTF-8"
)

Variables

View Source
var (
	DefCache         CacheInterface
	RedisGlobalCache *RedisCache
	MeCache2         *MemoryCache2
)

DefCache ...

View Source
var (
	ErrUnsupportedMediaType        = NewHTTPError(http.StatusUnsupportedMediaType)
	ErrNotFound                    = NewHTTPError(http.StatusNotFound)
	ErrUnauthorized                = NewHTTPError(http.StatusUnauthorized)
	ErrForbidden                   = NewHTTPError(http.StatusForbidden)
	ErrMethodNotAllowed            = NewHTTPError(http.StatusMethodNotAllowed)
	ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge)
	ErrValidatorNotRegistered      = errors.New("validator not registered")
	ErrRendererNotRegistered       = errors.New("renderer not registered")
	ErrInvalidRedirectCode         = errors.New("invalid redirect status code")
	ErrCookieNotFound              = errors.New("cookie not found")
)

Errors

View Source
var (
	DefaultProcess = Process{
		ListenPort: 9001,
		Mode:       "release",
		CacheType:  "memory",
		Secret:     random.String(32, random.Uppercase+random.Numeric),
	}
	DefaultRedis = Redis{
		Addr:     "127.0.0.1:6379",
		Password: "",
		DB:       1,
	}
	DefaultWxDeveloper = WxDeveloper{
		AppID:     "",
		AppSecret: "",
	}
	DefaultPull = PullBind{
		PullDomain: "yh8.in:39001",
		SoftName:   "ty-chat",
		Branch:     "dev-v1-charles",
		Domain:     "127.0.0.1:9001",
	}

	WebFilePath = filepath.Join(SelfDir(), "conf", "web.ini")

	InIConf = func() *ini.File {
		var (
			f   *ini.File
			err error
		)
		if err = TouchFile(WebFilePath); err != nil {
			panic(err.Error())
		}
		if f, err = ini.Load(WebFilePath); err != nil {
			panic("web.ini 配置文件加载错误:" + err.Error())
		}
		return f
	}()

	//Queue External configuration, you must pass the queue in the use method.
	Queue = make(chan func(), 100)
	Job   = grpool.NewPool(runtime.NumCPU()*100, runtime.NumCPU()*2)
)
View Source
var (
	Cron = func() *cron.Cron {
		cb := cron.New()
		cb.Start()
		return cb
	}()
)
View Source
var DefSecretString = "rYtY0RD5hvN2T0McxjNWfH1MM7PExE0w"

DefSecretString ...

View Source
var (
	// DefaultLoggerConfig is the default Logger middleware config.
	DefaultLoggerConfig = LoggerConfig{
		Skipper: middleware.DefaultSkipper,
		Format: `{"time":"${time_custom}","id":"${id}","remote_ip":"${remote_ip}","referer":"${referer}","host":"${host}",` +
			`"method":"${method}","uri":"${uri}","status":${status},"error":"${error}","latency":${latency},` +
			`"latency_human":"${latency_human}","bytes_in":${bytes_in},"bytes_out":${bytes_out}}` + "\n",
		CustomTimeFormat: "2006-01-02 15:04:05.00000",
		Output:           nil,
		// contains filtered or unexported fields
	}
)
View Source
var DefaultPidFile = filepath.Join(SelfDir(), "PID")

DEFAULT_PID_FILE the default PID file name

View Source
var Delimiter = func() string {
	if runtime.GOOS == "windows" {
		return "\\"
	}
	return "/"
}()

Delimiter ... 文件夹目录分隔符

View Source
var (
	Engine *xorm.EngineGroup
)

Functions

func AESDecrypt

func AESDecrypt(cipherkey, ciphertext []byte) ([]byte, error)

AESDecrypt decrypts a piece of data. The cipherkey argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

func AESEncrypt

func AESEncrypt(cipherkey, src []byte) []byte

AESEncrypt encrypts a piece of data. The cipherkey argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

func BytesToString

func BytesToString(b []byte) string

BytesToString convert []byte type to string type.

func CamelString

func CamelString(s string) string

CamelString converts the accepted string to a camel string (xx_yy to XxYy)

func CopyFile

func CopyFile(dstName, srcName string) (written int64, err error)

CopyFile ...

func CreateDB

func CreateDB() (err error)

创建数据库

func EncryPassword

func EncryPassword(pwd string, key ...string) (string, error)

EncryPassword ... 加密一个密码

func ExtranetIP

func ExtranetIP() (ip string, err error)

ExtranetIP get external IP addr.

func FileExists

func FileExists(name string) bool

FileExists reports whether the named file or directory exists.

func GetFileSize

func GetFileSize(file *os.File) (int64, error)

GetFileSize 获取当前文件大小 kb >>10 , mb >>1e2

func GetPID

func GetPID(pidFile ...string) (pid int64, err error)

func GrepFile

func GrepFile(patten string, filename string) (lines []string, err error)

GrepFile like command grep -E for example: GrepFile(`^hello`, "hello.txt") \n is striped while read

func InSlice

func InSlice(str string, slice []string) bool

func InitCache

func InitCache()

func Initialize

func Initialize()

Initialize ... This method needs to be referenced when the configuration file needs to be initialized

func IntranetIP

func IntranetIP() (string, error)

IntranetIP get internal IP addr.

func IsExportedName

func IsExportedName(name string) bool

IsExportedName is this an exported - upper case - name?

func IsExportedOrBuiltinType

func IsExportedOrBuiltinType(t reflect.Type) bool

IsExportedOrBuiltinType is this type exported or a builtin?

func JsQueryEscape

func JsQueryEscape(s string) string

JsQueryEscape escapes the string in javascript standard so it can be safely placed inside a URL query.

func JsQueryUnescape

func JsQueryUnescape(s string) (string, error)

JsQueryUnescape does the inverse transformation of JsQueryEscape, converting %AB into the byte 0xAB and '+' into ' ' (space). It returns an error if any % is not followed by two hexadecimal digits.

func LoggerWithConfig

func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc

LoggerWithConfig returns a Logger middleware with config. See: `Logger()`.

func MaxSliceInt64

func MaxSliceInt64(slice []int64) int64

MaxSliceInt64 ...

func Md5

func Md5(b []byte) string

Md5 returns the MD5 checksum string of the data.

func Md5string

func Md5string(in string) string

Md5string ...

func MidCors

func MidCors() echo.MiddlewareFunc

func MidGzip

func MidGzip() echo.MiddlewareFunc

func MidLogger

func MidLogger() echo.MiddlewareFunc

Logger returns a middleware that logs HTTP requests.

func MinSliceInt64

func MinSliceInt64(slice []int64) int64

MinSliceInt64 ...

func ObjectName

func ObjectName(obj interface{}) string

ObjectName gets the type name of the object

func PanicTrace

func PanicTrace(kb int) []byte

PanicTrace trace panic stack info.

func RandomBytes

func RandomBytes(n int) []byte

RandomBytes returns securely generated random bytes. It will panic if the system's secure random number generator fails to function correctly.

func ReadObjInformation

func ReadObjInformation(ptr Init) error

ReadObjInformation Read information from the configuration file into a global variable, and if there is no information about the object in the configuration file, write the initial properties of the object to the configuration file.

func Recover

func Recover() echo.MiddlewareFunc

Recover returns a middleware which recovers from panics anywhere in the chain and handles the control to the centralized HTTPErrorHandler.

func RelPath

func RelPath(targpath string) string

RelPath gets relative path.

func SearchFile

func SearchFile(filename string, paths ...string) (fullpath string, err error)

SearchFile Search a file in paths. this is often used in search config file in /etc ~/

func SelfChdir

func SelfChdir()

SelfChdir switch the working path to my own path.

func SelfDir

func SelfDir() string

SelfDir gets compiled executable file directory.

func SelfName

func SelfName() string

SelfName ...

func SelfPath

func SelfPath() string

SelfPath gets compiled executable file absolute path.

func SnakeString

func SnakeString(s string) string

SnakeString converts the accepted string to a snake string (XxYy to xx_yy)

func StatusText

func StatusText(code int) string

func StringToBytes

func StringToBytes(s string) []byte

StringToBytes convert string type to []byte type. NOTE: panic if modify the member value of the []byte.

func TodayDir

func TodayDir(file *os.File) string

TodayDir 获取当前日期目录

func TouchFile

func TouchFile(fileName string) error

TouchFile If the file does not exist, it is created automatically. Do not do anything if the file already exists.

func URLRandomString

func URLRandomString(n int) string

URLRandomString returns a URL-safe, base64 encoded securely generated random string. It will panic if the system's secure random number generator fails to function correctly. The length n must be an integer multiple of 4, otherwise the last character will be padded with `=`.

func VerifyPassword

func VerifyPassword(pwd string, encryptPwd string, key ...string) (bool, error)

VerifyPassword ... 验证一个密码

func WalkDirs

func WalkDirs(targpath string, suffixes ...string) (dirlist []string)

WalkDirs traverses the directory, return to the relative path. You can specify the suffix.

func WritePidFile

func WritePidFile(pidFile ...string)

WritePidFile writes the current PID to the specified file.

Types

type CacheInterface

type CacheInterface interface {
	Get(key string) ([]byte, error)
	//if cannot get value,return 0
	GetInt64(key string) (int64, error)
	//return "" if can't get value
	GetValue(key string) (string, error)
	//bind value to struct point
	Bind(key string, bean interface{}) error
	Set(key string, value interface{}, exp time.Duration) error
	Remember(key string, set func() error) ([]byte, error)
	RememberBind(key string, bean interface{}, set func() error) error
	Exists(key string) bool
	Del(key string) error
	DelAll() error
}

CacheInterface ... 缓存接口

type CurrentIP

type CurrentIP struct {
	IP    string `json:"ip"`
	Place string `json:"place"`
}

func NewCurrentIP

func NewCurrentIP(ip string) (b *CurrentIP, err error)

type Database

type Database struct {
	Type     string `yaml:",omitempty"`
	Address  string
	Port     int
	User     string `yaml:",omitempty"`
	Password string `yaml:",omitempty"`
	DB       string `yaml:",omitempty"`
}

Database configuration Settings

type HTTPError

type HTTPError struct {
	Code     int         `json:"code"`
	Message  interface{} `json:"message"`
	Internal error       `json:"-"` //Errors returned by external dependencies can be stored
}

HTTPError represents an error that occurred while handling a request.

func NewHTTPError

func NewHTTPError(code int, message ...interface{}) *HTTPError

NewHTTPError creates a new HTTPError instance.

func (*HTTPError) Error

func (he *HTTPError) Error() string

Error makes it compatible with `error` interface.

type Init

type Init interface {
	InitFunc() error
}

Init ...

type JSONTime

type JSONTime time.Time

JSONTime ...

func ToDatetime

func ToDatetime(in string) (JSONTime, error)

ToDatetime ...

func (*JSONTime) GobDecode

func (p *JSONTime) GobDecode(data []byte) error

GobDecode implements the gob.GobDecoder interface.

func (JSONTime) GobEncode

func (p JSONTime) GobEncode() ([]byte, error)

GobEncode implements the gob.GobEncoder interface.

func (JSONTime) MarshalJSON

func (p JSONTime) MarshalJSON() ([]byte, error)

MarshalJSON ...

func (*JSONTime) Scan

func (p *JSONTime) Scan(v interface{}) error

Scan valueof time.Time

func (JSONTime) String

func (p JSONTime) String() string

String ...

func (*JSONTime) UnmarshalJSON

func (p *JSONTime) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

func (JSONTime) Value

func (p JSONTime) Value() (driver.Value, error)

Value insert timestamp into mysql need this function.

type Log

type Log struct {
	ConsoleEnable bool
	FileEnable    bool
	FilePath      string // Program current directory;`logs/web`

}

Log Log system Settings The server log system is placed in the "logs/web" directory. Whenever the log file size exceeds 1MB, the system will automatically backup the log file. The system will only back up the log file for the last 3 days.

type Logger

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

func GetWebErrLogger

func GetWebErrLogger() *Logger

func NewLogger

func NewLogger(fName string) (lg *Logger, err error)

func (*Logger) DelDirForDays

func (l *Logger) DelDirForDays()

func (*Logger) GLogger

func (l *Logger) GLogger() (gl *logrus.Logger, err error)

func (*Logger) GetFile

func (l *Logger) GetFile() *os.File

func (*Logger) GetGLogger

func (l *Logger) GetGLogger() *logrus.Logger

func (*Logger) GetLogger

func (l *Logger) GetLogger() Logs

func (*Logger) SetLogger

func (l *Logger) SetLogger(lg Logs)

type LoggerConfig

type LoggerConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper middleware.Skipper

	// Tags to constructed the logger format.
	//
	// - time_unix
	// - time_unix_nano
	// - time_rfc3339
	// - time_rfc3339_nano
	// - time_custom
	// - id (Request ID)
	// - remote_ip
	// - uri
	// - host
	// - method
	// - path
	// - protocol
	// - referer
	// - user_agent
	// - status
	// - error
	// - latency (In nanoseconds)
	// - latency_human (Human readable)
	// - bytes_in (Bytes received)
	// - bytes_out (Bytes sent)
	// - header:<NAME>
	// - query:<NAME>
	// - form:<NAME>
	//
	// Example "${remote_ip} ${status}"
	//
	// Optional. Default value DefaultLoggerConfig.Format.
	Format string `yaml:"format"`

	// Optional. Default value DefaultLoggerConfig.CustomTimeFormat.
	CustomTimeFormat string `yaml:"custom_time_format"`

	// Output is a writer where logs in JSON format are written.
	// Optional. Default value os.Stdout.
	Output io.Writer
	// contains filtered or unexported fields
}

LoggerConfig defines the config for Logger middleware.

type Logs

type Logs interface {
	Printf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
	Panicf(format string, args ...interface{})
}

Logger defines the logging interface.

type Map

type Map interface {
	// Load returns the value stored in the map for a key, or nil if no
	// value is present.
	// The ok result indicates whether value was found in the map.
	Load(key interface{}) (value interface{}, ok bool)
	// Store sets the value for a key.
	Store(key, value interface{})
	// LoadOrStore returns the existing value for the key if present.
	// Otherwise, it stores and returns the given value.
	// The loaded result is true if the value was loaded, false if stored.
	LoadOrStore(key, value interface{}) (actual interface{}, loaded bool)
	// Range calls f sequentially for each key and value present in the map.
	// If f returns false, range stops the iteration.
	Range(f func(key, value interface{}) bool)
	// Random returns a pair kv randomly.
	// If exist=false, no kv data is exist.
	Random() (key, value interface{}, exist bool)
	// Delete deletes the value for a key.
	Delete(key interface{})
	// Clear clears all current data in the map.
	Clear()
	// Len returns the length of the map.
	Len() int
}

Map is a concurrent map with loads, stores, and deletes. It is safe for multiple goroutines to call a Map's methods concurrently.

func AtomicMap

func AtomicMap() Map

AtomicMap creates a concurrent map with amortized-constant-time loads, stores, and deletes. It is safe for multiple goroutines to call a atomicMap's methods concurrently. From go v1.9 sync.Map.

func RwMap

func RwMap(capacity ...int) Map

RwMap creates a new concurrent safe map with sync.RWMutex. The normal Map is high-performance mapping under low concurrency conditions.

type MemoryCache

type MemoryCache struct {
	cache.Cache
}
var (
	MeCache *MemoryCache
)

func NewMemoryCache

func NewMemoryCache() *MemoryCache

func (*MemoryCache) Bind

func (ce *MemoryCache) Bind(key string, bean interface{}) error

func (*MemoryCache) Del

func (ce *MemoryCache) Del(key string) error

func (*MemoryCache) DelAll

func (ce *MemoryCache) DelAll() error

func (*MemoryCache) Exists

func (ce *MemoryCache) Exists(key string) bool

func (*MemoryCache) Get

func (ce *MemoryCache) Get(key string) ([]byte, error)

func (*MemoryCache) GetInt64

func (ce *MemoryCache) GetInt64(key string) (int64, error)

func (*MemoryCache) GetValue

func (ce *MemoryCache) GetValue(key string) (str string, err error)

func (*MemoryCache) Remember

func (ce *MemoryCache) Remember(key string, set func() error) (b []byte, err error)

func (*MemoryCache) RememberBind

func (ce *MemoryCache) RememberBind(key string, bean interface{}, set func() error) error

func (*MemoryCache) Set

func (ce *MemoryCache) Set(key string, value interface{}, exp time.Duration) error

type MemoryCache2

type MemoryCache2 struct {
	Client *buntdb.DB
	// contains filtered or unexported fields
}

MemoryCache ...

func NewMemoryCache2

func NewMemoryCache2() *MemoryCache2

NewMemoryCache ...

func (*MemoryCache2) Bind

func (m *MemoryCache2) Bind(key string, bean interface{}) error

Bind ...

func (*MemoryCache2) Del

func (m *MemoryCache2) Del(key string) error

Del ...

func (*MemoryCache2) DelAll

func (m *MemoryCache2) DelAll() error

DelAll ...

func (*MemoryCache2) Exists

func (m *MemoryCache2) Exists(key string) bool

Exists ...

func (*MemoryCache2) Get

func (m *MemoryCache2) Get(key string) ([]byte, error)

Get ...

func (*MemoryCache2) GetInt64

func (m *MemoryCache2) GetInt64(key string) (i int64, err error)

GetInt64 ...

func (*MemoryCache2) GetValue

func (m *MemoryCache2) GetValue(key string) (string, error)

GetValue ...

func (*MemoryCache2) Remember

func (m *MemoryCache2) Remember(key string, set func() error) (b []byte, err error)

Remember ...

func (*MemoryCache2) RememberBind

func (m *MemoryCache2) RememberBind(key string, bean interface{}, set func() error) error

RememberBind ...

func (*MemoryCache2) Set

func (m *MemoryCache2) Set(key string, value interface{}, exp time.Duration) error

Set ...

type Process

type Process struct {
	// server listen port
	ListenPort int `json:"listen_port" ini:"listen_port" comment:"监听端口"`

	// program run mode,debug or release
	Mode string `json:"mode" ini:"mode" comment:"模式,debug,release"`

	// redis or memory
	CacheType string `json:"cache_type" ini:"cache_type" comment:"redis or memory"`

	// program secret , use to jwt
	Secret string `json:"secret" ini:"secret" comment:"program secret , use to jwt,一定不能修改/删除"`

	ReadTimeOut  time.Duration `json:"read_time_out" ini:"read_time_out"`
	WriteTimeOut time.Duration `json:"write_time_out" ini:"write_time_out"`
}

Process Program global configuration items

func (*Process) InitFunc

func (p *Process) InitFunc() error

InitFunc ReadIn ...

type PullBind

type PullBind struct {
	PullDomain string `json:"pull_domain" ini:"pull_domain"`
	SoftName   string `json:"soft_name" ini:"soft_name"`
	Branch     string `json:"branch" ini:"branch"`
	Domain     string `json:"domain" ini:"domain"`
}

pull config

func (*PullBind) InitFunc

func (p *PullBind) InitFunc() error

type Random

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

Random random string creater.

func NewRandom

func NewRandom(encoderSeed string, ignore ...byte) *Random

NewRandom creates a new padded Encoding defined by the given alphabet.

func (*Random) RandomString

func (r *Random) RandomString(n int) string

RandomString returns a base64 encoded securely generated random string. It will panic if the system's secure random number generator fails to function correctly. The length n must be an integer multiple of 4, otherwise the last character will be padded with `=`.

type Redis

type Redis struct {
	Addr     string `json:"addr" ini:"addr"` // redis server address;example:127.0.0.1:6379
	Password string `json:"password" ini:"password"`
	DB       int    `json:"db" ini:"db"`
}

Redis set;need cacheType = `redis`

func (*Redis) InitFunc

func (p *Redis) InitFunc() error

InitFunc ReadIn ...

type RedisCache

type RedisCache struct {
	Client *redis.Client
	// contains filtered or unexported fields
}

RedisCache ...

func NewRedisCache

func NewRedisCache() *RedisCache

NewRedisCache ...

func (*RedisCache) Bind

func (r *RedisCache) Bind(key string, bean interface{}) error

Bind ...

func (*RedisCache) Del

func (r *RedisCache) Del(key string) error

Del ...

func (*RedisCache) DelAll

func (r *RedisCache) DelAll() error

DelAll ...

func (*RedisCache) Exists

func (r *RedisCache) Exists(key string) bool

Exists ...

func (*RedisCache) Get

func (r *RedisCache) Get(key string) (b []byte, err error)

Get ...

func (*RedisCache) GetInt64

func (r *RedisCache) GetInt64(key string) (int64, error)

GetInt64 ...

func (*RedisCache) GetValue

func (r *RedisCache) GetValue(key string) (string, error)

GetValue ...

func (*RedisCache) JSONSet

func (r *RedisCache) JSONSet(key string, value interface{}, exp time.Duration) error

JSONSet ... 将一个对象序列化成 json 字符串,并进行存储

func (*RedisCache) Remember

func (r *RedisCache) Remember(key string, set func() error) (b []byte, err error)

Remember ...

func (*RedisCache) RememberBind

func (r *RedisCache) RememberBind(key string, bean interface{}, set func() error) error

RememberBind ...

func (*RedisCache) Set

func (r *RedisCache) Set(key string, value interface{}, exp time.Duration) error

Set write operation,and need lock

type ReturnJSON

type ReturnJSON struct {
	Code       int         `json:"code"`
	StatusText string      `json:"status_text"`
	Message    interface{} `json:"message,omitempty"`
}

func NewReturnJSON

func NewReturnJSON() *ReturnJSON

func (*ReturnJSON) Ok

func (r *ReturnJSON) Ok(i interface{}) *ReturnJSON

func (*ReturnJSON) Set

func (r *ReturnJSON) Set(code int, msg interface{}) *ReturnJSON

type WxDeveloper

type WxDeveloper struct {
	AppID     string `json:"app_id" ini:"AppID" comment:""`
	AppSecret string `json:"app_secret" ini:"AppSecret" comment:""`
}

Init ...

func (*WxDeveloper) InitFunc

func (p *WxDeveloper) InitFunc() error

type XOrmConf

type XOrmConf struct {
	UserCache bool
	ShowSQL   bool
	IdleConnS int
	MaxConnS  int
	Master    Database
	Slave     Database `yaml:",flow"`
}

XOrmConf All Database configuration Settings

Jump to

Keyboard shortcuts

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