heldiamgo

package module
v0.0.0-...-710c528 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2019 License: MIT Imports: 38 Imported by: 0

README

go

个人golang常用工具包

proxy 设置

随着 go1.11 的发布,go 官方引入了 go module 来解决依赖管理问题,go module 被集成到原生的 go cmd 中,但是如果你的代码库在$GOPATH中,go1.11 的 module 功能是默认不会开启的,想要开启也非常简单, 通过一个环境变量即可开启go module:

export GO111MODULE=on

当我们使用go的时候,go默认会直接从代码库中去下载所需的相关依赖,GOPROXY 这个环境变量可以让我们控制自己从哪里去下载源代码,如果 GOPROXY 没有设置,go 会直接从代码库下载相关依赖代码。如果你像下面这样设置了这个环境变量,那么你就会通过 goproxy.io 下载所有的源代码。

export GOPROXY=https://goproxy.io

你可以通过置空这个环境变量来关闭,export GOPROXY=

以前大家执行 go get golang.org/x/net net代码库会下载到本地GOPATH中,以后有任何项目引用到了 golang.org/x/net 都不会再去下载这个代码库,因为本地GOPATH已经有了,哪怕版本不对,golang也会引用。但是随着 module 概念引入go语言,每个引入的 module 拥有了 version。随着代码库的不断更新迭代,大家即使是对同一个代码库的引用也可能用了不同的tag 或者 commit hash,基于这个现状,go1.11 的 module 会比以前更频繁的下载源代码。但是基于中国有中国特色的互联网,我们有时候很难get到我们需要的依赖源代码,进而导致项目编译失败,CI失败。于是,我们需要一个proxy。

how to create

echo "# golib4db" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/bigdot123456/golib4db.git
git push -u origin master

how to use


just open go.mod

include which lib ?
  1. redis
  2. db linker
  3. crypto
  4. error dispose
  5. log

FAQ

  • I/O Timeout Errors The golang.org domain may be blocked from some countries. go get usually produces an error like the following when this happens:
