Skip to content

Commit b9229e0

Browse files
committed
Optimize type conversion
1 parent 54c7196 commit b9229e0

File tree

6 files changed

+48
-72
lines changed

6 files changed

+48
-72
lines changed

checker.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,18 @@ package idvalidator
77
import (
88
"errors"
99
"regexp"
10-
"strconv"
1110
"strings"
1211
"time"
12+
13+
"github.com/spf13/cast"
1314
)
1415

1516
// 检查ID参数
16-
// func checkIdArgument(id string) bool {
17-
// _, err := generateCode(id)
18-
//
19-
// return err == nil
20-
// }
17+
func checkIDArgument(id string) bool {
18+
_, err := generateCode(id)
19+
20+
return err == nil
21+
}
2122

2223
// 生成数据
2324
func generateCode(id string) (map[string]string, error) {
@@ -77,13 +78,12 @@ func checkAddressCode(addressCode string, birthdayCode string, strict bool) bool
7778

7879
// 检查出生日期码
7980
func checkBirthdayCode(birthdayCode string) bool {
80-
year, _ := strconv.Atoi(substr(birthdayCode, 0, 4))
81+
year := cast.ToInt(substr(birthdayCode, 0, 4))
8182
if year < 1800 {
8283
return false
8384
}
8485

85-
nowYear := time.Now().Year()
86-
if year > nowYear {
86+
if year > time.Now().Year() {
8787
return false
8888
}
8989

generator.go

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@ import (
88
"math"
99
"math/rand"
1010
"regexp"
11-
"strconv"
1211
"strings"
1312
"time"
1413

1514
"github.com/guanguans/id-validator/data"
15+
"github.com/spf13/cast"
1616
)
1717

1818
// 生成Bit码
@@ -29,42 +29,36 @@ func generatorCheckBit(body string) string {
2929
bodyArray := strings.Split(body, "")
3030
count := len(bodyArray)
3131
for i := 0; i < count; i++ {
32-
bodySub, _ := strconv.Atoi(bodyArray[i])
33-
bodySum += bodySub * int(posWeight[18-i])
32+
bodySum += cast.ToInt(bodyArray[i]) * int(posWeight[18-i])
3433
}
3534

3635
// 生成校验码
3736
checkBit := (12 - (bodySum % 11)) % 11
3837
if checkBit == 10 {
3938
return "x"
4039
}
41-
return strconv.Itoa(checkBit)
40+
return cast.ToString(checkBit)
4241
}
4342

4443
// 生成地址码
4544
func generatorAddressCode(address string) string {
4645
addressCode := ""
4746
for code, addressStr := range data.AddressCode {
4847
if address == addressStr {
49-
addressCode = strconv.Itoa(code)
48+
addressCode = cast.ToString(code)
5049
break
5150
}
5251
}
5352

5453
classification := addressCodeClassification(addressCode)
5554
switch classification {
5655
case "country":
57-
// addressCode = getRandAddressCode("\\d{4}(?!00)[0-9]{2}$")
5856
addressCode = getRandAddressCode("\\d{4}(?)[0-9]{2}$")
5957
case "province":
60-
provinceCode := substr(addressCode, 0, 2)
61-
// pattern := "^" + provinceCode + "\\d{2}(?!00)[0-9]{2}$"
62-
pattern := "^" + provinceCode + "\\d{2}(?)[0-9]{2}$"
58+
pattern := "^" + substr(addressCode, 0, 2) + "\\d{2}(?)[0-9]{2}$"
6359
addressCode = getRandAddressCode(pattern)
6460
case "city":
65-
cityCode := substr(addressCode, 0, 4)
66-
// pattern := "^" + cityCode + "(?!00)[0-9]{2}$"
67-
pattern := "^" + cityCode + "(?)[0-9]{2}$"
61+
pattern := "^" + substr(addressCode, 0, 4) + "(?)[0-9]{2}$"
6862
addressCode = getRandAddressCode(pattern)
6963
}
7064

@@ -102,7 +96,7 @@ func getRandAddressCode(pattern string) string {
10296
mustCompile := regexp.MustCompile(pattern)
10397
var keys []string
10498
for key := range data.AddressCode {
105-
keyStr := strconv.Itoa(key)
99+
keyStr := cast.ToString(key)
106100
if mustCompile.MatchString(keyStr) && substr(keyStr, 4, 6) != "00" {
107101
keys = append(keys, keyStr)
108102
}
@@ -121,7 +115,7 @@ func generatorBirthdayCode(addressCode string, address string, birthday string)
121115
month := datePipelineHandle(datePad(substr(birthday, 4, 6), "month"), "month")
122116
day := datePipelineHandle(datePad(substr(birthday, 6, 8), "day"), "day")
123117

124-
addressCodeInt, _ := strconv.Atoi(addressCode)
118+
addressCodeInt := cast.ToInt(addressCode)
125119
if _, ok := data.AddressCodeTimeline[addressCodeInt]; ok {
126120
timeLine := data.AddressCodeTimeline[addressCodeInt]
127121
for _, val := range timeLine {
@@ -136,13 +130,11 @@ func generatorBirthdayCode(addressCode string, address string, birthday string)
136130
}
137131
}
138132

139-
yearInt, _ := strconv.Atoi(year)
140-
startYearInt, _ := strconv.Atoi(startYear)
141-
endYearInt, _ := strconv.Atoi(endYear)
142-
if yearInt < startYearInt {
133+
yearInt := cast.ToInt(year)
134+
if yearInt < cast.ToInt(startYear) {
143135
year = startYear
144136
}
145-
if yearInt > endYearInt {
137+
if yearInt > cast.ToInt(endYear) {
146138
year = endYear
147139
}
148140

@@ -160,26 +152,26 @@ func generatorBirthdayCode(addressCode string, address string, birthday string)
160152

161153
// 日期处理
162154
func datePipelineHandle(date string, category string) string {
163-
dateInt, _ := strconv.Atoi(date)
155+
dateInt := cast.ToInt(date)
164156

165157
switch category {
166158
case "year":
167159
nowYear := time.Now().Year()
168160
rand.Seed(time.Now().Unix())
169161
if dateInt < 1800 || dateInt > nowYear {
170162
randDate := rand.Intn(nowYear-1950) + 1950
171-
date = strconv.Itoa(randDate)
163+
date = cast.ToString(randDate)
172164
}
173165
case "month":
174166
if dateInt < 1 || dateInt > 12 {
175167
randDate := rand.Intn(12-1) + 1
176-
date = strconv.Itoa(randDate)
168+
date = cast.ToString(randDate)
177169
}
178170

179171
case "day":
180172
if dateInt < 1 || dateInt > 31 {
181173
randDate := rand.Intn(28-1) + 1
182-
date = strconv.Itoa(randDate)
174+
date = cast.ToString(randDate)
183175
}
184176
}
185177

@@ -194,7 +186,7 @@ func generatorOrderCode(sex int) string {
194186
orderCode--
195187
}
196188

197-
return strconv.Itoa(orderCode)
189+
return cast.ToString(orderCode)
198190
}
199191

200192
// 日期补全

go.mod

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@ module github.com/guanguans/id-validator
33
go 1.14
44

55
require (
6-
github.com/fatih/color v1.10.0 // indirect
7-
github.com/rakyll/gotest v0.0.6 // indirect
8-
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7 // indirect
6+
github.com/spf13/cast v1.4.1
97
gopkg.in/ffmt.v1 v1.5.6
108
)

go.sum

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,10 @@
1-
github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
2-
github.com/fatih/color v1.10.0 h1:s36xzo75JdqLaaWoiEHk767eHiwo0598uUxyfiPkDsg=
3-
github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM=
4-
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
5-
github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
6-
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
7-
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
8-
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
9-
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
10-
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
11-
github.com/rakyll/gotest v0.0.6 h1:hBTqkO3jiuwYW/M9gL4bu0oTYcm8J6knQAAPUsJsz1I=
12-
github.com/rakyll/gotest v0.0.6/go.mod h1:SkoesdNCWmiD4R2dljIUcfSnNdVZ12y8qK4ojDkc2Sc=
13-
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
14-
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
15-
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
16-
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
17-
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7 h1:iGu644GcxtEcrInvDsQRCwJjtCIOlT2V7IRt6ah2Whw=
18-
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
1+
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
2+
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
3+
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
4+
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
5+
github.com/spf13/cast v1.4.1 h1:s0hze+J0196ZfEMTs80N7UlFt0BDuQ7Q+JDnHiMWKdA=
6+
github.com/spf13/cast v1.4.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
7+
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
8+
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
199
gopkg.in/ffmt.v1 v1.5.6 h1:4Bu3riZp5sAIXW2T/18JM9BkwJLodurXFR0f7PXp+cw=
2010
gopkg.in/ffmt.v1 v1.5.6/go.mod h1:LssvGOZFiBGoBcobkTqnyh+uN1VzIRoibW+c0JI/Ha4=

helper.go

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"strings"
1010

1111
"github.com/guanguans/id-validator/data"
12+
"github.com/spf13/cast"
1213
)
1314

1415
// 获取地址信息
@@ -41,7 +42,7 @@ func getAddressInfo(addressCode string, birthdayCode string, strict bool) map[st
4142
// 获取省市区地址码
4243
func getAddress(addressCode string, birthdayCode string, strict bool) string {
4344
address := ""
44-
addressCodeInt, _ := strconv.Atoi(addressCode)
45+
addressCodeInt := cast.ToInt(addressCode)
4546
if _, ok := data.AddressCodeTimeline[addressCodeInt]; !ok {
4647
// 修复 \d\d\d\d01、\d\d\d\d02、\d\d\d\d11 和 \d\d\d\d20 的历史遗留问题
4748
// 以上四种地址码,现实身份证真实存在,但民政部历年公布的官方地址码中可能没有查询到
@@ -66,7 +67,7 @@ func getAddress(addressCode string, birthdayCode string, strict bool) string {
6667
}
6768

6869
timeline := data.AddressCodeTimeline[addressCodeInt]
69-
year, _ := strconv.Atoi(substr(birthdayCode, 0, 4))
70+
year := cast.ToInt(substr(birthdayCode, 0, 4))
7071
startYear := "0001"
7172
endYear := "9999"
7273
for _, val := range timeline {
@@ -76,9 +77,7 @@ func getAddress(addressCode string, birthdayCode string, strict bool) string {
7677
if val["end_year"] != "" {
7778
endYear = val["end_year"]
7879
}
79-
startYearInt, _ := strconv.Atoi(startYear)
80-
endYearInt, _ := strconv.Atoi(endYear)
81-
if year >= startYearInt && year <= endYearInt {
80+
if year >= cast.ToInt(startYear) && year <= cast.ToInt(endYear) {
8281
address = val["address"]
8382
}
8483
}
@@ -95,10 +94,8 @@ func getAddress(addressCode string, birthdayCode string, strict bool) string {
9594

9695
// 获取星座信息
9796
func getConstellation(birthdayCode string) string {
98-
monthStr := substr(birthdayCode, 4, 6)
99-
dayStr := substr(birthdayCode, 6, 8)
100-
month, _ := strconv.Atoi(monthStr)
101-
day, _ := strconv.Atoi(dayStr)
97+
month, _ := strconv.Atoi(substr(birthdayCode, 4, 6))
98+
day, _ := strconv.Atoi(substr(birthdayCode, 6, 8))
10299
startDate := data.Constellation[month]["start_date"]
103100
startDay, _ := strconv.Atoi(strings.Split(startDate, "-")[1])
104101
if day >= startDay {
@@ -117,7 +114,7 @@ func getConstellation(birthdayCode string) string {
117114
func getChineseZodiac(birthdayCode string) string {
118115
// 子鼠
119116
start := 1900
120-
end, _ := strconv.Atoi(substr(birthdayCode, 0, 4))
117+
end := cast.ToInt(substr(birthdayCode, 0, 4))
121118
key := (end - start) % 12
122119

123120
return data.ChineseZodiac[key]

id_validator.go

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ package idvalidator
66

77
import (
88
"errors"
9-
"strconv"
109
"time"
1110

1211
"github.com/guanguans/id-validator/data"
12+
"github.com/spf13/cast"
1313
)
1414

1515
// IdInfo 身份证信息
@@ -51,11 +51,11 @@ func IsValid(id string, strict bool) bool {
5151
func GetInfo(id string, strict bool) (IdInfo, error) {
5252
// 验证有效性
5353
if !IsValid(id, strict) {
54-
return IdInfo{}, errors.New("not Valid ID card number")
54+
return IdInfo{}, errors.New("invalid ID card number")
5555
}
5656

5757
code, _ := generateCode(id)
58-
addressCode, _ := strconv.Atoi(code["addressCode"])
58+
addressCode := cast.ToInt(code["addressCode"])
5959

6060
// 地址信息
6161
addressInfo := getAddressInfo(code["addressCode"], code["birthdayCode"], strict)
@@ -76,13 +76,12 @@ func GetInfo(id string, strict bool) (IdInfo, error) {
7676

7777
// 性别
7878
sex := 1
79-
sexCode, _ := strconv.Atoi(code["order"])
80-
if (sexCode % 2) == 0 {
79+
if (cast.ToInt(code["order"]) % 2) == 0 {
8180
sex = 0
8281
}
8382

8483
// 长度
85-
length, _ := strconv.Atoi(code["type"])
84+
length := cast.ToInt(code["type"])
8685

8786
return IdInfo{
8887
AddressCode: addressCode,
@@ -114,7 +113,7 @@ func FakeRequireId(isEighteen bool, address string, birthday string, sex int) st
114113
var addressCode string
115114
if address == "" {
116115
for i, s := range data.AddressCode {
117-
addressCode = strconv.Itoa(i)
116+
addressCode = cast.ToString(i)
118117
address = s
119118
break
120119
}
@@ -140,7 +139,7 @@ func FakeRequireId(isEighteen bool, address string, birthday string, sex int) st
140139
// UpgradeId 15位升级18位号码
141140
func UpgradeId(id string) (string, error) {
142141
if !IsValid(id, true) {
143-
return "", errors.New("not Valid ID card number")
142+
return "", errors.New("invalid ID card number")
144143
}
145144

146145
code, _ := generateShortCode(id)

0 commit comments

Comments
 (0)