Commit fca2083c by feidy

init

parents
package utils
import (
c "github.com/robfig/cron/v3"
)
type CronFunc func()
func NewCron(spec string,fun CronFunc)(cron *c.Cron){
cron = c.New(c.WithSeconds())
cron.AddFunc(spec,fun)
cron.Start()
return cron
}
module github.com/go/utils
go 1.17
require (
github.com/go-playground/assert/v2 v2.0.1
github.com/natefinch/lumberjack v2.0.0+incompatible
github.com/qiniu/qmgo v1.0.6
github.com/robfig/cron/v3 v3.0.1
go.mongodb.org/mongo-driver v1.8.2
go.uber.org/zap v1.21.0
)
require (
github.com/BurntSushi/toml v1.0.0 // indirect
github.com/go-playground/locales v0.13.0 // indirect
github.com/go-playground/universal-translator v0.17.0 // indirect
github.com/go-playground/validator/v10 v10.4.1 // indirect
github.com/go-stack/stack v1.8.0 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/leodido/go-urn v1.2.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.0.2 // indirect
github.com/xdg-go/stringprep v1.0.2 // indirect
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.0.0-20210510120138-977fb7262007 // indirect
golang.org/x/text v0.3.5 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
)
package utils
import "time"
// Location wraps time.Location.
type Location time.Location
// ToLocation *time.Location to *Location
func ToLocation(location *time.Location) *Location {
return (*Location)(location)
}
// TimeLocation time.Location
func (l *Location) TimeLocation() *time.Location {
return (*time.Location)(l)
}
// Set implements pflag/flag.Value
func (l *Location) Set(s string) error {
location, err := ParseLocation(s)
if err != nil {
return err
}
*l = *location
return nil
}
// Type implements pflag.Value
func (l *Location) Type() string {
return "location"
}
// String string
func (l Location) String() string {
location := (time.Location)(l)
return location.String()
}
// MarshalYAML implements the yaml.Marshaler interface.
func (l Location) MarshalYAML() (interface{}, error) {
return l.String(), nil
}
// UnmarshalYAML implements the yaml.Unmarshaler interface.
func (l *Location) UnmarshalYAML(unmarshal func(interface{}) error) error {
var s string
if err := unmarshal(&s); err != nil {
return err
}
location, err := ParseLocation(s)
if err != nil {
return err
}
*l = *location
return nil
}
// ParseLocation parses a string into a time.Location
func ParseLocation(locationStr string) (*Location, error) {
location, err := time.LoadLocation(locationStr)
if err != nil {
return nil, err
}
return (*Location)(location), nil
}
package utils
import (
"github.com/natefinch/lumberjack"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"os"
)
const (
// DebugLevel logs are typically voluminous, and are usually disabled in
// production.
Debug int8 = iota - 1
// InfoLevel is the default logging priority.
Info
// WarnLevel logs are more important than Info, but don't need individual
// human review.
Warn
// ErrorLevel logs are high-priority. If an application is running smoothly,
// it shouldn't generate any error-level logs.
Error
// DPanicLevel logs are particularly important errors. In development the
// logger panics after writing the message.
DPanic
// PanicLevel logs a message, then panics.
Panic
// FatalLevel logs a message, then calls os.Exit(1).
Fatal
)
type loggerConfig struct {
Level int8
FilePath string
MaxSize int
MaxBackups int
MaxAge int
Compress bool
}
type loggerOption func(m *loggerConfig)
func WithLevel(level int8) loggerOption {
return func(m *loggerConfig){
m.Level = level
}
}
func WithLogFilePath(filePath string) loggerOption {
return func(m *loggerConfig) {
m.FilePath = filePath
}
}
func WithMaxSize(maxSize int)loggerOption {
return func(m *loggerConfig) {
m.MaxSize = maxSize
}
}
func WithMaxBackups(maxBack int)loggerOption {
return func(m *loggerConfig) {
m.MaxBackups = maxBack
}
}
func WithMaxAge(maxAge int)loggerOption {
return func(m *loggerConfig) {
m.MaxAge = maxAge
}
}
func WithCompress(compress bool) loggerOption {
return func(m *loggerConfig){
m.Compress = compress
}
}
var lf = loggerConfig{
Level: 1,
FilePath: "log/log.log",
MaxSize: 100,
MaxAge: 7,
MaxBackups: 7,
Compress: true,
}
var L *zap.SugaredLogger
func InitLogger(opt ...loggerOption) {
for _, config := range opt {
config(&lf)
}
writeSync := getLogWriter()
encoder := getEncoder()
consoleDebugging := zapcore.Lock(os.Stdout)
core := zapcore.NewTee(
zapcore.NewCore(encoder, writeSync, zapcore.Level(lf.Level)),
zapcore.NewCore(zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig()), consoleDebugging, zapcore.Level(lf.Level)),
)
logger := zap.New(core, zap.AddCaller())
L = logger.Sugar()
}
func getEncoder() zapcore.Encoder {
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
return zapcore.NewConsoleEncoder(encoderConfig)
}
func getLogWriter() zapcore.WriteSyncer {
lumberJackLogger := &lumberjack.Logger{
Filename: lf.FilePath, // 日志文件路径
MaxSize: lf.MaxSize, // 每个日志文件保存的最大尺寸 单位:M
MaxBackups: lf.MaxBackups, // 日志文件最多保存多少个备份
MaxAge: lf.MaxAge, // 文件最多保存多少天
Compress: lf.Compress, // 是否压缩
}
return zapcore.AddSync(lumberJackLogger)
}
package utils
import (
"context"
"fmt"
"github.com/qiniu/qmgo"
"net/url"
)
type MongoConfig struct {
Username string
Password string
Host string
DB string
Collection string
MaxPoolSize uint64
MinPoolSize uint64
}
type Mongo struct{
Cli *qmgo.QmgoClient //必须初始化DB和Collection
Client *qmgo.Client // 不用初始化DB和Collection
}
type Option func(m *MongoConfig)
func WithDB(db string)Option{
return func(m *MongoConfig) {
m.DB = db
}
}
func WithCollection(collection string)Option{
return func(m *MongoConfig) {
m.Collection = collection
}
}
func WithMaxPoolSize(poolSize uint64)Option{
return func(m *MongoConfig){
m.MaxPoolSize = poolSize
}
}
func WithMinPoolSize(poolSize uint64)Option{
return func(m *MongoConfig){
m.MinPoolSize = poolSize
}
}
func NewMongo(host string,username string,password string,options ...Option) (m *Mongo, err error) {
mfg := MongoConfig{
Username:url.QueryEscape(username),
Password:url.QueryEscape(password),
Host:host,
}
for _, option := range options {
option(&mfg)
}
cfg := qmgo.Config{
Uri:fmt.Sprintf("mongodb://%s:%s@%s", mfg.Username, mfg.Password, mfg.Host),
}
var maxPoolSize uint64 = 100
var minPoolSize uint64 = 0
if mfg.MinPoolSize != 0 {
cfg.MaxPoolSize = &mfg.MaxPoolSize
}else{
cfg.MaxPoolSize = &maxPoolSize
}
if mfg.MinPoolSize != 0{
cfg.MinPoolSize = &mfg.MinPoolSize
}else{
cfg.MinPoolSize = &minPoolSize
}
var isCollection bool
if mfg.DB != ""{
cfg.Database = mfg.DB
}
if mfg.Collection != ""{
cfg.Coll = mfg.Collection
isCollection = true
}
ctx := context.Background()
m = &Mongo{}
if isCollection{
m.Cli,err = qmgo.Open(ctx, &cfg)
}else{
m.Client,err = qmgo.NewClient(ctx,&cfg)
}
return
}
func (m *Mongo)Close() {
if m.Client != nil {
m.Client.Close(context.Background())
}
if m.Cli != nil {
m.Cli.Close(context.Background())
}
}
package utils
import (
"context"
"github.com/go-playground/assert/v2"
"go.mongodb.org/mongo-driver/bson"
"testing"
)
func TestMongo_InitCli(t *testing.T) {
m,err := NewMongo("192.168.31.129:27017/snc","snc","shuoren@2019snc",
WithDB("snc"),WithCollection("alarm"))
defer m.Close()
if err != nil{
t.Fatal(err)
}
c,err := m.Cli.Find(context.Background(),bson.M{}).Count()
if err != nil{
t.Fatal(err)
}
count := int64(37415)
assert.Equal(t,c,count)
}
func TestMongo_InitClient(t *testing.T){
m,err := NewMongo("192.168.31.129:27017/snc","snc","shuoren@2019snc")
defer m.Close()
if err != nil{
t.Fatal(err)
}
c,err := m.Client.Database("snc").Collection("alarm").Find(context.Background(),bson.M{}).Count()
if err != nil{
t.Fatal(err)
}
count := int64(37415)
assert.Equal(t,c,count)
}
\ No newline at end of file
package utils
import (
"log"
"net/http"
"net/http/pprof"
)
// init disables default handlers registered by importing net/http/pprof.
func Init() {
http.DefaultServeMux = http.NewServeMux()
}
// Handle adds standard pprof handlers to mux.
func Handle(mux *http.ServeMux) {
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
}
// NewServeMux builds a ServeMux and populates it with standard pprof handlers.
func NewServeMux() *http.ServeMux {
mux := http.NewServeMux()
Handle(mux)
return mux
}
// NewServer constructs a server at addr with the standard pprof handlers.
func NewServer(addr string) *http.Server {
return &http.Server{
Addr: addr,
Handler: NewServeMux(),
}
}
// ListenAndServe starts a server at addr with standard pprof handlers.
func ListenAndServe(addr string) error {
return NewServer(addr).ListenAndServe()
}
// Launch a standard pprof server at addr.
func Launch(addr string) {
go func() {
log.Fatal(ListenAndServe(addr))
}()
}
package utils
import "strconv"
func IntToString(a int)string{
return strconv.Itoa(a)
}
package utils
import (
"time"
)
// Date Format
const (
YmdHms = "2006-01-02 15:04:05"
YmdHm = "2006-01-02 15:04"
YmdH = "2006-01-02 15"
Ymd = "2006-01-02"
Ym = "2006-01"
RFC3339 = time.RFC3339
)
// now time.Now()
func now() time.Time {
return time.Now()
}
// Today today
func Today() time.Time {
t := time.Now()
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}
func Yesterday() time.Time{
t := time.Now()
return time.Date(t.Year(), t.Month(),t.Day()-1, 0, 0, 0, 0, t.Location())
}
// ToDay 2019-08-21 22:07:07 -> 2019-08-21 00:00:00
func ToDay(t time.Time) time.Time {
y, m, d := t.Date()
return time.Date(y, m, d, 0, 0, 0, 0, t.Location())
}
// ToHour 2019-08-21 22:07:07 -> 2019-08-21 22:00:00
func ToHour(t time.Time) time.Time {
y, m, d := t.Date()
return time.Date(y, m, d, t.Hour(), 0, 0, 0, t.Location())
}
// ToMinute 2019-08-21 22:07:07 -> 2019-08-21 22:07:00
func ToMinute(t time.Time) time.Time {
y, m, d := t.Date()
return time.Date(y, m, d, t.Hour(), t.Minute(), 0, 0, t.Location())
}
// ThisMonth 2019-08-21 22:07:07 -> 2019-08-01 00:00:00
func ThisMonth(t time.Time) time.Time {
y, m, _ := t.Date()
return time.Date(y, m, 1, 0, 0, 0, 0, t.Location())
}
// ThisYear 2019-08-21 22:07:07 -> 2019-01-01 00:00:00
func ThisYear(t time.Time) time.Time {
return time.Date(t.Year(), 1, 1, 0, 0, 0, 0, t.Location())
}
// TimestampToTime second timestamp to Time
func TimestampToTime(u int64) time.Time {
return time.Unix(u, 0)
}
// TimeToTimestamp Time to millisecond
func TimeToTimestamp(t time.Time) int64 {
return t.UnixNano() / 1e6
}
// TimestampToDate second timestamp to date
func TimestampToDate(u int64, format string) string {
return time.Unix(u, 0).Format(format)
}
// MillisecondToTime millisecond timestamp to Time
func MillisecondToTime(u int64) time.Time {
return time.Unix(u/1e3, 0)
}
// MillisecondToTime millisecond timestamp to date
func MillisecondToDate(u int64, format string) string {
return time.Unix(u/1e3, 0).Format(format)
}
//millisecond timestamp now
func MillisecondNow() int64 {
return time.Now().UnixNano() / 1e6
}
//second timestamp now
func SecondNow() int64 {
return MillisecondNow() / 1e3
}
// DateToTime date to time
func DateToTime(format, date string) (time.Time, error) {
return time.ParseInLocation(format, date, time.Local)
}
// FormatRFC3339 to RFC3339
func FormatRFC3339(t time.Time) string {
return t.Format(RFC3339)
}
func YesterdayStart()int64{
return TimeToTimestamp(Yesterday())
}
func YesterdayEnd()int64{
return TimeToTimestamp(Today()) - 1000
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment