st

package module
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2021 License: Apache-2.0 Imports: 37 Imported by: 0

README

short

Golang 后端开发辅助工具集合

导入

import st "gitee.com/yscsky/short"

服务

app.go提供了一个服务启动的框架,有监听中断信号的功能。

可以自行实现AppInterfaceServerInterface接口,也可以用库中提供的。

参考examples/app_base_usage中代码。

server_gin.go,server_grpc.go是分别实现ServerInterface接口的服务。

可以参考examples下的server_gin_usageserver_grpc_usage中代码。

middleware.go提供的 gin 和 grpc 中间件。

client_http.goclient_grpc.go分别提供了 http 和 grpc 的客户端生成函数,可以参考examples下的client_gin_usageclient_grpc_usage中代码。

prometheus.go添加 prometheus 监控,提供了 http 和 grpc 的中间件。

数据库

db_gorm.go 使用 gorm 连接数据库,内置了 mysql 和 postgres 的连接方式,参考examples/db_gorm_usage中代码。

db_sqlx.go 使用 sqlx 连接数据库,内置了一个加了 statement 缓存的数据库操作结构,参考examples/db_sqlx_usage中代码。

db_redis.go 提供连接 redis 的函数,使用github.com/go-redis/redis/v8包。

其他

queue.go 使用 chan 实现多协程的队列处理,参考examples/queue_usage中代码。

serial.go 使用 chan 实现线程安全的序列生成器,参考examples/serial_usage中代码。

tstamp.go 实现一个时间戳类型,JSON 序列化为字符串,反序列化为 int64。

utils.go 提供了一系列便利的函数。

Documentation

Index

Constants

View Source
const (
	CodeOK = iota
	CodeErr
)

返回code值

View Source
const (
	// TimeLayout1 2006-01-02 15:04:05
	TimeLayout1 = "2006-01-02 15:04:05"
	// TimeLayout2 2006-01-02
	TimeLayout2 = "2006-01-02"
	// TimeLayout3 15:04:05
	TimeLayout3 = "15:04:05"
	// TimeLayout4 20060102150405
	TimeLayout4 = "20060102150405"
	// TimeLayout5 20060102
	TimeLayout5 = "20060102"
	// TimeLayout6 150405
	TimeLayout6 = "150405"
	// TimeLayout7 2006.01.02
	TimeLayout7 = "2006.01.02"
	// TimeLayout8 2006/01/02
	TimeLayout8 = "2006/01/02"
)

timestamp format layout

Variables

View Source
var (
	RequestCounter   *prometheus.CounterVec
	LatencyHistogram *prometheus.HistogramVec
	DurationsSummary *prometheus.SummaryVec
)

prmethous监控变量

Functions

func BasicAuth

func BasicAuth(username, password string) gin.HandlerFunc

BasicAuth 设置BasicAuth认证

func CORS

func CORS(acceptedOrigin, AcceptedMethods, AcceptedHeaders, MaxAge string) gin.HandlerFunc

CORS 设置跨域

func CreateFolder

func CreateFolder(path string) error

CreateFolder 创建path路径的文件夹

func Errf added in v0.0.3

func Errf(fomart string, v ...interface{})

Errf 固定格式打印错误信息

func GetCaller added in v0.0.3

func GetCaller(d int) (string, int)

GetCaller 获取调用方法名

func GetRealIP

func GetRealIP(req *http.Request) string

GetRealIP 获取真实IP

func GrpcRecovery added in v0.0.7

func GrpcRecovery(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
	handler grpc.UnaryHandler) (resp interface{}, err error)

GrpcRecovery grpc接口panic恢复中间件

func GzipJSON

func GzipJSON(c *gin.Context, data interface{})

GzipJSON gzip压缩发送JSON

func HeadSeparator added in v0.0.3

func HeadSeparator(path string) string

HeadSeparator 确保path以/开头

func InitPrometheus added in v0.0.6

func InitPrometheus(name string)

InitPrometheus 初始化Prometheus

func JSON

func JSON(c *gin.Context, data interface{})

JSON 发送JSON

func JsonErr

func JsonErr(c *gin.Context, err error)

JsonErr 反馈Err

func JsonMsg added in v0.0.3

func JsonMsg(c *gin.Context, msg string)

JsonMsg 反馈发生错误信息

func JsonOK

func JsonOK(c *gin.Context, data interface{})

JsonOK 反馈OK

func LoadJSON

func LoadJSON(name string, data interface{}) error

LoadJSON 解析name.json

func LoadOrSaveJSON added in v0.0.3

func LoadOrSaveJSON(name string, res interface{}, def func() interface{}) (err error)

