Skip to content

Commit

Permalink
Optimize type conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
guanguans committed Jan 15, 2022
1 parent 54c7196 commit b9229e0
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 72 deletions.
18 changes: 9 additions & 9 deletions checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,18 @@ package idvalidator
import (
"errors"
"regexp"
"strconv"
"strings"
"time"

"github.com/spf13/cast"
)

// 检查ID参数
// func checkIdArgument(id string) bool {
// _, err := generateCode(id)
//
// return err == nil
// }
func checkIDArgument(id string) bool {
_, err := generateCode(id)

return err == nil
}

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

// 检查出生日期码
func checkBirthdayCode(birthdayCode string) bool {
year, _ := strconv.Atoi(substr(birthdayCode, 0, 4))
year := cast.ToInt(substr(birthdayCode, 0, 4))
if year < 1800 {
return false
}

nowYear := time.Now().Year()
if year > nowYear {
if year > time.Now().Year() {
return false
}

Expand Down
40 changes: 16 additions & 24 deletions generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import (
"math"
"math/rand"
"regexp"
"strconv"
"strings"
"time"

"github.com/guanguans/id-validator/data"
"github.com/spf13/cast"
)

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

// 生成校验码
checkBit := (12 - (bodySum % 11)) % 11
if checkBit == 10 {
return "x"
}
return strconv.Itoa(checkBit)
return cast.ToString(checkBit)
}

// 生成地址码
func generatorAddressCode(address string) string {
addressCode := ""
for code, addressStr := range data.AddressCode {
if address == addressStr {
addressCode = strconv.Itoa(code)
addressCode = cast.ToString(code)
break
}
}

classification := addressCodeClassification(addressCode)
switch classification {
case "country":
// addressCode = getRandAddressCode("\\d{4}(?!00)[0-9]{2}$")
addressCode = getRandAddressCode("\\d{4}(?)[0-9]{2}$")
case "province":
provinceCode := substr(addressCode, 0, 2)
// pattern := "^" + provinceCode + "\\d{2}(?!00)[0-9]{2}$"
pattern := "^" + provinceCode + "\\d{2}(?)[0-9]{2}$"
pattern := "^" + substr(addressCode, 0, 2) + "\\d{2}(?)[0-9]{2}$"
addressCode = getRandAddressCode(pattern)
case "city":
cityCode := substr(addressCode, 0, 4)
// pattern := "^" + cityCode + "(?!00)[0-9]{2}$"
pattern := "^" + cityCode + "(?)[0-9]{2}$"
pattern := "^" + substr(addressCode, 0, 4) + "(?)[0-9]{2}$"
addressCode = getRandAddressCode(pattern)
}

Expand Down Expand Up @@ -102,7 +96,7 @@ func getRandAddressCode(pattern string) string {
mustCompile := regexp.MustCompile(pattern)
var keys []string
for key := range data.AddressCode {
keyStr := strconv.Itoa(key)
keyStr := cast.ToString(key)
if mustCompile.MatchString(keyStr) && substr(keyStr, 4, 6) != "00" {
keys = append(keys, keyStr)
}
Expand All @@ -121,7 +115,7 @@ func generatorBirthdayCode(addressCode string, address string, birthday string)
month := datePipelineHandle(datePad(substr(birthday, 4, 6), "month"), "month")
day := datePipelineHandle(datePad(substr(birthday, 6, 8), "day"), "day")

addressCodeInt, _ := strconv.Atoi(addressCode)
addressCodeInt := cast.ToInt(addressCode)
if _, ok := data.AddressCodeTimeline[addressCodeInt]; ok {
timeLine := data.AddressCodeTimeline[addressCodeInt]
for _, val := range timeLine {
Expand All @@ -136,13 +130,11 @@ func generatorBirthdayCode(addressCode string, address string, birthday string)
}
}

yearInt, _ := strconv.Atoi(year)
startYearInt, _ := strconv.Atoi(startYear)
endYearInt, _ := strconv.Atoi(endYear)
if yearInt < startYearInt {
yearInt := cast.ToInt(year)
if yearInt < cast.ToInt(startYear) {
year = startYear
}
if yearInt > endYearInt {
if yearInt > cast.ToInt(endYear) {
year = endYear
}

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

// 日期处理
func datePipelineHandle(date string, category string) string {
dateInt, _ := strconv.Atoi(date)
dateInt := cast.ToInt(date)

switch category {
case "year":
nowYear := time.Now().Year()
rand.Seed(time.Now().Unix())
if dateInt < 1800 || dateInt > nowYear {
randDate := rand.Intn(nowYear-1950) + 1950
date = strconv.Itoa(randDate)
date = cast.ToString(randDate)
}
case "month":
if dateInt < 1 || dateInt > 12 {
randDate := rand.Intn(12-1) + 1
date = strconv.Itoa(randDate)
date = cast.ToString(randDate)
}

case "day":
if dateInt < 1 || dateInt > 31 {
randDate := rand.Intn(28-1) + 1
date = strconv.Itoa(randDate)
date = cast.ToString(randDate)
}
}

Expand All @@ -194,7 +186,7 @@ func generatorOrderCode(sex int) string {
orderCode--
}

return strconv.Itoa(orderCode)
return cast.ToString(orderCode)
}

// 日期补全
Expand Down
4 changes: 1 addition & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ module github.com/guanguans/id-validator
go 1.14

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

"github.com/guanguans/id-validator/data"
"github.com/spf13/cast"
)

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

timeline := data.AddressCodeTimeline[addressCodeInt]
year, _ := strconv.Atoi(substr(birthdayCode, 0, 4))
year := cast.ToInt(substr(birthdayCode, 0, 4))
startYear := "0001"
endYear := "9999"
for _, val := range timeline {
Expand All @@ -76,9 +77,7 @@ func getAddress(addressCode string, birthdayCode string, strict bool) string {
if val["end_year"] != "" {
endYear = val["end_year"]
}
startYearInt, _ := strconv.Atoi(startYear)
endYearInt, _ := strconv.Atoi(endYear)
if year >= startYearInt && year <= endYearInt {
if year >= cast.ToInt(startYear) && year <= cast.ToInt(endYear) {
address = val["address"]
}
}
Expand All @@ -95,10 +94,8 @@ func getAddress(addressCode string, birthdayCode string, strict bool) string {

// 获取星座信息
func getConstellation(birthdayCode string) string {
monthStr := substr(birthdayCode, 4, 6)
dayStr := substr(birthdayCode, 6, 8)
month, _ := strconv.Atoi(monthStr)
day, _ := strconv.Atoi(dayStr)
month, _ := strconv.Atoi(substr(birthdayCode, 4, 6))
day, _ := strconv.Atoi(substr(birthdayCode, 6, 8))
startDate := data.Constellation[month]["start_date"]
startDay, _ := strconv.Atoi(strings.Split(startDate, "-")[1])
if day >= startDay {
Expand All @@ -117,7 +114,7 @@ func getConstellation(birthdayCode string) string {
func getChineseZodiac(birthdayCode string) string {
// 子鼠
start := 1900
end, _ := strconv.Atoi(substr(birthdayCode, 0, 4))
end := cast.ToInt(substr(birthdayCode, 0, 4))
key := (end - start) % 12

return data.ChineseZodiac[key]
Expand Down
15 changes: 7 additions & 8 deletions id_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ package idvalidator

import (
"errors"
"strconv"
"time"

"github.com/guanguans/id-validator/data"
"github.com/spf13/cast"
)

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

code, _ := generateCode(id)
addressCode, _ := strconv.Atoi(code["addressCode"])
addressCode := cast.ToInt(code["addressCode"])

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

// 性别
sex := 1
sexCode, _ := strconv.Atoi(code["order"])
if (sexCode % 2) == 0 {
if (cast.ToInt(code["order"]) % 2) == 0 {
sex = 0
}

// 长度
length, _ := strconv.Atoi(code["type"])
length := cast.ToInt(code["type"])

return IdInfo{
AddressCode: addressCode,
Expand Down Expand Up @@ -114,7 +113,7 @@ func FakeRequireId(isEighteen bool, address string, birthday string, sex int) st
var addressCode string
if address == "" {
for i, s := range data.AddressCode {
addressCode = strconv.Itoa(i)
addressCode = cast.ToString(i)
address = s
break
}
Expand All @@ -140,7 +139,7 @@ func FakeRequireId(isEighteen bool, address string, birthday string, sex int) st
// UpgradeId 15位升级18位号码
func UpgradeId(id string) (string, error) {
if !IsValid(id, true) {
return "", errors.New("not Valid ID card number")
return "", errors.New("invalid ID card number")
}

code, _ := generateShortCode(id)
Expand Down

0 comments on commit b9229e0

Please sign in to comment.