go的flag解析 生成密码
点击查看代码
package main
import (
"flag"
"fmt"
"math/rand"
"time"
)
var (
length int
charset string
)
const (
NumStr = "0123456789"
CharStr = "ABCDEFGHIKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
SpecStr = "!?$%^&*()_-+={[}]:;@~#|<,>./"
)
func parseArgs() {
flag.IntVar(&length, "l", 16, "-l 用户生成密码的长度")
flag.StringVar(&charset, "t", "num",
`-t 制定生成密码的字符集,
num: 只使用数字[0-9],
char:只使用英文字母[a-zA-A],
mix 使用数字和字母,
advance:使用数字,字母以及特殊字符`)
flag.Parse()
}
func generatePasswd() string {
var passwd []byte = make([]byte, length, length)
var sourceStr string
if charset == "num" {
sourceStr = NumStr
} else if charset == "char" {
sourceStr = CharStr
} else if charset == "mix" {
sourceStr = fmt.Sprintf("%s%s", NumStr, CharStr)
} else if charset == "advance" {
sourceStr = fmt.Sprintf("%s%s%s", NumStr, CharStr, SpecStr)
} else {
sourceStr = NumStr
}
fmt.Println("source:", sourceStr)
for i := 0; i < length; i++ {
index := rand.Intn(len(sourceStr))
passwd[i] = sourceStr[index]
}
return string(passwd)
}
func main() {
rand.Seed(time.Now().UnixNano())
parseArgs()
fmt.Printf("length:%d charset:%s\n", length, charset)
passwd := generatePasswd()
fmt.Println("passwd>>",passwd)
}
输出:
点击查看代码
API server listening at: 127.0.0.1:8345
length:16 charset:num
source: 0123456789
passwd>> 3441011573221112
写入自己的博客中才能记得长久