侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

浅析Go语言版本的forgery

Go  /  管理员 发布于 5年前   345

使用过Python语言的朋友们可能使用过 forgery_py ,它是一个伪造数据的工具。能伪造一些常用的数据。在我们开发过程和效果展示是十分有用。但是没有Go语言版本的,所以就动手折腾吧。

从源码入手

在forgery_py的 PyPi 有一段的实例代码:

>>> import forgery_py>>> forgery_py.address.street_address()u'4358 Shopko Junction'>>> forgery_py.basic.hex_color()'3F0A59'>>> forgery_py.currency.description()u'Slovenia Tolars'>>> forgery_py.date.date()datetime.date(2012, 7, 27)>>> forgery_py.internet.email_address()u'[email protected]'>>> forgery_py.lorem_ipsum.title()u'Pretium nam rhoncus ultrices!'>>> forgery_py.name.full_name()u'Mary Peters'>>> forgery_py.personal.language()u'Hungarian'

从以上的方法调用我们可以看出forgery_py下有一系列的 *.py 文件,里面有各种方法,实现各种功能,我们在来通过分析下Python版本的forgery_py的源码来看看它的实现原理。

# ForgeryPy 包的一级目录├── dictionaries # 伪造内容和来源目录,目录下存放的都是一些文本文件├── dictionaries_loader.py # 加载文件脚本├── forgery    # 主目录,实现各种数据伪造功能,目录下存放的都是python文件├── __init__.py

我们在来看下forgery目录下的脚本

$ cat name.pyimport randomfrom ..dictionaries_loader import get_dictionary__all__ = [  'first_name', 'last_name', 'full_name', 'male_first_name',  'female_first_name', 'company_name', 'job_title', 'job_title_suffix',  'title', 'suffix', 'location', 'industry']def first_name():  """Random male of female first name."""  _dict = get_dictionary('male_first_names')  _dict += get_dictionary('female_first_names')  return random.choice(_dict).strip()

__all__ 设置能被调用的方法。

first_name() 方法是forgery_py中一个典型伪造数据方法,我们只要来分析它就可以知道forgery_py的工作原理了。

这个方法代码很少,能容易就看出 _dict = get_dictionary('male_first_names') 和 _dict += get_dictionary('female_first_names') 获取的数据合并,在最后的 return random.choice(_dict).strip() 返回随机的数据。它的重点在于 get_dictionary() ,所以我们需要来看它的所在位置 dictionaries_loader.py 文件。

$ cat dictionaries_loaderimport randomDICTIONARIES_PATH = abspath(join(dirname(__file__), 'dictionaries'))dictionaries_cache = {}def get_dictionary(dict_name):  """  Load a dictionary file ``dict_name`` (if it's not cached) and return its  contents as an array of strings.  """  global dictionaries_cache  if dict_name not in dictionaries_cache:    try:      dictionary_file = codecs.open(        join(DICTIONARIES_PATH, dict_name), 'r', 'utf-8'      )    except IOError:      None    else:      dictionaries_cache[dict_name] = dictionary_file.readlines()      dictionary_file.close()  return dictionaries_cache[dict_name]

以上就是 dictionaries_loader.py 文件去掉注释后的所以要内容。它的主要实现就是:定义一个全局的字典参数 dictionaries_cache 作为缓存,然后定义方法 get_dictionary() 获取源数据, get_dictionary() 中每次forgery目录底下方法调用时先查看缓存,缓存字典中存在数据就直接输出,不存在就读取 dictionaries 底下的对应文件,并存入缓存。最后是返回数据。

总的来说forgery_py的原理就是:一个方法调用,去读内存中的缓存,存在就直接返回,不存在就到对应的文本文件中读取并写入缓存并返回。返回来的数据再随机选取输出结果。

使用Go语言实现

在了解了forgery_py的工作原理之后,我们就可以来使用Go语言来实现了。

# forgery的基本目录$ cat forgery├── dictionaries # 数据源│  ├── male_first_names├── name.go  # 具体功能实现└── loader.go # 加载数据

根据python版本的我们也来创建对应的目录。

实现数据的读取的缓存:

// forgery/loader.gopackage forgeryimport (  "os"  "io"  "bufio"  "math/rand"  "time"  "strings")// 全局的缓存mapvar dictionaries map[string][]string = make(map[string][]string)// 在获取数据之后随机输出func random(slice []string) string {  rand.Seed(time.Now().UnixNano())  n := rand.Intn(len(slice))  return strings.TrimSpace(slice[n])}// 主要的数据加载方法func loader(name string) (slice []string, err error) {  slice, ok := dictionaries[name]  // 缓存中存在数据,直接返回  if ok {    return slice, nil  }  // 读取对应文件  file, err := os.Open("./dictionaries/" + name)  if err != nil {    return slice, err  }  defer file.Close()  rd := bufio.NewReader(file)  for {    line, err := rd.ReadString('\n')    slice = append(slice, line)    if err != nil || io.EOF == err {      break    }  }  dictionaries[name] = slice  return slice, nil}// 统一的错误处理func checkErr(err error) (string, error) {  return "", err}

实现具体的功能:

// forgery/name.go// Random male of female first name.func FirstName() (string, error) {  slice, err := loader("male_first_names")  checkErr(err)  slice1, err := loader("female_first_names")  checkErr(err)  slice = append(slice, slice1...)  return random(slice), nil}

这样就将python语言版本的forgery_py使用Go来实现了。

最后

上面只是提及了一些工作原理,具体的源代码可以看 https://github.com/xingyys/fo... ,也十分感谢 https://github.com/tomekwojci... ,具体的思路和里面的数据源都是他提供的。本人就是做了一些 翻译 的的工作。

总结

以上所述是小编给大家介绍的Go语言版本的forgery,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站的支持!


  • 上一条:
    go语言实现聊天服务器的示例代码
    下一条:
    go语言同步教程之条件变量
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2017-09
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-12
    • 2021-01
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-08
    • 2024-11
    • 2025-02
    • 2025-04
    • 2025-05
    • 2025-06
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客