LoadOrSaveJSON 解析name.json,不存在保存

func LoadOrSaveToml added in v0.0.3

func LoadOrSaveToml(name string, data interface{}, def func() interface{}) (err error)

LoadOrSaveToml 解析name.toml,不存在保存

func LoadToml added in v0.0.3

func LoadToml(name string, data interface{}) error

LoadToml 解析name.toml

func LogControl added in v0.0.3

func LogControl(trace bool, skip []string) gin.HandlerFunc

LogControl 控制gin是否输出log

func LogErr

func LogErr(err error, msg string)

LogErr 固定格式打印error

func Logf added in v0.0.3

func Logf(fomart string, v ...interface{})

Logf 固定格式打印信息

func MD5

func MD5(src string) []byte

MD5 获取字符串的MD5

func NewGrpcConn added in v0.0.3

func NewGrpcConn(addr string) (*grpc.ClientConn, error)

NewGrpcConn 创建grpc.ClientConn,with insecure and block

func NewRedisClient added in v0.0.3

func NewRedisClient(addr, pass string, db int) *redis.Client

NewRedisClient 根据db编号创建redis.Client

func NewRedisClients added in v0.0.3

func NewRedisClients(addr, pass string) (clients map[int]*redis.Client, err error)

NewRedisClients 创建redis.Client map以db编号为key

func NoCache

func NoCache() gin.HandlerFunc

NoCache 设置请求头为无缓存

func PromMetrics added in v0.0.6

func PromMetrics() gin.HandlerFunc

PromMetrics prometheus metrics 中间件

func PrometheusInterceptor added in v0.0.6

func PrometheusInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
	handler grpc.UnaryHandler) (resp interface{}, err error)

PrometheusInterceptor promethous grpc中间件

func PromethousHandler added in v0.0.6

func PromethousHandler() gin.HandlerFunc

PromethousHandler 启动promethous http监听

func RandomString

func RandomString(n int) string

RandomString 生成n长度的字符串

func Run added in v0.0.3

func Run(app AppInterface)

Run 运行服务

func SaveJSON

func SaveJSON(name string, data interface{}) error

SaveJSON 保存到name.json

func SaveToml added in v0.0.3

func SaveToml(name string, data interface{}) error

SaveToml 保存到name.toml

func StrTime

func StrTime(timestamp int64, timeLayout string) string

StrTime 将时间戳转成字符串

func TailSeparator added in v0.0.3

func TailSeparator(path string) string

TailSeparator 确保path以/结尾

func ToJsonStr

func ToJsonStr(data interface{}) string

ToJsonStr 将结构体转成json字符串

func Trace

func Trace(msg string) func()

Trace 耗时检测

func UUID

func UUID() string

UUID 生成没有-的UUID

func UnixTime

func UnixTime(timeStr, layout string) int64

UnixTime 将字符串转成时间戳

Types

type App added in v0.0.3

type App struct {
	Na    string
	Start func() bool
	Stop  func()
	Svrs  []ServerInterface
}

App 内置App

func (*App) Name added in v0.0.3

func (a *App) Name() string

Name 实现 Name() string 接口

func (*App) OnStart added in v0.0.3

func (a *App) OnStart() bool

OnStart 实现 OnStart() bool 接口

func (*App) OnStop added in v0.0.3

func (a *App) OnStop()

OnStop 实现 OnStop() 接口

func (*App) Servers added in v0.0.3

func (a *App) Servers() []ServerInterface

Servers 实现 Servers() []ServerInterface 接口

type AppInterface added in v0.0.3

type AppInterface interface {
	Name() string
	Servers() []ServerInterface
	OnStart() bool
	OnStop()
}

AppInterface 应用实现接口

type DSN added in v0.0.3

type DSN struct {
	Username string
	Password string
	URL      string
	Port     string
	DBName   string
	SkipTran bool
	PreStmt  bool
	LogLevel logger.LogLevel
}

DSN 连接数据库路由参数

func (DSN) MySQL added in v0.0.3

func (d DSN) MySQL() string

MySQL 生成MySQL的dsn

func (DSN) Postgres added in v0.0.3

func (d DSN) Postgres() string

Postgres 生成Postgres的dsn

type GinServer added in v0.0.3

type GinServer struct {
	Name   string
	Server *http.Server
	Engine *gin.Engine
}

GinServer 包含gin的http server

func NewGinServer added in v0.0.3

func NewGinServer(name, addr, mod string) *GinServer

NewGinServer 创建GinServer

func (*GinServer) Group added in v0.0.3

func (s *GinServer) Group(path string, handlers ...gin.HandlerFunc) *gin.RouterGroup

