<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by ChopperLee on Medium]]></title>
        <description><![CDATA[Stories by ChopperLee on Medium]]></description>
        <link>https://medium.com/@lihengpro?source=rss-5e5fe6ccbb6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nQaSMeU_yXCddKcw.jpg</url>
            <title>Stories by ChopperLee on Medium</title>
            <link>https://medium.com/@lihengpro?source=rss-5e5fe6ccbb6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 09:00:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lihengpro/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Read files in Go]]></title>
            <link>https://medium.com/@lihengpro/read-files-in-go-4a2f4c78a4e0?source=rss-5e5fe6ccbb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a2f4c78a4e0</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[ChopperLee]]></dc:creator>
            <pubDate>Thu, 28 Jul 2016 08:23:07 GMT</pubDate>
            <atom:updated>2016-08-05T02:29:58.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QygM_UeFWCDYVasu8pyu7g.jpeg" /></figure><h4>Introduction</h4><p>My team members in Wiredcraft begin to use tools which are writing in Go or even using Go directly on our projects like <a href="https://wiredcraft.com/blog/building-myanmar-voter-registration-software/">building the voter registration for Myanmar elections</a>. And as a fun of strongly-typed programming language, I think it is time to check out this young language. Go (also referred to as golang) likes other programming languages, offer many standard libraries to help users handler files by buffer, position or line. But not like Java or Node.js, Go doesn’t have any standard asynchronous I/O lib, actually you can easily use Go concurrency to implement non-blocking I/O. As a Go beginner, I gonna try to list some methods for Reading and catching wanted information in files by Go.</p><h4>Examples</h4><p>You can get demo code in my github repo <a href="https://github.com/ChopperLee2011/query_file_demo">query_file_demo</a>.</p><ol><li>Ok, let us start with the the most simple way: using ioutil lib</li></ol><pre>func SimpleReader(path string) string {<br> f, err := ioutil.ReadFile(path)<br> CheckError(err)<br> lines := strings.Split(string(f), &quot;\n&quot;)<br> re := regexp.MustCompile(`\bslowpoke\b`)<br> var result string</pre><pre>for _, line := range lines {<br>  if re.MatchString(line) {<br>   result = line<br>  }<br> }<br> return result<br>}</pre><p>Then <strong>strings.Split()</strong> can help to convert loaded content to a string array. And <strong>regexp.MatchString()</strong> will match the regex expression with each element of the array. But you should not read a file with <strong>ioutil.ReadFile()</strong> method when the file is too large to load in memory once, you can know why from the Go lib’s <a href="https://github.com/golang/go/blob/master/src/io/ioutil/ioutil.go#L18">source code</a></p><pre>func ReadFile(filename string) ([]byte, error) {</pre><pre>...</pre><pre>return readAll(f, n+bytes.MinRead)<br>}</pre><p>There<strong> n</strong> is size of the file, you will get <strong>bytes.ErrTooLarge</strong> if the file overflows the buffer.</p><p>2. Then you can try to use bufio lib:</p><pre>func Scanner(path string) string {<br> f, err := os.Open(path)<br> CheckError(err)<br> defer f.Close()</pre><pre>var result string<br> scanner := bufio.NewScanner(f)<br> re := regexp.MustCompile(`\bslowpoke\b`)<br> for scanner.Scan() {<br>  s := scanner.Text()<br>  if re.MatchString(s) {<br>   result = s<br>  }<br> }<br> return result<br>}</pre><p>Again, you can read the <a href="https://github.com/golang/go/blob/master/src/bufio/scan.go#L81">source code</a> of NewScanner function:</p><pre>const ( <br>// MaxScanTokenSize is the maximum size used to buffer a token <br>// unless the user provides an explicit buffer with Scan.Buffer. <br>// The actual maximum token size may be smaller as the buffer <br>// may need to include, for instance, a newline. <br>  MaxScanTokenSize = 64 * 1024  <br>  startBufSize = 4096 // Size of initial allocation for buffer.<br>)<br>func NewScanner(r io.Reader) *Scanner { <br>  return &amp;Scanner{  <br>    r:            r,  <br>    split:        ScanLines,  <br>    maxTokenSize: MaxScanTokenSize, <br>    }<br>}</pre><p>There<strong> MaxScanTokenSize</strong> is the max size for each line, but it is reading one line per time, only if you line size is above <strong>MaxScanTokenSize</strong>, then you can read the file as big as you want. If you do not want the way that reads a file one by one line, you can change to file.Read(), IO.copy(), these apis allow you to define a buffer size when read a file.</p><p>3. Still if you want to use Go concurrency to help you to make the job faster. You can using Go channel and g<a href="https://gobyexample.com/goroutines">oroutines</a>.</p><pre>func ChannelReader(path string) string {<br> works := 10<br> f, err := os.Open(path)<br> CheckError(err)<br> defer f.Close()<br> jobs := make(chan string)<br> results := make(chan string)<br> complete := make(chan bool)</pre><pre>go func() {<br>  scanner := bufio.NewScanner(f)<br>  for scanner.Scan() {<br>   jobs &lt;- scanner.Text()<br>  }<br>  close(jobs)<br> }()</pre><pre>for i := 0; i &lt;= works; i++ {<br>  go grepLine(jobs, results, complete)<br> }</pre><pre>for i := 0; i &lt; works; i++ {<br>  &lt;-complete<br> }<br> return &lt;-results<br>}</pre><pre>func grepLine(jobs &lt;-chan string, results chan&lt;- string, complete chan bool) {<br> re := regexp.MustCompile(`\bslowpoke\b`)<br> for j := range jobs {<br>  if re.MatchString(j) {<br>   results &lt;- j<br>  }<br> }<br> complete &lt;- true<br>}</pre><p>This code create 10 g<a href="https://gobyexample.com/goroutines">oroutines</a> for the grep information job, when every g<a href="https://gobyexample.com/goroutines">oroutine</a> finished, the complete channel with get all true value, then blocking code &lt;-complete can pass.</p><h4>Bechmark</h4><p>Go Testing Suit `testing` not only support automated testing of Go packages, but also contains benchmark tools. Just write your test case and run the command, turn on the -benchmem flag add the result with memory consumption.</p><pre>go test -bench=. -benchmem</pre><p>Here is the result from my compute, cause i am using a small file to test, so the results and the bench directory in my repo is just telling the way to benchmark your function.</p><pre>testing: warning: no tests to run<br>PASS<br>BenchmarkChannelReader-4 grep line: 79,slowpoke,79,12,360,63,98,1<br>    1000    1712159 ns/op   490096 B/op     1149 allocs/op<br>BenchmarkScanner-4       79,slowpoke,79,12,360,63,98,1<br>    1000    1766001 ns/op    77130 B/op      846 allocs/op<br>BenchmarkSimpleReader-4  grep line: 79,slowpoke,79,12,360,63,98,1<br>    1000    1791945 ns/op   112651 B/op       37 allocs/op<br>ok   github.com/chopperlee2011/query_file_demo/bench 5.816s</pre><h4>conclusion</h4><p>I am glad to know that Go support convenient and fast lib for doing such concurrency works, which can make developer breaking through some technic bottleneck when builded some apps by other languages, and the performance of Go tools or framework, such as Gin, NSQ really impressive me. If you want to dig more into Go, I think <a href="https://www.gopheracademy.com/">gopher academy</a> website is a good place, and you can meet more Go gopher in their <a href="https://blog.gopheracademy.com/gophers-slack-community/">Slack channel</a>, hope you will enjoy there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a2f4c78a4e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a logger lib with Node.js]]></title>
            <link>https://medium.com/@lihengpro/how-to-build-a-logger-lib-with-node-js-63b163d612c7?source=rss-5e5fe6ccbb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/63b163d612c7</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[ChopperLee]]></dc:creator>
            <pubDate>Mon, 14 Mar 2016 06:33:37 GMT</pubDate>
            <atom:updated>2016-08-02T07:18:19.374Z</atom:updated>
            <content:encoded><![CDATA[<h4># My node lib</h4><p>When your Node.js app is getting bigger and aggregation of more components, you may want to have a logging system to trace event on each component or store error information for detecting. So let us begin to write a logger lib with Node.js for project sharing.</p><p>Firstly, i should figure out the lib’s features:</p><p>1. can be configurable for multi log steams, such as file storage for dev and syslog for production.</p><p>2. logger template, pre-defined template log template will help different project’s component sharing neat log format easily.</p><p>3. logger level can be changed in the code.</p><p>Secondly, choose tools cause i don’t want to restart from nothing:</p><p>1. bunyan and wiston are both very popular logging frameworks, the biggest different is bunyan use JSON format which make logging a big object data more directly. Due to easy use for implementing logger template, i plan to use bunyan.</p><p>2. node-bunyan-logger is a plugins lib which can help transfer logging data to syslog, it works fine in my mac, but watch out your OS and Node.js version, cause it do not support all.</p><p>3. also for implementing logger template feature, i need an object validator lib for defining logger schema. I find <a href="https://github.com/hapijs/joi">JOI</a> lib which has complete method and active project management.</p><h4>#Let’s begging to write the lib.</h4><p>Here is the my lib <a href="https://github.com/Wiredcraft/bunyan-logger">bunyan-logger</a> link, you can see the details and ask questions there.</p><ol><li>write a steam factory for getting logger steam configure.</li></ol><pre><strong>const </strong>bsyslog = require(&#39;bunyan-syslog&#39;);<br><br>exports.syslog = (opt) =&gt; {<br>  <strong>return </strong>{<br>    type: &#39;raw&#39;,<br>    stream: bsyslog.createBunyanStream({<br>      host: opt.syslogHost || &#39;localhost&#39;,<br>      port: parseInt(opt.syslogPort || 514, 10),<br>      facility: bsyslog.facility.local0,<br>      type: &#39;sys&#39;<br>    })<br>  };<br>};</pre><pre>exports.file = (opt) =&gt; {<br>  <strong>return </strong>{<br>    path: opt.filePath || &#39;./app.log&#39;<br>  };<br>};</pre><p>2. implement logger instance code.</p><pre><strong>const </strong>LOGGER = Symbol();</pre><pre><strong>class </strong>BunyanLogger {<br>  <strong>this</strong>.streams = BunyanLogger.<em>setStreams</em>(opt);<br>  <strong>this</strong>[LOGGER] = bunyan.createLogger({<br>    name: opt.name || &#39;APP&#39;,<br>    streams: <strong>this</strong>.streams<br>  });<br>}</pre><p>use ES2015 class syntax, i can clearly define a logger class with static or not static method, constructor and getter-setter method.</p><p>3. define logger template. After setup some log schema, i can use it format and verify the raw data with JOI lib.</p><pre>formated(payload) {<br>  <strong>let </strong>httpSchema = Joi.object().keys({<br>    type: Joi.string(),<br>    direction: Joi.string(),<br>    actionType: Joi.string(),<br>    target: Joi.string().required(),<br>    targetModule: Joi.string(),<br>    transactionId: Joi.string(),<br>    appId: Joi.string(),<br>    statusCode: Joi.number().allow(<strong>null</strong>)<br>  });<br>}<br><strong>switch </strong>(<strong>this</strong>.format) {<br>    <strong>case </strong>&#39;request&#39;:<br>      Joi.validate({<br>        type: &#39;HTTP&#39;,<br>        direction: &#39;IN&#39;,<br>        actionType: &#39;REQ&#39;,<br>        target: payload.method + &#39;:&#39; + payload.originalUrl,<br>        targetModule: payload.targetModule.toUpperCase(),<br>        transactionId: payload.transactionId,<br>        appId: payload.appId,<br>        statusCode: payload.statusCode<br>      }, httpSchema, (err, value)=&gt; {<br>        <strong>if </strong>(err) {<br>          <strong>throw </strong>err;<br>        }<br>        formatedLog = value;<br>      });<br>      <strong>break</strong>;<br>    <strong>case </strong>&#39;response&#39;:<br>      Joi.validate({<br>        type: &#39;HTTP&#39;,<br>        direction: &#39;OUT&#39;,<br>        actionType: &#39;RESP&#39;,<br>        target: payload.method + &#39;:&#39; + payload.originalUrl,<br>        targetModule: payload.targetModule.toUpperCase(),<br>        transactionId: payload.transactionId,<br>        appId: payload.appId,<br>        statusCode: payload.statusCode<br>      }, httpSchema, (err, value)=&gt; {<br>        <strong>if </strong>(err) {<br>          <strong>throw </strong>err;<br>        }<br>        formatedLog = value;<br>      });<br>      <strong>break</strong>;<br>    <strong>case </strong>&#39;error&#39;:<br>      Joi.validate({<br>        type: &#39;ERROR&#39;,<br>        targetModule: payload.targetModule.toUpperCase(),<br>        message: payload.message,<br>        code: payload.code<br>      }, errSchema, (err, value)=&gt; {<br>        <strong>if </strong>(err) {<br>          <strong>throw </strong>err;<br>        }<br>        formatedLog = value;<br>      });<br>      <strong>break</strong>;<br>    <strong>default</strong>:<br>      formatedLog = {<br>        type: &#39;MESSAGE&#39;,<br>        message: payload.message<br>      };<br>      <strong>break</strong>;<br>  }<br>  <strong>return </strong>formatedLog;<br>}</pre><h4># test code with mocha</h4><p>test code is not only for check whether lib’s features work correctly or not , but also a good way to show user how to use this lib.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63b163d612c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create unique constraint on loopback model with nosql database]]></title>
            <link>https://medium.com/@lihengpro/how-to-create-unique-constraint-on-loopback-model-with-nosql-database-52a90f21022e?source=rss-5e5fe6ccbb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/52a90f21022e</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[ChopperLee]]></dc:creator>
            <pubDate>Thu, 26 Nov 2015 03:36:26 GMT</pubDate>
            <atom:updated>2019-01-08T02:12:36.548Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fplay.ht%2Farticles%2F52a90f21022e&amp;src=https%3A%2F%2Fplay.ht%2Fembed%2F%3Farticle_url%3Dhttps%3A%2F%2Fmedium.com%2F_p%2Fhow-to-create-unique-constraint-on-loopback-model-with-nosql-database-52a90f21022e&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=play" width="700" height="185" frameborder="0" scrolling="no"><a href="https://medium.com/media/58e5141c344f2226b249077bd2123321/href">https://medium.com/media/58e5141c344f2226b249077bd2123321/href</a></iframe><p>Currently, I am using <a href="http://loopback.io/">Loopback</a> as backend framework for implement some restful APIs, and nosql database like <a href="http://www.couchbase.com/">couchbase</a> for storing persisted data. I encounter problem on how to create unique constraint on the model, cause many nosql database do not have unique constraint feature on properties which is not key of document, for example: a model like customer: {id,name,email,address}, id is the key but what if i want email property to be unique too. I find a simple way to create a loopback mixin which is a hook on create data for achieving this function.</p><h4>Init the project</h4><ul><li>mkdir loopback-nosql-unique-mixin &amp;&amp; cd $_</li><li>npm init</li></ul><h4>Define mixin</h4><pre>module.exports = <strong>(</strong>Model, options<strong>) </strong>=&gt; {<br>  <strong>&#39;use strict&#39;</strong>;<br>  Model.observe<strong>(&#39;before save&#39;</strong>, <strong>(</strong>ctx, next<strong>) </strong>=&gt; {<strong><em><br>    </em>if (</strong>ctx.<strong>instance </strong>&amp;&amp; ctx.<strong>isNewInstance) </strong>{<br>      Model.<strong>app</strong>.models.unique.createKey<strong>(</strong>ctx.<strong>instance[</strong>options.<strong>column]</strong>, Model.<strong>modelName)</strong>.then<strong>(</strong>next<strong>())</strong>;<br>    } <strong>else </strong>{<br>      next<strong>()</strong>;<br>    }<br>  }<strong>)</strong>;<br>Model.observe<strong>(&#39;before delete&#39;</strong>, <strong>(</strong>ctx, next<strong>) </strong>=&gt; {<br>   next<strong>(&#39;delete the unique doc&#39;)</strong>;<br>  }<strong>)</strong>;<br>}</pre><p>loopback applies many <a href="https://docs.strongloop.com/display/public/LB/Operation+hooks">operation hooks</a> which are triggered on CRUD operation on the model, `before save` means this hook is before the create and update method invoke. `ctx` parma is the target model instance, cause i only want trigger invoke on before model created, so the handle logic is in the `ctx.instance &amp;&amp; ctx.isNewInstance` block. ctx.isNewInstance only support for memory, MongoDB, and MySQL connectors officially, so the next thing i should do is checking whether the couchbase connector support this syntax or not, fortunately it can.</p><h4>create unique model</h4><pre>module.exports = Unique=&gt; {<br>  <strong>&#39;use strict&#39;</strong>;<br>  Unique.createKey = <strong>(</strong>key, type<strong>) </strong>=&gt; {<br>    <strong>return </strong>Unique.<em>create</em><strong>(</strong>{<strong>id</strong>: <strong>`</strong>${type}<strong>:</strong>${key}<strong>`</strong>}<strong>)</strong>;<br>  };<br>};</pre><p>it will add a method createKey to the model, you even can add some restful api use `remoteMethod` to the model when the trigger on. I use the format like : email:example@gmail.com as the key of my unique constraint document.</p><h4>register mixin</h4><ul><li>add the mixin directory(loopback-nosql-unique-mixin) to the middleware.json.</li><li>add the model directory(models) to the model-config.json.</li><li>update the target model which you want put the hook on, add this to the last</li></ul><pre><strong>&quot;mixins&quot;</strong>: {<br>  <strong>&quot;UniqueConstraint&quot;</strong>: {<br>    <strong>&quot;column&quot;</strong>: <strong>&quot;email&quot;<br>  </strong>}<br>}</pre><h3>Conclusion</h3><p>Loopback mixin are used for injecting logic on models, you can apply it on every model you want without edit code inside the model.js. It’s kind of cool things for loopback already support lots of operation hooks, which can make the project more clear and simple.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52a90f21022e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>