$ go get -u google.golang.org/grpc
package google.golang.org/grpc: unrecognized import path "google.golang.org/grpc" (https fetch: Get https://google.golang.org/grpc?go-get=1: dial tcp 216.239.37.1:443: i/o timeout)
To build Go code, there are several options:
solving method
  1. Set up a VPN and access google.golang.org through that.

  2. Without Go module support: git clone the repo manually:

git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc

You will need to do the same for all of grpc's dependencies in golang.org, e.g. golang.org/x/net.

  1. With Go module support: it is possible to use the replace feature of go mod to create aliases for golang.org packages. In your project's directory:

go mod edit -replace=google.golang.org/grpc=github.com/grpc/grpc-go@latest
go mod tidy
go mod vendor
go build -mod=vendor

Again, this will need to be done for all transitive dependencies hosted on golang.org as well. Please refer to this issue in the golang repo regarding this concern.

Compiling error, undefined: grpc.SupportPackageIsVersion

Please update proto package, gRPC package and rebuild the proto files:


go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
go get -u google.golang.org/grpc
protoc --go_out=plugins=grpc:. *.proto

How to turn on logging

The default logger is controlled by the environment variables. Turn everything on by setting:

GRPC_GO_LOG_VERBOSITY_LEVEL=99 GRPC_GO_LOG_SEVERITY_LEVEL=info

The RPC failed with error "code = Unavailable desc = transport is closing" This error means the connection the RPC is using was closed, and there are many possible reasons, including:

  1. mis-configured transport credentials, connection failed on handshaking
  2. bytes disrupted, possibly by a proxy in between
  3. server shutdown

It can be tricky to debug this because the error happens on the client side but the root cause of the connection being closed is on the server side. Turn on logging on both client and server, and see if there are any transport errors.

Documentation

Index

Constants

View Source
const (
	DateFormat     = "2006-01-02"
	DateTimeFormat = "2006-01-02 15:04:05"
	TimeFormat     = "15:04:05"
)

时间格式

View Source
const TracingChild = 1
View Source
const TracingFollowsFrom = 2

Variables

View Source
var (
	LockFail   = err1.NewError(-100, "锁失败")
	UnlockFail = err1.NewError(-101, "解锁失败")
)
View Source
var EnableMetrics = false //是否开启性能统计
View Source
var MetricsCancel context.CancelFunc
View Source
var MetricsRegistry metrics.Registry
View Source
var Tracing = true

开启追踪

Functions

func DateEndTimeString

func DateEndTimeString(t time.Time) string

日期结束时间

func DateStartTimeString

func DateStartTimeString(t time.Time) string

日期起始时间

func Decimal

func Decimal(value float64, preciseDigits int) float64

浮点数保留指定的位数 @value float64 要转换的浮点数值 @preciseDigits int 要保留的位数

func ID

func ID() uint64

生成唯一数字ID

func IDGen

func IDGen() string

生成数字ID带日期

func IsChineseChar

func IsChineseChar(str string) bool

判断是否有中文

func IsEmail

func IsEmail(emailaddress string) bool

验证是否是有效的邮箱

func IsHomePhone

func IsHomePhone(phone string) bool

验证是否为家庭电话

func IsIdCard

func IsIdCard(Identnumber string) bool

验证是否有效的身份证号码

func IsPhone

func IsPhone(phonenumber string) bool

验证是否是有效的手机号

func IsTimeString

func IsTimeString(timeString string, timeFormat string) bool

验证是否是时间字符串

func JsonString

func JsonString(obj interface{}) string

json数据

func MetricExpHandler

func MetricExpHandler() http.Handler

爆露性能统计http接口

func PprofHttpHandler

func PprofHttpHandler() (string, http.Handler)

func RandCode

func RandCode(len int, onlynumber bool) string

生成随机字符串,len字符串长度,onlynumber 是否只包含数字

func RemoveStringArrayDuplicate

func RemoveStringArrayDuplicate(list []string) []string

字符串数组去重

func SetLogger

func SetLogger(lg logs.Logger)

设置日志

func StartMetrics

func StartMetrics(influxdbURL string, influxdbName string,
	influxdbUser string, influxdbPwd string)

开启性能统计

func StopMetrics

func StopMetrics()

结束性能统计

func StringSliceIsRepeat

func StringSliceIsRepeat(slc []string) bool

判断字符串类型的切片元素是否重复

func TimeNow

func TimeNow() string

当前日期时间

func UUID

func UUID() string

Types

type Circle

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

圆形 https://blog.golang.org/go-imagedraw-package

func NewCircle

func NewCircle(p image.Point, r int) *Circle

新建一个圆形,p为圆形中心点. r为半径

func (*Circle) At

func (c *Circle) At(x, y int) color.Color

func (*Circle) Bounds

func (c *Circle) Bounds() image.Rectangle

func (*Circle) ColorModel

func (c *Circle) ColorModel() color.Model

type Context

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

上下文

func NewContext

func NewContext(operationName string) *Context

初始化上下文

func NewContextWithTracing

func NewContextWithTracing(tracingSpan TracingSpan) *Context

初始化上下文

func (*Context) Copy

func (t *Context) Copy() IContext

Copy

func (*Context) Finish

func (t *Context) Finish()

Finish

func (*Context) Logf

func (t *Context) Logf(fields ...opentracinglog.Field) IContext

日志

func (*Context) SetTracingType

func (t *Context) SetTracingType(tracingType int)

func (*Context) Start

func (t *Context) Start(operationName string) TracingContext

Start

func (*Context) TracingSpan

func (t *Context) TracingSpan() TracingSpan

追踪信息获取,可能返回nil

type Ellipse

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

椭圆形

func (*Ellipse) At

func (c *Ellipse) At(x, y int) color.Color

func (*Ellipse) Bounds

func (c *Ellipse) Bounds() image.Rectangle

func (*Ellipse) ColorModel

func (c *Ellipse) ColorModel() color.Model

func (*Ellipse) SetBounds

func (c *Ellipse) SetBounds(rect image.Rectangle)

func (*Ellipse) SetRadius

func (c *Ellipse) SetRadius(radius int)

type EtcdLockFactory

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

func NewEtcdLockFactory

func NewEtcdLockFactory(endpoints []string) (*EtcdLockFactory, error)

初始化ETCD连接

func (*EtcdLockFactory) Close

func (e *EtcdLockFactory) Close()

关闭etcd对象

func (*EtcdLockFactory) GetEtcdClient

func (e *EtcdLockFactory) GetEtcdClient() *clientv3.Client

获取etcd连接对象

func (*EtcdLockFactory) GetEtcdSession

func (e *EtcdLockFactory) GetEtcdSession() (*concurrency.Session, error)

获取etcd会话

func (*EtcdLockFactory) GetLock

func (e *EtcdLockFactory) GetLock(path string) (*Lock, error)

获取一个分布式锁对象。如果出错会painc需要处理panic情况

type HandleFunc

type HandleFunc func()

type IContext

type IContext interface {
	TracingContext

	Copy() IContext

	SetTracingType(int)

	Logf(fields ...opentracinglog.Field) IContext

	TracingSpan() TracingSpan
}

func ContextChild

func ContextChild(parentCtx IContext) IContext

ChildOf

func ContextFollows

func ContextFollows(parentCtx IContext) IContext

FollowsFrom

type JSTemplate

type JSTemplate struct {
	ExtendType string //扩展文件名
	Cache      bool   //是否缓存
	// contains filtered or unexported fields
}

JSTemplate JS模版引擎

func NewJSTemplate

func NewJSTemplate(TemplateDIR string, ExtendType ...string) *JSTemplate

NewJSTemplate 深层JS模版引擎对象

func (*JSTemplate) Error

func (je *JSTemplate) Error() error

Error 错误记录

func (*JSTemplate) SetTemplateDir

func (je *JSTemplate) SetTemplateDir(TemplateDir string)

SetTemplateDir 设置模版目录

func (*JSTemplate) Template

func (je *JSTemplate) Template(body []byte, params ...interface{}) ([]byte, error)

Template 解析模版

@Param body 模版内容

@Param params 模版参数

type Lock

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

锁对象

func (*Lock) CallFunc

func (l *Lock) CallFunc(fun func() err1.Error) err1.Error

回调处理

func (*Lock) IsLock

func (l *Lock) IsLock() bool

func (*Lock) Lock

func (l *Lock) Lock()

func (*Lock) LockErr

func (l *Lock) LockErr() error

func (*Lock) Unlock

func (l *Lock) Unlock()

解锁

type Ms15LenIDGenerator

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

毫秒级15位ID生成器

func NewMs15LenIDGenerator

func NewMs15LenIDGenerator(workID int64) *Ms15LenIDGenerator

实例化毫秒15位一个ID生成器

func (*Ms15LenIDGenerator) NextID

func (mig *Ms15LenIDGenerator) NextID() (int64, error)

生成下一个ID

type RedisKeyValue

type RedisKeyValue struct {
	Key   string
	Value string
}

redis键值

type RedisUtil

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

RedisUtil redis操作工具

func InitializeRedis

func InitializeRedis(host, password, db string, maxidle, maxactive int) *RedisUtil

初始化redis,host=地址,password密码,db数据名称,maxidle最大有效连接数,active 最大可用连接数

func (*RedisUtil) DEL

func (r *RedisUtil) DEL(key ...interface{}) int

DEL 删除 @return 返回删除的个数,-1代表错误

func (*RedisUtil) Debug

func (r *RedisUtil) Debug(b bool)

设置是否调试,调试状态不进入真正缓存

func (*RedisUtil) EXPIRE

func (r *RedisUtil) EXPIRE(key string, expireTime int64) int

EXPIRE 设置过期时间 @return -1=错误,0=key不存在, 1=成功

func (*RedisUtil) GET

func (r *RedisUtil) GET(key string) string

GET 获取 @return 如果key不存在返回空

func (*RedisUtil) GETEXP

func (r *RedisUtil) GETEXP(key string, expireTime int64) string

GETEXP 获取值并更新过期时间 @return 如果key不存在返回空

func (*RedisUtil) GETSET

func (r *RedisUtil) GETSET(key, value string) string

GETSET 获取旧值并设置新值 @return 如果key不存在返回空

func (*RedisUtil) GetConn

func (r *RedisUtil) GetConn(fun func(redis.Conn))

GetConn 获取redis链接

func (*RedisUtil) INCRBY

func (r *RedisUtil) INCRBY(key string, increment int64) (int64, error)

原子操作

func (*RedisUtil) KEYS

func (r *RedisUtil) KEYS(pattern string) ([]string, error)

KEYS 获取key集合 @param {string} pattern 匹配模式 Supported glob-style patterns: h?llo matches hello, hallo and hxllo h*llo matches hllo and heeeello h[ae]llo matches hello and hallo, but not hillo h[^e]llo matches hallo, hbllo, ... but not hello h[a-b]llo matches hallo and hbllo Use \ to escape special characters if you want to match them verbatim. @return 返回符合patten的key

func (*RedisUtil) MGET

func (r *RedisUtil) MGET(keys ...string) ([]string, error)

批量获取

func (*RedisUtil) MGETWithKeyPattern

func (r *RedisUtil) MGETWithKeyPattern(pattern string) ([]*RedisKeyValue, error)

按key的正则方式批量获取

func (*RedisUtil) Mutex

func (r *RedisUtil) Mutex(key string, options ...redsync.Option) *redsync.Mutex

redis分布式锁对象

func (*RedisUtil) Prefix

func (r *RedisUtil) Prefix() string

缓存前缀

func (*RedisUtil) SADD

func (r *RedisUtil) SADD(key, member string) (int64, error)

将元素添加到集合,返回0/1(失败/成功)

func (*RedisUtil) SCARD

func (r *RedisUtil) SCARD(key string) (int64, error)

返回集合key成员数量

func (*RedisUtil) SET

func (r *RedisUtil) SET(key, value string) bool

SET 设置值

func (*RedisUtil) SETEX

func (r *RedisUtil) SETEX(key, value string, expireTime int64) bool

SETEX 设置值和过期时间

func (*RedisUtil) SISMEMBER

func (r *RedisUtil) SISMEMBER(key string, member string) bool

判断序集合key是否包含成员member

func (*RedisUtil) SMEMBERS

func (r *RedisUtil) SMEMBERS(key string) ([]string, error)

获取集合所有值

func (*RedisUtil) SREM

func (r *RedisUtil) SREM(key string, member string) (int64, error)

移除集合key中指定成员的排名,返回移除数量

func (*RedisUtil) SetLogger

func (r *RedisUtil) SetLogger(lg logs.Logger)

设置日志

func (*RedisUtil) SetPrefix

func (r *RedisUtil) SetPrefix(prefix string)

设置缓存前缀

func (*RedisUtil) ZADD

func (r *RedisUtil) ZADD(key string, score float64, member string) (int64, error)

将元素添加有序集合,返回0/1(失败/成功)

func (*RedisUtil) ZCARD

func (r *RedisUtil) ZCARD(key string) (int64, error)

返回有序集合key成员数量

func (*RedisUtil) ZINCRBY

func (r *RedisUtil) ZINCRBY(key string, increment int64, member string) (int64, error)

为有序集合key成员score增加值

func (*RedisUtil) ZRANGE

func (r *RedisUtil) ZRANGE(key string, start, stop int64, withscores bool) ([]string, error)

返回有序集合key中,指定区间的成员(按score从小到大排序)

func (*RedisUtil) ZRANK

func (r *RedisUtil) ZRANK(key string, member string) (int64, error)

返回有序集合key中,指定成员的排名(按score从小到大排序),第一名为0

func (*RedisUtil) ZREM

func (r *RedisUtil) ZREM(key string, member string) (int64, error)

移除有序集合key中指定成员的排名,返回移除数量

func (*RedisUtil) ZREVRANGE

func (r *RedisUtil) ZREVRANGE(key string, start, stop int64, withscores bool) ([]string, error)

返回有序集合key中,指定区间的成员(按score从大到小排序)

func (*RedisUtil) ZREVRANK

func (r *RedisUtil) ZREVRANK(key string, member string) (int64, error)

返回有序集合key中,指定成员的排名(按score从大到小排序),第一名为0

func (*RedisUtil) ZSCORE

func (r *RedisUtil) ZSCORE(key string, member string) (float64, error)

返回有序集合成员score值

type TracingContext

type TracingContext interface {
	//Start 注意:由于该方法可能会进行连级调用所以不允许返回nil
	Start(operationName string) TracingContext

	//Finish 标记追踪结束
	Finish()
}

追踪上下文

type TracingSpan

type TracingSpan interface {
	//SpanContext
	SpanContext() opentracing.SpanContext

	//context.Context
	Context(ctx context.Context) context.Context

	//Span
	Span() opentracing.Span

	//ChildOf
	ChildOf(operationName string) TracingSpan

	//FollowsFrom
	FollowsFrom(operationName string) TracingSpan

	//日志
	Logf(fields ...opentracinglog.Field)

	//Finish
	Finish()

	//Start
	Start(operationName string) TracingSpan

	//InjectHttpHeader
	InjectHttpHeader(header http.Header)
}

func NewTracingSpanExtractHttpRequest

func NewTracingSpanExtractHttpRequest(req *http.Request) TracingSpan

解析一个HTTP追踪请求

func NewTracingSpanStart

func NewTracingSpanStart(operationName string) TracingSpan

新建一个追踪

type TracingSpanImpl

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

数据

func (*TracingSpanImpl) ChildOf

func (t *TracingSpanImpl) ChildOf(operationName string) TracingSpan

ChildOf

func (*TracingSpanImpl) Context

func (t *TracingSpanImpl) Context(ctx context.Context) context.Context

context.Context

func (*TracingSpanImpl) Finish

func (t *TracingSpanImpl) Finish()

Finish

func (*TracingSpanImpl) FollowsFrom

func (t *TracingSpanImpl) FollowsFrom(operationName string) TracingSpan

FollowsFrom

func (*TracingSpanImpl) InjectHttpHeader

func (t *TracingSpanImpl) InjectHttpHeader(header http.Header)

编码HTTP请求

func (*TracingSpanImpl) Logf

func (t *TracingSpanImpl) Logf(fields ...opentracinglog.Field)

日志

func (*TracingSpanImpl) Span

func (t *TracingSpanImpl) Span() opentracing.Span

Span

func (*TracingSpanImpl) SpanContext

func (t *TracingSpanImpl) SpanContext() opentracing.SpanContext

SpanContext

func (*TracingSpanImpl) Start

func (t *TracingSpanImpl) Start(operationName string) TracingSpan

Start

Directories

Path Synopsis
rsa
db
mssql
package gosql mssql工具包..引用"github.com/denisenkom/go-mssqldb"
package gosql mssql工具包..引用"github.com/denisenkom/go-mssqldb"
mysql
package gosql mysql工具包..引用"github.com/go-sql-driver/mysql"
package gosql mysql工具包..引用"github.com/go-sql-driver/mysql"
cmd

Jump to

Keyboard shortcuts

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