Group 创建gin.RouterGroup

func (*GinServer) Health added in v0.0.3

func (s *GinServer) Health()

Health 健康检查接口,需要的话设置

func (*GinServer) Info added in v0.0.3

func (s *GinServer) Info() string

Info 实现ServerInterface接口

func (*GinServer) OnStart added in v0.0.3

func (s *GinServer) OnStart() bool

OnStart 实现ServerInterface接口

func (*GinServer) OnStop added in v0.0.3

func (s *GinServer) OnStop()

OnStop 实现ServerInterface接口

func (*GinServer) Promethous added in v0.0.6

func (s *GinServer) Promethous(name, pass string)

Promethous 启动Promethous监听

type GormDB added in v0.0.3

type GormDB struct {
	*gorm.DB
}

GormDB 内嵌*gorm.DB,添加封装方法

func MustOpen added in v0.0.3

func MustOpen(dial gorm.Dialector, d DSN) *GormDB

MustOpen 无错的连接数据库并返回*GormDB

func MustOpenMySQL added in v0.0.3

func MustOpenMySQL(d DSN) *GormDB

MustOpenMySQL 无错的连接MySQL返回*gorm.DB

func MustOpenPostgres added in v0.0.3

func MustOpenPostgres(d DSN) *GormDB

MustOpenPostgres 无错的连接Postgres返回*gorm.DB

func (*GormDB) BatchInsert added in v0.0.4

func (db *GormDB) BatchInsert(tb string, value interface{}, batchSize int) error

BatchInsert 批量插入数据

func (*GormDB) CloseDB added in v0.0.3

func (gdb *GormDB) CloseDB()

CloseDB 关闭数据库连接

func (*GormDB) ExecSQL added in v0.0.3

func (db *GormDB) ExecSQL(sql string, values ...interface{}) (int64, error)

ExecSQL 直接执行sql

func (*GormDB) Insert added in v0.0.3

func (db *GormDB) Insert(tb string, value interface{}) error

Insert 插入数据

func (*GormDB) Query added in v0.0.3

func (db *GormDB) Query(dest interface{}, stmt string, values ...interface{}) error

Query 查询数据

func (*GormDB) QueryRow added in v0.0.3

func (db *GormDB) QueryRow(stmt string, values ...interface{}) *sql.Row

QueryRow 获取*sql.Row

func (*GormDB) QueryRows added in v0.0.3

func (db *GormDB) QueryRows(hand func(*sql.Rows) error, sql string, values ...interface{}) (err error)

QueryRows 批量查询使用rows行扫描处理

type GrpcServer added in v0.0.3

type GrpcServer struct {
	Name string
	Addr string
	*grpc.Server
	Register func(*GrpcServer)
}

GrpcServer 封装grpc server

func NewGrpcServer added in v0.0.3

func NewGrpcServer(name, addr string, reg func(*GrpcServer), opt ...grpc.ServerOption) *GrpcServer

NewGrpcServer 创建GrpcServer

func (*GrpcServer) Info added in v0.0.3

func (gs *GrpcServer) Info() string

Info 实现ServerInterface接口

func (*GrpcServer) OnStart added in v0.0.3

func (gs *GrpcServer) OnStart() bool

OnStart 实现ServerInterface接口

func (*GrpcServer) OnStop added in v0.0.3

func (gs *GrpcServer) OnStop()

OnStop 实现ServerInterface接口

type HttpClient added in v0.0.3

type HttpClient struct {
	*http.Client
}

HttpClient 嵌入http.Client,添加一些方法

func NewHttpClient added in v0.0.3

func NewHttpClient() *HttpClient

NewHttpClient 创建HttpClient

func (*HttpClient) GetJSON added in v0.0.3

func (c *HttpClient) GetJSON(url string, data interface{}) (err error)

GetJSON GET请求,解析JSON

func (*HttpClient) GetJSONAuth added in v0.0.3

func (c *HttpClient) GetJSONAuth(url, un, pa string, data interface{}) (err error)

GetJSONAuth GET请求带BasicAuth认证,解析JSON

func (*HttpClient) PostFormJSON added in v0.0.3

func (c *HttpClient) PostFormJSON(url string, vals url.Values, data interface{}) (err error)

PostFormJSON POST请求,参数Form表单,解析JSON

func (*HttpClient) PostFormJSONAuth added in v0.0.3

func (c *HttpClient) PostFormJSONAuth(url, un, pa string, vals url.Values, data interface{}) (err error)

PostFormJSONAuth POST请求带BasicAuth认证,参数Form表单,解析JSON

func (*HttpClient) PostJSON added in v0.0.3

