Go language version of forgery

Source: Internet
Author: User

Friends who have used the Python language may have used forgery_py, which is a tool for falsifying data. Can forge some commonly used data. It is very useful in our development process and effect presentation. But there is no go language version, so just toss it.

Start with the source code

In Forgery_py's PyPi There is an example code:

>>> 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'brian@zazio.mil'>>> forgery_py.lorem_ipsum.title()u'Pretium nam rhoncus ultrices!'>>> forgery_py.name.full_name()u'Mary Peters'>>> forgery_py.personal.language()u'Hungarian'

From the above method call we can see Forgery_py a series of *.py files, there are various methods to achieve various functions, we have to analyze the Python version of the forgery_py source to see its implementation principle.

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

We're looking at the script under the forgery directory.

$ 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()

The

__all__ Sets the method that can be called. The
first_name () method is a typical falsified data method in Forgery_py, so we can just analyze it to see how forgery_py works.
This method code is very small, can be easily seen _dict = get_dictionary (' male_first_names ') and _dict + = get_dictionary (' Female_ First_names ') gets the data merge, in the last return Random.choice (_dict). Strip () returns random data. It's focused on get_dictionary () , so we need to look at the dictionaries_loader.py file where it's located.

 $ 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 their contents as an array of strings. "" "Global Dictionaries_cache if dict_name not in Dictionaries_cache:try:dictionary_file = Codec S.open (Join (Dictionaries_path, Dict_name), ' R ', ' Utf-8 ') except Ioerror:non    E Else:dictionaries_cache[dict_name] = Dictionary_file.readlines () dictionary_file.close () return Dictionaries_cache[dict_name]  

The above is the dictionaries_loader.py file to remove the comments after the content. Its main implementation is: To define a global dictionary parameters dictionaries_cache as a cache, and then define the method get_dictionary() to get the source data, get_dictionary() each time the forgery directory under the method call the first view of the cache, the cache dictionary exists in the data directly output, does not exist to read Dictionaries the corresponding file below and cache it. The last is the return data.
In general, the principle of forgery_py is: A method call, to read the memory cache, the presence of the direct return, does not exist in the corresponding text file read and write to the cache and return. The returned data is then randomly selected to output the result.

Use the go language to implement

Once we understand how forgery_py works, we can use the go language to implement it.

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

According to the Python version we also create the corresponding directory.
To implement a read cache of data:

 //forgery/loader.gopackage forgeryimport ("OS" "IO" "Bufio" "Math/rand" "Time" Strings ")//Global cache Mapvar Dictionaries map[string][]string = Make (map[string][]string)//random output after fetching data func random (slice [] String) string {rand. Seed (time. Now (). Unixnano ()) N: = Rand. INTN (len (slice)) return strings.    Trimspace (Slice[n])}//Primary Data Load method Func loader (name string) (slice []string, err Error) {slice, OK: = Dictionaries[name] There is data in the cache, return directly if OK {return slice, nil}//read the corresponding 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}//unified error handling func Checkerr (err Error (string, error) {return "", err}  

To achieve specific functions:

// 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}

This enables the Python language version of Forgery_py to be used by go.

At last

Above just mentioned some work principle, the specific source code can see https://github.com/xingyys/fo ..., also very grateful to Https://github.com/tomekwojci ..., The specific ideas and the data sources are provided by him. I have done some translation work.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.