1 Star 0 Fork 43

Shirdon / go验证码合集包

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
wordmanager.go 2.18 KB
一键复制 编辑 Web IDE 原始数据 按行查看 历史
shirdon 提交于 2019-07-07 16:16 . commit
//++++++++++++++++++++++++++++++++++++++++
//Fighting for great,share generate value!
//Build the best soft by golang,let's go!
//++++++++++++++++++++++++++++++++++++++++
//Author:ShirDon <http://www.shirdon.com>
//Email:hcbsts@163.com; 823923263@qq.com
//++++++++++++++++++++++++++++++++++++++++
package captchas_with_go
import (
"encoding/csv"
"errors"
"io"
"os"
"strings"
"unicode/utf8"
)
//WordManager is a captcha word manage tool
type WordManager struct {
words []string
isDataSingleChar bool
isValid bool
}
//CreateWordManagerFromDataFile will create a entity from a dictionary file
func CreateWordManagerFromDataFile(filename string) (*WordManager, error) {
mgr := &WordManager{}
mgr.words = []string{}
mgr.isValid = false
f, err := os.Open(filename)
if nil != err {
return mgr, err
}
defer f.Close()
reader := csv.NewReader(f)
mgr.isDataSingleChar = true
for {
record, err := reader.Read()
if err == io.EOF {
break
} else if nil != err {
return mgr, err
}
if 1 < len([]rune(record[0])) {
mgr.isDataSingleChar = false
}
mgr.words = append(mgr.words, strings.TrimSpace(record[0]))
}
mgr.isValid = true
return mgr, nil
}
//Get a specifical length word
func (mgr *WordManager) Get(length int) (string, error) {
var retErr error
rst := ""
if mgr.isValid {
if true == mgr.isDataSingleChar {
if len(mgr.words) < length {
return "", errors.New("dict words count is less than your length")
}
for {
line := mgr.getLine()
if false == strings.ContainsRune(rst, []rune(line)[0]) {
rst = rst + line
}
if utf8.RuneCountInString(rst) >= length {
break
}
}
rstRune := []rune(rst)
rst = string(rstRune[0:length])
} else {
rst = mgr.getLine()
}
} else {
retErr = errors.New("WordManager is invalid")
}
return rst, retErr
}
func (mgr *WordManager) SetWords(words []string) {
mgr.words = words
mgr.isValid = len(words) > 0
mgr.isDataSingleChar = true
for _, s := range words {
if len([]rune(s)) > 1 {
mgr.isDataSingleChar = false
}
}
}
func (mgr *WordManager) getLine() string {
maxIndex := len(mgr.words) - 1
rstIndex := rnd(0, maxIndex)
rst := mgr.words[rstIndex]
return rst
}
Go
1
https://gitee.com/shirdon/captchas_with_go.git
git@gitee.com:shirdon/captchas_with_go.git
shirdon
captchas_with_go
go验证码合集包
master

搜索帮助