func (c *HttpClient) PostJSON(url string, src, data interface{}) (err error)

PostJSON POST JSON请求,解析JSON

func (*HttpClient) PostJSONAuth added in v0.0.3

func (c *HttpClient) PostJSONAuth(url, un, pa string, src, data interface{}) (err error)

PostJSONAuth POST JSON请求带BasicAuth认证,解析JSON

type Queue

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

Queue 队列

func NewQueue

func NewQueue(size int) *Queue

NewQueue 新建队列

func (*Queue) Start

func (q *Queue) Start(num int, deal func(interface{}))

Start 启动队列

func (*Queue) Stop

func (q *Queue) Stop()

Stop 停止队列

func (*Queue) Submit

func (q *Queue) Submit(item interface{})

Submit 非阻塞提交队列

func (*Queue) Submit2

func (q *Queue) Submit2(item interface{})

Submit2 阻塞提交队列

type Resp

type Resp struct {
	Code int         `json:"code"`
	Data interface{} `json:"data,omitempty"`
}

Resp http统一返回结构

func NewResp

func NewResp(code int, data interface{}) *Resp

NewResp 创建一个返回结构

func RespErr

func RespErr(err error) *Resp

RespErr 创建一个返回error的结构

func RespMsg

func RespMsg(code int, msg string) *Resp

RespMsg 创建一个返回字符串信息的结构

func RespOK

func RespOK(data interface{}) *Resp

RespOK 创建一个返回OK的结构

type Serial

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

Serial 序列生成器

func NewSerial

func NewSerial(reset int) *Serial

NewSerial 创建Serial

func (*Serial) Get

func (s *Serial) Get() int

Get 获取序列值

func (*Serial) Reset

func (s *Serial) Reset(c int)

Reset 重置计数

func (*Serial) Start

func (s *Serial) Start()

Start 开始序列生成器

type ServerInterface added in v0.0.3

type ServerInterface interface {
	OnStart() bool
	OnStop()
	Info() string
}

ServerInterface 服务实现接口

type StmtDB

type StmtDB struct {
	*sqlx.DB
	// contains filtered or unexported fields
}

StmtDB 嵌入sqlx.DB,加了statement缓存

func NewStmtDB

func NewStmtDB(db *sqlx.DB) *StmtDB

NewStmtDB 创建StmtDB

func (*StmtDB) CloseDB

func (s *StmtDB) CloseDB()

CloseDB 关闭StmtDB

func (*StmtDB) DeferLock

func (s *StmtDB) DeferLock() func()

DeferLock 合并锁的使用 example: defer s.DeferLock()()

func (*StmtDB) Lock

func (s *StmtDB) Lock()

Lock 使用锁

func (*StmtDB) NStmt

func (s *StmtDB) NStmt(sqlStr string) (stmt *sqlx.NamedStmt, err error)

NStmt g懒加载的方式缓存sqlx.NamedStmt

func (*StmtDB) Stmt

func (s *StmtDB) Stmt(sqlStr string) (stmt *sqlx.Stmt, err error)

Stmt 懒加载的方式缓存sqlx.Stmt

func (*StmtDB) Unlock

func (s *StmtDB) Unlock()

Unlock 释放锁

type TStamp

type TStamp int64

TStamp custom type for int64

func NewStampTime

func NewStampTime(te time.Time) TStamp

NewStampTime new TStamp by time.Time

func NewStrStamp

func NewStrStamp(ts string) TStamp

NewStrStamp new TStamp by time string

func NewTimeStamp

func NewTimeStamp(ts int64) TStamp

NewTimeStamp new TStamp

func (TStamp) Format

func (t TStamp) Format(layout string) string

Format get format time

func (TStamp) GoString

func (t TStamp) GoString() string

GoString implement GoStringer

func (TStamp) Int64

func (t TStamp) Int64() int64

Int64 get int64 value

func (TStamp) MarshalJSON

func (t TStamp) MarshalJSON() (buf []byte, err error)

MarshalJSON implement Marshaler

func (TStamp) String

func (t TStamp) String() string

String implement Stringer

func (TStamp) Time

func (t TStamp) Time() time.Time

Time get time.Time

func (*TStamp) UnmarshalJSON

func (t *TStamp) UnmarshalJSON(b []byte) error

UnmarshalJSON implement Unmarshaler

type XmlMap

type XmlMap map[string]string

XmlMap xml转换map

func (XmlMap) MarshalXML

func (m XmlMap) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML marshals the map to XML

func (*XmlMap) UnmarshalXML

func (m *XmlMap) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML unmarshals the XML into a map of string to strings

Jump to

Keyboard shortcuts

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