Skip to content

Commit

Permalink
add util && examples
Browse files Browse the repository at this point in the history
  • Loading branch information
wangyongtao committed Apr 3, 2022
1 parent 7a7a2a5 commit a39f3de
Show file tree
Hide file tree
Showing 7 changed files with 409 additions and 0 deletions.
96 changes: 96 additions & 0 deletions doc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Docs



## 环境 environment

```sh
$ go version
go version go1.18 darwin/amd64
```

## 如何创建一个新项目 create a new project


(1) 新建目录 Create a directory for Go module source code

```
$ mkdir gotools
$ cd gotools
```

(2) 初始化 Start module using the go mod init command

```
$ go mod init github.com/wangyongtao/gotools
```

(3) 写一些代码 write some code :

```
$ vi main.go
```

main.go:

```go
package main

import (
"log"
)

func main() {
log.Println("hello, my go tools")
}
```

(4) 编译并执行代码 compile and run:

```
$ go run main.go
```

test:

$ go test -v util/password_test.go util/password.go


(5) Create a new repository in github.com

(6) Git初始化 git init && git remote add:

```sh
$ cd gotools
$ git init
$ git remote add origin git@github.com:wangyongtao/gotools.git
```

(7) 代码推送 git push:

```sh
$ git status
$ git add .
$ git commit -m "init"
$ git push --set-upstream origin master
```

(8) 发一个版本 Draft a new release in github.com


(9) 在其他项目中调用本库 Call your code from another module

```sh
$ mkdir hello
$ cd hello
$ go mod init example.com/hello
$ go get -u github.com/wangyongtao/gotools
```

## 参考 Reference

https://go.dev/doc
https://go.dev/doc/tutorial/create-module


·END·
31 changes: 31 additions & 0 deletions examples/helloworld/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package main

import (
"fmt"

// 引入工具库
"github.com/wangyongtao/gotools/util"
)

// 演示加密字符串、校验加密结果

func main() {
fmt.Println("hello, world!")

// 加密:encrypt
// 用户密码,需要加密存储
pwd := "admin"
hash, _ := util.PasswordHash(pwd)

fmt.Println("==> 密码加密:")
fmt.Println("--> 输入的密码:", pwd)
fmt.Println("--> 生成的hash:", hash)
// hash: $2a$10$tL00vjlVzidXygcmmW7naObKkI2CgoH9lcaT/DYAFWVAbVO/PVMiu

// 校验 verify
// 登录账户时,将用户输入的密码加密后,与数据中查询的加密密码对比,校验通过则说明用户密码输入正确
fmt.Println("==> 对比加密结果:")
match := util.PasswordVerify(pwd, hash)

fmt.Println("--> 验证结果:", match)
}
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29 h1:tkVvjkPTB7pnW3jnid7kNyAMPVWllTNOf/qKDze4p9o=
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
122 changes: 122 additions & 0 deletions util/datetime.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package util

import (
"fmt"
"strings"
"time"
)

// UnixTime time()
func UnixTime() int64 {
return time.Now().Unix()
}

// 时间戳转成 datetime 字符串 YY-mm-dd
func UnixTime2Date(timestamp int64) string {
return time.Unix(timestamp, 0).Format("2006-01-02")
}

// 时间戳转成 datetime 字符串 YY-mm-dd HH:ii:ss
func UnixTime2DateTime(timestamp int64) string {
return time.Unix(timestamp, 0).Format("2006-01-02 15:04:05")
}

// 将时间字符串转成可读性友好的时间字符串
func Str2HumanTime(datetime string) string {

layout := "2006-01-02 15:04:05"
index := strings.Index(datetime, "T")
if index == 10 {
layout = "2006-01-02T15:04:05Z"
}
localTime, _ := time.ParseInLocation(layout, datetime, time.Local)
res := localTime.Unix()
fmt.Println(" datetime ", datetime)
fmt.Println(" localTime ", localTime)
fmt.Println(" index ", index)

return HumanTime(res)
}

// UTC时间字符串转成时间戳
func Str2UnixTime(datetime string) int64 {
layout := "2006-01-02 15:04:05"
index := strings.Index(datetime, "T")
if index == 10 {
layout = "2006-01-02T15:04:05Z"
}
localTime, _ := time.ParseInLocation(layout, datetime, time.Local)

return localTime.Unix()
}

// UTC时间字符串转成时间
func Str2Datetime(datetime string) string {
layout := "2006-01-02 15:04:05"
index := strings.Index(datetime, "T")
if index == 10 {
layout = "2006-01-02T15:04:05Z"
}
localTime, _ := time.ParseInLocation(layout, datetime, time.Local)

return localTime.Format("2006-01-02 15:04:05")
}

// 获取可读性友好的时间字符串
func HumanTime(timestamp int64) string {
const minute = 60 // 60 秒
const hour = 3600 // 3600 秒
const day = hour * 24
const week = day * 7
const month = day * 30
const year = month * 12
var now = time.Now().Unix() // 获取当前时间戳
var diff = now - timestamp // 给的日期与当前时间戳的差值
// startTime := time.Now()
// durations := time.Since(startTime)
// time.Sleep(time.Second * 2)
// fmt.Println("离现在过去了:", durations.Seconds())

var s string
if diff > year {
s = fmt.Sprintf("%.0f 年前", float64(diff/year))
} else if diff > month {
s = fmt.Sprintf("%.0f 月前", float64(diff/month))
} else if diff > week {
s = fmt.Sprintf("%.0f 周前", float64(diff/week))
} else if diff > day {
s = fmt.Sprintf("%.0f 天前", float64(diff/day))
} else if diff > hour {
s = fmt.Sprintf("%.0f 小时前", float64(diff/hour))
} else if diff > minute {
s = fmt.Sprintf("%.0f 分钟前", float64(diff/minute))
} else if diff > 1000 {
s = fmt.Sprintf("%.0f 秒前", float64(diff/1000))
} else {
s = "刚刚"
}

return s
}

// TimeAgo
func TimeAgo(t time.Time) string {
now := time.Now()
diff := now.Sub(t)
hours := diff.Hours()
if hours < 1.0 {
return fmt.Sprintf("约 %.0f 分钟前", diff.Minutes())
}
if hours < 24.0 {
return fmt.Sprintf("约 %.0f 小时前", hours)
}
if hours < 72.0 {
return fmt.Sprintf("约 %.0f 天前", hours/24.0)
}
// 同一年的显示月份
if now.Year() == t.Year() {
return t.Format("01-02 15:04")
}

return t.Format("2006-01-02")
}
98 changes: 98 additions & 0 deletions util/datetime_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package util

import (
"testing"
"time"
)

// cd gotools
// go test -v util/datetime_test.go util/datetime.go

func Test_HumanTime(t *testing.T) {
t.Log("---> Test_HumanTime")
// var timestamp int64 = 1625882650
timestamp := time.Now().Unix() - 3600*24*66
str := HumanTime(timestamp)
t.Log("---> Test_HumanTime", str)
}

func Test_Str2HumanTime(t *testing.T) {
t.Log("---> Test_Str2HumanTime")

// data := "2021-02-06 06:25:56"
data := "2021-08-06T06:25:42Z"

str := Str2HumanTime(data)

t.Log("---> Test_Str2HumanTime", str)
}

func Test_UnixTime2DateTime(t *testing.T) {
t.Log("---> Test_UnixTime2DateTime")

data := 1612563956

result := UnixTime2DateTime(int64(data))
t.Log("---> UnixTime2DateTime unixtime", data)
t.Log("---> UnixTime2DateTime datetime", result)
}

func Test_Str2UnixTime(t *testing.T) {
t.Log("---> Str2UnixTime")

data := "2021-02-06 06:25:56"

result := Str2UnixTime(data)

t.Log("---> Str2UnixTime datetime", data)
t.Log("---> Str2UnixTime unixtime", result)
}

func Test_TimeAgo(t *testing.T) {
type args struct {
t time.Time
}

myTime := time.Now().Add(-72 * time.Hour)

tests := []struct {
name string
args args
want string
}{
{
"小于1分钟",
args{time.Now().Add(-30 * time.Second)},
"约 1 分钟前",
},
{
"约2小时前",
args{time.Now().Add(-100 * time.Minute)},
"约 2 小时前",
},
{
"约1天前",
args{time.Now().Add(-25 * time.Hour)},
"约 1 天前",
},
{
"同年的从月份开始",
args{myTime},
myTime.Format("01-02 15:04"),
},
{
"2016-02-02",
args{time.Date(2016, 2, 2, 0, 0, 0, 0, time.Local)},
"2016-02-02",
},
}
for _, info := range tests {
t.Run(info.name, func(t *testing.T) {
got := TimeAgo(info.args.t)

if got != info.want {
t.Errorf("Test_TimeAgo failed: got %v, want %v", got, info.want)
}
})
}
}
29 changes: 29 additions & 0 deletions util/validate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package util

import (
"errors"
"net/url"
"strings"
)

// 验证跳转域名的合法性:即跳转链接的域名 应该包含 baseURI 的域名
// ValidateBaseURI validates that redirectURI is contained in baseURI
func ValidateBaseURI(baseURI string, redirectURI string) error {
base, err := url.Parse(baseURI)
if err != nil {
return err
}

redirect, err := url.Parse(redirectURI)
if err != nil {
return err
}

// log.Println("---> base.Host => ", base.Host)
// log.Println("---> redirect.Host => ", redirect.Host)
if !strings.HasSuffix(redirect.Host, base.Host) {
return errors.New("invalid redirect uri")
}

return nil
}
Loading

0 comments on commit a39f3de

Please sign in to comment.