diff --git a/db/db.go b/db/db.go index 4f4feb5..3765edb 100644 --- a/db/db.go +++ b/db/db.go @@ -1,11 +1,11 @@ package db import ( + "errors" "fmt" "strings" - "time" - "github.com/gxxgle/go-utils/env" + "github.com/gxxgle/go-utils/time" "github.com/doug-martin/goqu/v9" _ "github.com/doug-martin/goqu/v9/dialect/mysql" @@ -18,6 +18,10 @@ const ( MySQL = "mysql" ) +var ( + ErrNotFound = errors.New("record not found") +) + // default config var ( DefaultRetries = 5 @@ -54,7 +58,7 @@ func OpenDB(cfg *Config) (*xorm.Engine, error) { return nil, err } - db.DatabaseTZ = env.Local + db.DatabaseTZ = time.Local db.ShowSQL(cfg.Debug) db.SetConnMaxLifetime(time.Minute * 30) diff --git a/env/env.go b/env/env.go deleted file mode 100644 index a881e6b..0000000 --- a/env/env.go +++ /dev/null @@ -1,17 +0,0 @@ -package env - -import ( - "time" - - "github.com/imroc/req" -) - -var ( - Local *time.Location -) - -func init() { - Local, _ = time.LoadLocation("Asia/Chongqing") - time.Local = Local - req.EnableInsecureTLS(true) -} diff --git a/example/main.go b/example/main.go index bfe121a..9a9d707 100644 --- a/example/main.go +++ b/example/main.go @@ -5,8 +5,7 @@ import ( _ "github.com/gxxgle/go-utils/config" _ "github.com/gxxgle/go-utils/conver" _ "github.com/gxxgle/go-utils/db" - _ "github.com/gxxgle/go-utils/env" - _ "github.com/gxxgle/go-utils/ip" + _ "github.com/gxxgle/go-utils/http" _ "github.com/gxxgle/go-utils/json" _ "github.com/gxxgle/go-utils/log" _ "github.com/gxxgle/go-utils/math" @@ -15,6 +14,7 @@ import ( _ "github.com/gxxgle/go-utils/proxy" _ "github.com/gxxgle/go-utils/schedule" _ "github.com/gxxgle/go-utils/sync" + _ "github.com/gxxgle/go-utils/time" _ "github.com/gxxgle/go-utils/validate" ) diff --git a/go.mod b/go.mod index 2864fbe..29be49c 100644 --- a/go.mod +++ b/go.mod @@ -7,8 +7,8 @@ require ( github.com/doug-martin/goqu/v9 v9.9.0 github.com/go-playground/validator/v10 v10.3.0 github.com/go-redis/redis/v7 v7.4.0 + github.com/go-resty/resty/v2 v2.3.0 github.com/go-sql-driver/mysql v1.5.0 - github.com/imroc/req v0.3.0 github.com/json-iterator/go v1.1.10 github.com/patrickmn/go-cache v0.0.0-20191004192108-46f407853014 github.com/phuslu/log v1.0.40 diff --git a/go.sum b/go.sum index f5611a1..8ae4f6c 100644 --- a/go.sum +++ b/go.sum @@ -26,6 +26,8 @@ github.com/go-playground/validator/v10 v10.3.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GO github.com/go-redis/redis/v7 v7.2.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= github.com/go-redis/redis/v7 v7.4.0 h1:7obg6wUoj05T0EpY0o8B59S9w5yeMWql7sw2kwNW1x4= github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg= +github.com/go-resty/resty/v2 v2.3.0 h1:JOOeAvjSlapTT92p8xiS19Zxev1neGikoHsXJeOq8So= +github.com/go-resty/resty/v2 v2.3.0/go.mod h1:UpN9CgLZNsv4e9XG50UU8xdI0F43UQ4HmxLBDwaroHU= github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= @@ -39,8 +41,6 @@ github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8l github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/imroc/req v0.3.0 h1:3EioagmlSG+z+KySToa+Ylo3pTFZs+jh3Brl7ngU12U= -github.com/imroc/req v0.3.0/go.mod h1:F+NZ+2EFSo6EFXdeIbpfE9hcC233id70kf0byW97Caw= github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr68= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= @@ -103,6 +103,7 @@ golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200904194848-62affa334b73 h1:MXfv8rhZWmFeqX3GNZRsd6vOLoaCHjYEX3qkRo3YBUA= golang.org/x/net v0.0.0-20200904194848-62affa334b73/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= diff --git a/http/http.go b/http/http.go new file mode 100644 index 0000000..03c15e6 --- /dev/null +++ b/http/http.go @@ -0,0 +1,18 @@ +package http + +import ( + "crypto/tls" + + "github.com/gxxgle/go-utils/time" + + "github.com/go-resty/resty/v2" +) + +var ( + C = resty.New() +) + +func init() { + C.SetTimeout(time.Second * 30) + C.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}) +} diff --git a/http/http_test.go b/http/http_test.go new file mode 100644 index 0000000..2a087c3 --- /dev/null +++ b/http/http_test.go @@ -0,0 +1,14 @@ +package http + +import ( + "testing" +) + +func TestGet(t *testing.T) { + resp, err := C.R().Get("http://pv.sohu.com/cityjson?ie=utf-8") + if err != nil { + t.Fatal("http get failed, err:", err) + } + + t.Log("http response:", resp.String()) +} diff --git a/ip/example/main.go b/ip/example/main.go deleted file mode 100644 index 510b88e..0000000 --- a/ip/example/main.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -import ( - "log" - - "github.com/gxxgle/go-utils/ip" -) - -func main() { - log.Println(ip.ExtranetIP()) - log.Println(ip.IntranetIPs()) -} diff --git a/ip/ip.go b/ip/ip.go deleted file mode 100644 index e5f0358..0000000 --- a/ip/ip.go +++ /dev/null @@ -1,73 +0,0 @@ -package ip - -import ( - "bytes" - "net" - - "github.com/imroc/req" -) - -// ExtranetIP return external IP address. -func ExtranetIP() (string, error) { - resp, err := req.Get("http://pv.sohu.com/cityjson?ie=utf-8") - if err != nil { - return "", err - } - - bs := resp.Bytes() - idx := bytes.Index(bs, []byte(`"cip": "`)) - bs = bs[idx+len(`"cip": "`):] - idx = bytes.Index(bs, []byte(`"`)) - bs = bs[:idx] - return string(bs), nil -} - -// IntranetIPs return internal IP address. -func IntranetIPs() ([]string, error) { - out := make([]string, 0) - is, err := net.Interfaces() - if err != nil { - return nil, err - } - - for _, i := range is { - // interface down - if i.Flags&net.FlagUp == 0 { - continue - } - - // loopback interface - if i.Flags&net.FlagLoopback != 0 { - continue - } - - addrs, err := i.Addrs() - if err != nil { - return nil, err - } - - for _, addr := range addrs { - var ip net.IP - - switch v := addr.(type) { - case *net.IPNet: - ip = v.IP - case *net.IPAddr: - ip = v.IP - } - - if ip == nil || ip.IsLoopback() { - continue - } - - ip = ip.To4() - if ip == nil { - continue - } - - out = append(out, ip.String()) - } - } - - return out, nil -} diff --git a/log/log.go b/log/log.go index c7c841e..3fe5b77 100644 --- a/log/log.go +++ b/log/log.go @@ -15,7 +15,7 @@ var ( ) func init() { - log.DefaultLogger.Level = log.InfoLevel + log.DefaultLogger.SetLevel(log.InfoLevel) log.DefaultLogger.Caller = 1 } @@ -53,8 +53,12 @@ func File(logpaths ...string) { log.DefaultLogger.Writer = fileWriter } +func SetLevel(lvl log.Level) { + log.DefaultLogger.SetLevel(lvl) +} + func SetDebug() { - log.DefaultLogger.Level = log.DebugLevel + SetLevel(log.DebugLevel) } func LogIfError(err error, msgs ...string) { @@ -70,6 +74,10 @@ func LogIfError(err error, msgs ...string) { log.Error().Caller(log.DefaultLogger.Caller + 1).Err(err).Msg(msg) } +func LogIfFuncError(fn func() error, msgs ...string) { + LogIfError(fn(), msgs...) +} + func FatalIfError(err error, msgs ...string) { if err == nil { return diff --git a/schedule/schedule.go b/schedule/schedule.go index a73d616..508e380 100644 --- a/schedule/schedule.go +++ b/schedule/schedule.go @@ -3,9 +3,8 @@ package schedule import ( "log" "sync" - "time" - "github.com/gxxgle/go-utils/env" + "github.com/gxxgle/go-utils/time" "github.com/robfig/cron/v3" ) @@ -30,7 +29,7 @@ func init() { // New new cron func New() (*Schedule, error) { - c := cron.New(cron.WithLocation(env.Local)) + c := cron.New(cron.WithLocation(time.Local)) s := &Schedule{ Cron: c, Stopped: false, diff --git a/time/time.go b/time/time.go new file mode 100644 index 0000000..c369d48 --- /dev/null +++ b/time/time.go @@ -0,0 +1,115 @@ +package time + +import ( + "time" +) + +const ( + ISO8601 = "2006-01-02T15:04:05-0700" + ISO8601Milli = "2006-01-02T15:04:05.999-0700" +) + +// time.Month +const ( + M1 = time.January + M2 = time.February + M3 = time.March + M4 = time.April + M5 = time.May + M6 = time.June + M7 = time.July + M8 = time.August + M9 = time.September + M10 = time.October + M11 = time.November + M12 = time.December +) + +type Duration = time.Duration + +// time.Duration +const ( + Millisecond = time.Millisecond + Second = time.Second + Minute = time.Minute + Hour = time.Hour + Day = time.Hour * 24 +) + +var ( + Sleep = time.Sleep + Local = time.Local +) + +type Time time.Time + +func New(t time.Time) Time { + return Time(t) +} + +func Now() Time { + return New(time.Now()) +} + +func Date(year int, month time.Month, day int, hour int, min int, sec int, nsec int) Time { + return New(time.Date(year, month, day, hour, min, sec, nsec, time.Local)) +} + +func (t Time) Time() time.Time { + return time.Time(t) +} + +func (t Time) Unix() int64 { + return t.Time().Unix() +} + +func (t Time) UnixMilli() int64 { + return t.Time().UnixNano() / int64(Millisecond) +} + +func (t Time) String() string { + return t.Time().Format(ISO8601Milli) +} + +func (t Time) MarshalJSON() ([]byte, error) { + b := make([]byte, 0, len(ISO8601Milli)+2) + b = append(b, '"') + b = t.Time().AppendFormat(b, ISO8601Milli) + b = append(b, '"') + return b, nil +} + +func (t *Time) UnmarshalJSON(data []byte) error { + if string(data) == "null" { + return nil + } + + tm, err := time.Parse(`"`+ISO8601Milli+`"`, string(data)) + if err != nil { + return err + } + + *t = New(tm) + return nil +} + +func SetUTC() error { + Local = time.UTC + time.Local = time.UTC + return nil +} + +func SetChinaLocal() error { + local, err := time.LoadLocation("Asia/Chongqing") + if err != nil { + return err + } + + Local = local + time.Local = local + return nil +} + +func Since(t Time) Duration { + return time.Since(t.Time()) +} diff --git a/time/time_test.go b/time/time_test.go new file mode 100644 index 0000000..e98eac6 --- /dev/null +++ b/time/time_test.go @@ -0,0 +1,26 @@ +package time + +import ( + "strings" + "testing" + + "github.com/gxxgle/go-utils/json" +) + +func TestJSON(t *testing.T) { + before := New(2008, M8, 8, 20, 8, 8, 8*1000*1000) + str := json.MustMarshalToString(before) + after := Time{} + + if err := json.UnmarshalFromString(str, &after); err != nil { + t.Fatal("time.Time UnmarshalJSON failed, err:", err) + } + + if !strings.HasPrefix(str, "\"2008-08-08T20:08:08") { + t.Fatal("time.Time MarshalJSON not match, str:", str) + } + + if before != after { + t.Fatal("time.Time UnmarshalJSON not match") + } +}