<?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 Walter Wu on Medium]]></title>
        <description><![CDATA[Stories by Walter Wu on Medium]]></description>
        <link>https://medium.com/@walterwu-22843?source=rss-7f3c3aa807b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2uUZvflBJMPEGNYn.</url>
            <title>Stories by Walter Wu on Medium</title>
            <link>https://medium.com/@walterwu-22843?source=rss-7f3c3aa807b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 21:16:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@walterwu-22843/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[SNMP 入門]]></title>
            <link>https://walterwu-22843.medium.com/snmp-%E5%85%A5%E9%96%80-42646f2fda8b?source=rss-7f3c3aa807b------2</link>
            <guid isPermaLink="false">https://medium.com/p/42646f2fda8b</guid>
            <category><![CDATA[snmp]]></category>
            <category><![CDATA[mib]]></category>
            <dc:creator><![CDATA[Walter Wu]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 15:31:05 GMT</pubDate>
            <atom:updated>2021-03-15T15:31:05.367Z</atom:updated>
            <content:encoded><![CDATA[<p>SNMP(Simple Network Management Protocol)是用來管理網路設備的一種Protocol，我對它的認識也是從工作接觸開始。雖說是管理網路設備，但是主機、電源供應器、RAID等也都可以透過它來做管理。</p><p>是的!主題是MIB，全名叫做Men In Black(X)，Management information base(O)! 對於一個3th-party的SNMP oid，有MIB可以幫助你去了解它所提供的資訊是什麼，且可以對它做什麼操作。最近我運氣很好剛好做到關於修改MIB的工作，也讓我順便了解一下它的語法，接下來我要交給大家MIB的基礎認識。</p><h3>smilib</h3><h3>安裝</h3><p>在Ubuntu上可先輸入smidump確認是否安裝，如果沒安裝可透過<strong>apt-get install libsmi2ldbl安裝</strong>。(CentOS可以透過yum install libsmi)</p><pre>root@tonylin:~/multi-boot-server# smidump<br>The program &#39;smidump&#39; is currently not installed.  You can install it by typing:<br>apt-get install libsmi2ldbl</pre><h3>使用</h3><p>透過下面兩行指令，就可以將mib file產生出對應的tree與oid列表的檔案。也可以透過這個結果確認MIB是不是你想要的。</p><pre>smidump -f <strong>tree</strong> example1.mib &gt; xtree.txt<br>smidump -f identifiers example1.mib &gt; xiden.txt</pre><p>如果有參考其它檔案要加上p的參數:</p><pre>smidump -f <strong>tree</strong> -p example1.mib example2.mib &gt; xtree.txt<br>smidump -f identifiers -p example1.mib example2.mib &gt; xiden.txt</pre><h3>MIB HelloWorld!</h3><p>一個MIB要怎麼寫，就看你要提供的資料結構是怎樣。舉例來說，如果要提供一個神盾局(S.H.I.E.L.D)的MIB，以下是我的一個簡易範例(xtree):</p><pre>--shieldMIB(1.3.6.1.4.1.135)<br>  |<br>  +-- rwn DisplayString directorName(1)<br>  |  <br>  +--staffObjects(2)<br>  |  |<br>  |  +--heroTable(1)<br>  |     |<br>  |     +--heroEntry(1) [heroIndex]<br>  |        |<br>  |        +-- --- Integer32         heroIndex(1)<br>  |        +-- r-n DisplayString     heroName(2)<br>  |        +-- rwn DisplayString     heroSex(3)<br>  |        +-- rwn Integer32         heroPower(4)<br>  |        +-- rwn DisplayString     wellknown(5)<br>  |<br>  +--enemyObjects(3)</pre><p>(各oid中的名稱必須是小寫開頭)<br>對應的意義即:</p><ul><li>1.3.6.1.4.1.135.1: 局長姓名，Nick Fury。</li><li>1.3.6.1.4.1.135.2: 雇員物件。我有列出來其下的heroTable。</li><li>1.3.6.1.4.1.135.2.1: heroTable，放置各個英雄資訊。</li><li>1.3.6.1.4.1.135.2.1: 英雄資訊。</li><li>1.3.6.1.4.1.135.2.1.1: 識別號。</li><li>1.3.6.1.4.1.135.2.1.2: 姓名，浩克。</li><li>1.3.6.1.4.1.135.2.1.3: 性別，男。</li><li>1.3.6.1.4.1.135.2.1.4: 攻擊力，65535。</li><li>1.3.6.1.4.1.135.2.1.4: 名言，「好弱的神」。</li><li>1.3.6.1.4.1.135.3: 敵人物件。與雇員物件雷同，不贅述。</li></ul><p>像上面的範例我們該怎麼寫MIB呢? 可以先下載我寫好的<a href="http://tonylin.idv.tw/dokuwiki/lib/exe/fetch.php/snmp:snmp:shield-mib.zip">完成品</a>。</p><h3>結構</h3><p>以我觀察smidump的結果，共有node、table、row、column、scala、type、notification、compliance、group這幾個種類。在這個範例中會使用到的有node、table、row、column與scala。<br>彼此的關係如下:</p><ul><li>node &gt; table &gt; row &gt; column，一個node可能會有多個table，table下會有多個row，row下會有多個column。用於重複的屬性，如heroTable。</li><li>node &gt; scala。用於不重複的屬性，如generalName。</li><li>node &gt; node，把node當分支就對了，如staffObjects和enemyObjects。</li></ul><h3>Init MIB</h3><p>一個初始的MIB file就長的像下面這個樣子，ModuleName就是這個MIB名稱；ImportsList就像是import library或package，包含所有會使用到的形態與物件的宣告，基本上也是使用到什麼就匯入什麼；AssignmentsList就是那堆oid結構宣告。</p><pre>ModuleName DEFINITIONS ::= BEGIN<br>?ImportsList?<br>?AssignmentsList?<br>END</pre><p>以這個範例來說，基本的雛形會長這個樣子:</p><pre>SHIELDMIB DEFINITIONS ::= BEGIN<br>IMPORTS<br>	MODULE-IDENTITY,<br>	OBJECT-IDENTITY,<br>        OBJECT-TYPE,<br>	Integer32,<br>	enterprises<br>		FROM SNMPv2-SMI<br>	DisplayString<br>		FROM SNMPv2-TC;</pre><pre>?AssignmentsList?<br>END</pre><p>MODULE-IDENTITY、OBJECT-IDENTITY、OBJECT-TYPE是用來描述結構與節點的；Integer32與DisplayString是會使用到的形態;enterprise代表1.3.6.1.4.1，SHIELDMIB是1.3.6.1.4.1.135，其中135必須與<a href="http://www.iana.org/">IANA</a>註冊，也代表著你的ID，這是用來代表私人企業的意思。這些宣告後都有FROM XXXX，是要告訴smidump這些宣告的來源，你也可以將你寫過的MIB弄進來重複使用。(假如是一個很大的組織，可能都會有類似Common Library的MIB file)透過設定SMIPATH，可以把參考的路徑設定進去。</p><h3>MODULE-IDENTITY</h3><p>一個MIB Module就是需要一個MODULE-IDENTITY的宣告，裡面的內容就是記錄這個MIB Module的資訊。</p><pre>shieldMIB MODULE-IDENTITY<br>    LAST-UPDATED &quot;201208200000Z&quot;<br>    ORGANIZATION &quot;S.H.I.E.L.D&quot;<br>    CONTACT-INFO &quot;shield@shield.gov.us&quot;<br>    DESCRIPTION  &quot;復仇者聯盟&quot;<br>    REVISION     &quot;201005200000Z&quot;<br>    DESCRIPTION  &quot;神盾局創立&quot;<br>    REVISION     &quot;201102140000Z&quot;<br>    DESCRIPTION  &quot;浩克加入&quot;<br>::= { enterprises 135 }</pre><p>依樣畫葫蘆，revision+description是用來描述這個module有做過什麼修改，如果不喜歡也可以在整個MIB file最上方用兩個減號(註解)做說明；::=之後是接OID。</p><h3>OBJECT-IDENTITY</h3><p>OBJECT-IDENTITY又叫branch node，用來做分類。以我們例子而言包含了staffObjects和enemyObjects，它們的oid宣告就是接在shieldMIB之後。</p><pre>staffObjects OBJECT-IDENTIFIER ::= { shieldMIB 2 }<br>enemyObjects OBJECT-IDENTIFIER ::= { shieldMIB 3 }</pre><h3>OBJECT-TYPE</h3><p>OBJECT-TYPE可表示scala、table、row與column。</p><h4>scala</h4><p>oid是接在node下，而且已經是leaf就是scala。以我們範例而言，就是神盾局局長，總不會同時會有兩個局長吧?其中SYNTAX代表著OBJECT-TYPE的型態；MAX-ACCESS代表著存取權限，可以參考<a href="http://www.muonics.com/Docs/MIBSmithy/UserGuide/variations.php#access">這裡</a>；STATUS代表這個oid目前的狀態，可以參考<a href="http://www.muonics.com/Docs/MIBSmithy/UserGuide/objects.php#status">這裡</a>。</p><pre>directorName OBJECT-TYPE<br>    SYNTAX      DisplayString<br>    MAX-ACCESS  read-write<br>    STATUS      current<br>    DESCRIPTION &quot;The director&#39;s name for the S.H.I.E.L.D.&quot;<br>    ::= { shieldMIB 1 }</pre><h4>table&amp;row</h4><p>與scala最大的不同就在於SYNTAX的描述。以我們的範例而言，heroTable是一個table包含多個heroEntry row代表著不同英雄，而heroEntry中又會有個別的column去描述英雄屬性。你可以把HeroEntry(大寫的)當做一種資料結構，裡面就是描述英雄屬性，而heroEntry(小寫的)的型態就是這個結構。而heroTable的SYNTAX就是代表著很多個HeroEntry。另外要注意的是oid，heroEntry一定是在heroTable之下，而heroTable則是在staffObjects之下。</p><pre>heroTable OBJECT-TYPE<br>    SYNTAX      SEQUENCE OF HeroEntry<br>    MAX-ACCESS  not-accessible<br>    STATUS      current<br>    DESCRIPTION<br>        &quot;A table of hero entries.&quot;<br>    ::= { staffObjects 1 }</pre><pre>heroEntry OBJECT-TYPE<br>    SYNTAX        HeroEntry <br>    MAX-ACCESS    not-accessible<br>    STATUS        current<br>    DESCRIPTION<br>        &quot;An entry in the hero table.&quot;<br>    INDEX        { heroIndex }<br>    ::= { heroTable 1 }</pre><pre>HeroEntry ::=<br>    SEQUENCE {<br>        heroIndex      Integer32,<br>        heroName       DisplayString,<br>        heroSex        DisplayString,<br>        heroPower      Integer32,<br>        wellknown      DisplayString<br>    }</pre><h4>column</h4><p>在row下的就是column，這部分寫法與scala大同小異，唯一差別就在於父節點是誰而已。</p><pre>heroIndex      OBJECT-TYPE<br>	SYNTAX	    Integer32 (1..65535)<br>	MAX-ACCESS  not-accessible<br>	STATUS	    current<br>	DESCRIPTION<br>		&quot;The unique value which identifies the hero.&quot;<br>	::= { heroEntry 1 }</pre><pre>heroName       OBJECT-TYPE<br>	SYNTAX	    DisplayString<br>	MAX-ACCESS  read-write<br>	STATUS	    current<br>	DESCRIPTION<br>		&quot;A textual full name assigned to a hero.&quot;<br>	::= { heroEntry 2 }</pre><p>就先大概介紹到這邊摟</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42646f2fda8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[SNMP MIB][protolDirID] 與它的不快樂夥伴]]></title>
            <link>https://walterwu-22843.medium.com/snmp-mib-protoldirid-%E8%88%87%E5%AE%83%E7%9A%84%E4%B8%8D%E5%BF%AB%E6%A8%82%E5%A4%A5%E4%BC%B4-309cf5dc0d89?source=rss-7f3c3aa807b------2</link>
            <guid isPermaLink="false">https://medium.com/p/309cf5dc0d89</guid>
            <category><![CDATA[snmp]]></category>
            <category><![CDATA[mib]]></category>
            <dc:creator><![CDATA[Walter Wu]]></dc:creator>
            <pubDate>Fri, 26 Jul 2019 05:38:11 GMT</pubDate>
            <atom:updated>2019-08-26T03:53:49.585Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>[SNMP MIB][protolDirID][protocolDirParameters] 與它的不快樂夥伴</strong></p><p>為什麼不快樂，因為寫這東西的人沒有人快樂的起來</p><p>首先來介紹一下我在工作上研究了差不多七，八個月的這個東西。它叫簡單網路管理協定(SNMP , Simple Network Management Protocol) 跟網路管理資料庫(MIB , <strong>Men In Black</strong>(X), Management Information Base(O))，剩下的自己估狗吧，估狗的到我就不講了</p><p>今天要講的是protocolDirTable的 Index:</p><p><strong>protocolDirID/protocolDirParameters</strong></p><p>先來看一下protocolDirID定義吧</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxWI_D-PBtkIiPXgpid2fA.png" /><figcaption>恩，什麼都講了，然後什麼都沒解釋</figcaption></figure><p>protocolDirTable is indexed by these two OID (很難用中文講這句)，所以我只好繼續找跟這個table相關的資料，最後找到了這個 <a href="https://tools.ietf.org/html/rfc2895#section-3">https://tools.ietf.org/html/rfc2895#section-3</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtCeqw3EfcKGShagyclr5A.png" /><figcaption>終於有格式了</figcaption></figure><p>雖然我不知道cnt是什麼，但是由上圖可以知道 protocolDirID其實每一個node都有它的意義存在，我們再來看看飯粒(X)範例(O)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*CAooB3_V5qvTKfyWl7oYDw.png" /><figcaption>最常見的http</figcaption></figure><p>從以上大概可以理解到，protocolDirID 就是由一系列的 protocol identifiers 所組成，拿 http來解釋的話，第一個16 就是表示後面會有16位的長度，這就是cnt的意思，前四位表示的base layer identifier。</p><pre>The first layer encapsulation is called the base identifier and it<br>contains optional protocol-function information and the base layer<br>(e.g.  MAC layer) enumeration value used in this protocol identifier.<br><br>The base identifier is encoded as four octets as shown in figure 2.<br><br>             Fig. 2<br>        base-identifier format<br>        +---+---+---+---+<br>        |   |   |   |   |<br>        | f |op1|op2| m |<br>        |   |   |   |   |<br>        +---+---+---+---+ octet<br>        | 1 | 1 | 1 | 1 | count<br><br>The first octet (&#39;f&#39;) is the special function code, found in table<br>4.1.  The next two octets (&#39;op1&#39; and &#39;op2&#39;) are operands for the<br>indicated function. If not used, an operand must be set to zero.  The last octet, &#39;m&#39;, is the enumerated value for a particular base layer encapsulation, found in table 4.2.  All four octets are encoded in network-byte-order.</pre><pre>Table 4.2  Base Layer Encoding Values<br>     --------------------------------------<br><br>           Name          ID<br>           ------------------<br>           ether2        1<br>           llc           2<br>           snap          3<br>           vsnap         4<br>           ianaAssigned  5<br></pre><p>我不想讓這篇文章太長，所以每個Layer的定義都在下面</p><p><a href="https://tools.ietf.org/html/rfc2895#section-4.2">RFC 2895 - Remote Network Monitoring MIB Protocol Identifier Reference</a></p><p>base layer identifier之後呢，就要去找iana的官網來找ip這個protocol的編號了，哪裡找呢，很抱歉我到目前還是沒找到，只知道最後代表IP的identifier是 0.0.8.0 。至於tcp就有辦法在下列網址找到代表的數字6了，and make 0.0.0.6</p><p><a href="https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml">Protocol Numbers</a></p><p>最後我們知道http用的是80這個通訊埠，組成了最後一個0.0.0.80</p><p>看到這邊相信各位對於protocolDirID就有了一個基本的認識了。</p><p>接下來介紹protocolDirParameters，關於這個oid從文件中有找到幾點必須要符合的：</p><pre>1. The protocolDirParameters length MUST be exactly one quarter of the protocolDirID string length. </pre><pre>就是如果前面 protocolDirID 長度是16, protocolDirParameters 的長度就會是16的四分之一, which is 4.</pre><pre>2. There are no suggested protocolDirParameters bits for the base layer. </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnU_0QVuhXbNpO5TGO27rA.png" /><figcaption>RFC2021裡面的定義</figcaption></figure><p>我目前所找到的資料都沒有特別敘述這些 parameter 哪裡來的，從原始定義裡面也可以知道 parameter 也可以是 0</p><p>畢竟這些都是20年前的東西，相關資料有點少，有機會再補充</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=309cf5dc0d89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[this]]></title>
            <link>https://walterwu-22843.medium.com/this-13c2c95a380e?source=rss-7f3c3aa807b------2</link>
            <guid isPermaLink="false">https://medium.com/p/13c2c95a380e</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Walter Wu]]></dc:creator>
            <pubDate>Tue, 17 Apr 2018 01:50:18 GMT</pubDate>
            <atom:updated>2018-04-17T01:50:18.787Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://segmentfault.com/a/1190000007101339">https://segmentfault.com/a/1190000007101339</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13c2c95a380e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Golang] Memory leak while handling huge amount of http request.]]></title>
            <link>https://walterwu-22843.medium.com/golang-memory-leak-while-handling-huge-amount-of-http-request-35cc970cb75e?source=rss-7f3c3aa807b------2</link>
            <guid isPermaLink="false">https://medium.com/p/35cc970cb75e</guid>
            <category><![CDATA[context]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[gorilla]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Walter Wu]]></dc:creator>
            <pubDate>Fri, 13 Apr 2018 07:27:20 GMT</pubDate>
            <atom:updated>2018-04-14T04:01:08.723Z</atom:updated>
            <content:encoded><![CDATA[<p>先講結論，這個耗時近兩週的debug旅程讓我學到的幾件事情</p><ul><li>Always close the request.body</li><li>如何使用 go 的 pprof 工具來調教程式效能</li><li>context原理</li><li>evil global variable</li></ul><p>問題發生的狀況是這樣，我們的一個用go寫的server在收了大量的request 之後(大概是client端10秒送2次，持續了兩到三天左右)，會發生memory leak。</p><p>在一開始還沒用pprof之前，因為了下面這篇文章</p><p><a href="https://hackernoon.com/avoiding-memory-leak-in-golang-api-1843ef45fca8">Avoiding Memory Leak in Golang API | Hacker Noon</a></p><p>我們發現了我們的code並沒有close request.body，改進之後memory的成長速度慢很多，但是始終沒有自己減少。所以我開始使用pprof找問題，使用教學如下</p><p><a href="https://lrita.github.io/2017/05/26/golang-memory-pprof/">golang 内存分析/动态追踪</a></p><p>由於我們用的是gorilla.mux，最方便的方法是另外開一個server來handle/debug這個route path：</p><pre>func attachProfiler() {<br>   go func() {<br>      // import pprof之後，它會自動幫你的server加上一個path &#39;/debug&#39;<br>      log.Println(http.ListenAndServe(&quot;:6060&quot;, nil))<br>   }()<br>}</pre><p>然後把你的server跑起來，就可以在terminal下指令</p><pre># 30-second CPU profile<br>go tool pprof <a href="http://localhost:6060/debug/pprof/profile">http://localhost:6060/debug/pprof/profile</a></pre><pre># heap profile<br>go tool pprof <a href="http://localhost:6060/debug/pprof/heap">http://localhost:6060/debug/pprof/heap</a></pre><pre># goroutine blocking profile<br>go tool pprof http://localhost:6060/debug/pprof/block</pre><p>上面的指令可以進入pprof 的互動模式，這裡需要注意的是，進入pprof之後下的任何指令，都是反映從程式開始，到你進入pprof之後的當下狀態，所以如果要持續觀察的話，你只能退出之後再次進入。</p><p>進入pprof之後下web會幫你產生svg樹狀圖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*G1ITMjko2RuSL5ugXxfFkQ.png" /></figure><p>可以看到很明顯的ReadMIMEHeader()這個佔了很大部分的memory，放心，我也是今天第一次注意到原來有這個header。但是到這邊我基本上了解了，不斷累積的memory是因為處理request的時候，不知道為什麼go的GC沒有把處理完的request所佔用的memory釋放掉，導致memory用量不斷上漲。</p><p>再繼續查資料後我發現了這篇文章</p><p><a href="https://gocn.io/article/340">记一次Go websocket　项目内存泄露排查 + 使用Go pprof定位内存泄露 - Go中国技术社区 - golang</a></p><p>雖然不是最後解法（咦？</p><p>但是還是告訴了我們一件事情：</p><blockquote>他解决了这个内存泄露问题，不是因为go-socket.io的原因，而是因为他使用的一个库用到了context，但是context的值没有清除。直觉告诉我们，很有可能我们也是在使用类似context的时候，数据没有清空。</blockquote><blockquote>然后我全局搜了 context。发现项目中使用了 &lt;github.com/gorilla/context&gt;这个库。并不是我们直接使用，而是在使用&lt;github.com/gorilla/sessions&gt;的时候，使用了&lt;github.com/gorilla/context&gt;。</blockquote><blockquote>有可能是&lt;github.com/gorilla/sessions&gt;的问题。来到&lt;github.com/gorilla/sessions&gt;的主页查看文档，在网页搜索&quot;leak&quot;发现了下面这句:</blockquote><blockquote><em>Important Note: If you aren’t using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory! An easy way to do this is to wrap the top-level mux when calling http.ListenAndServe: http.ListenAndServe(“:8080”, context.ClearHandler(http.DefaultServeMux))</em></blockquote><blockquote>意思是，如果不用我们自家的 &lt;gorilla/mux&gt; &lt;gorilla/sessions&gt; 包会有内存泄露。或者是需要</blockquote><blockquote><em>http.ListenAndServe(“:8080”, context.ClearHandler(http.DefaultServeMux))</em></blockquote><blockquote>這樣使用才有辦法</blockquote><p>2015/12/23加上的Important Note，讓我多走了很多冤枉路。因為我們的server有點像是拼裝車地，用了goji當主要的framework，但是goji沒有提供session，所以又套用了gorilla/sessions，但是我們沒用gorilla/mux，所以我改了一下code，順便去研究了一下context.ClearHandler在幹嘛。相關code如下：</p><pre><strong>var</strong> (     <br>   mutex sync.RWMutex<br>   data  = make(<strong>map</strong>[*http.Request]<strong>map</strong>[<strong>interface</strong>{}]<strong>interface</strong>{})<br>   datat = make(<strong>map</strong>[*http.Request]<strong>int64</strong>) <br>)  </pre><pre><strong>func</strong> <strong>ClearHandler</strong>(h http.Handler) <strong>http</strong>.<strong>Handler</strong> {     <br>   <strong>return</strong> http.HandlerFunc(<br>     <strong>func</strong>(w http.ResponseWriter, r*http.Request) {         <br>      <strong>defer</strong> Clear(r)         <br>      h.ServeHTTP(w, r)     <br>   }) <br>}  <br><em>// Clear removes all values stored for a given request.</em> <br><em>// This is usually called by a handler wrapper to clean up request</em> <em>// variables at the end of a request lifetime. See ClearHandler().</em> </pre><pre><strong>func</strong> <strong>Clear</strong>(r *http.Request) {     <br>     mutex.Lock()     <br>     clear(r)     <br>     mutex.Unlock() <br>}  <em>// clear is Clear without the lock.</em> </pre><pre><strong>func</strong> <strong>clear</strong>(r *http.Request) {     <br>     delete(data, r)     <br>     delete(datat, r) <br>}</pre><p>最後修改code</p><pre>globalR := mux.NewRouter()</pre><pre>srv := &amp;http.Server{<br>  Handler:        context.ClearHandler(globalR),<br>  Addr:           &quot;127.0.0.1:&quot; + os.Getenv(&quot;PORT&quot;),<br>  WriteTimeout:   10 * time.Second,<br>  ReadTimeout:    10 * time.Second,<br>  MaxHeaderBytes: 1 &lt;&lt; 20,<br>}</pre><pre>log.Fatal(srv.ListenAndServe())</pre><p>But</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*6FgI0N85owWxhFrQO5Dt1Q.gif" /></figure><p>直到我找到了下面這篇文章</p><p><a href="https://rover.rocks/golang-memory-leak/">Memory leak in Golang? | Rover&#39;s blog</a></p><p>裡面的這段:</p><blockquote>So we can see 2 things here. The first one is that if we would like to clean our stored request contexts, we had to wrap the request into <strong>ClearHandler</strong>function</blockquote><blockquote>The second thing is that <strong>Clear</strong> itself uses a global mutex to clear the data cached by the Gorilla context. What that means is that this function is a blocking function regarding incoming http requests.</blockquote><blockquote>Both of the functions use <strong>delete</strong> which is a built-in function for deleting maps. Despite using it, we experienced that garbage collector still wasn’t able to collect the data which were allocated here.</blockquote><blockquote>When you start to learn Go, probably one of the first things you learn, is that you don’t have to free memory manually because of the garbage collector. If you still decide to do it, you can write code for it which is not recommended, or you can use the fact that GC frees up memory, when you have no more reference to a given memory segment.</blockquote><blockquote>So after digging more down into the source code of Gorilla, it turned out that this was not the first application producing these kinds of issues while using Gorilla. Therefore the developers being aware of this situation implemented the <a href="https://github.com/gorilla/context/blob/master/context.go#L116"><strong>Purge</strong></a> function, which sounds much cooler than it actually is.</blockquote><p>大意是說：他們發現wrap handler 進去context.ClearHandler也沒有用，但是gorilla的作者有發現這件事情一直在發生，所以寫了一個叫Purge()的function來處理這件事。</p><p>code如下：</p><pre>// Purge removes request data stored for longer than maxAge, <br>// in seconds.<br>// It returns the amount of requests removed.<br>//<br>// If maxAge &lt;= 0, all request data is removed.<br>//<br>// This is only used for sanity check: in case context cleaning was // not properly set some request data can be kept forever, consuming // an increasing amount of memory. In case this is detected, Purge() // must be called periodically until the problem is fixed.</pre><pre>func Purge(maxAge int) int {<br>  mutex.Lock()<br>  count := 0<br>  if maxAge &lt;= 0 {<br>    count = len(data)<br>    data = make(map[*http.Request]map[interface{}]interface{})<br>    datat = make(map[*http.Request]int64)<br>  } else {<br>    min := time.Now().Unix() - int64(maxAge)<br>    for r := range data {<br>      if datat[r] &lt; min {<br>	clear(r)<br>	count++<br>      }<br>    }<br>  }<br>  mutex.Unlock()<br>  return count<br>}</pre><p>最後在開了另一個goroutin來執行這隻function</p><pre>func clearStaleRequest () {<br>  for {<br>    time.Sleep(3 * time.Minute)<br>    context.Purge(45)<br>  }<br>}</pre><p>用postman打request打了一整天，幾萬個request，server佔用的memory都維持在8–10m左右。</p><p>The world has returned calm.</p><p>這都要感謝飛天小女警的幫忙（咦？</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35cc970cb75e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[terminal] 上傳檔案到google drive 然後寄連結到信箱]]></title>
            <link>https://walterwu-22843.medium.com/%E4%B8%8A%E5%82%B3%E6%AA%94%E6%A1%88%E5%88%B0google-drive-%E7%84%B6%E5%BE%8C%E5%AF%84%E9%80%A3%E7%B5%90%E5%88%B0%E4%BF%A1%E7%AE%B1-f93aa23a06cd?source=rss-7f3c3aa807b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f93aa23a06cd</guid>
            <category><![CDATA[google-drive]]></category>
            <dc:creator><![CDATA[Walter Wu]]></dc:creator>
            <pubDate>Sat, 30 Sep 2017 08:37:40 GMT</pubDate>
            <atom:updated>2017-10-26T04:17:45.460Z</atom:updated>
            <content:encoded><![CDATA[<pre>drive push -no-prompt -ignore-conflict -destination $upload_path $file<br>drive share -no-prompt -with-link $upload_path<br>url=`drive url $upload_path`<br>url=”${url/open?/uc?export=download&amp;}”<br>drive share -no-prompt -emails $mailto -message “firmware released at $url” $upload_path</pre><p>2017/10/26 update</p><pre>mailto=&quot;<a href="/service/mailto:hangie921@gmail.com">y</a>ourmail&quot;<br>upload_path=&quot;yourpath&quot;</pre><pre>set -e<br>drive push -no-prompt  -ignore-conflict -destination $upload_path &quot;test1.txt&quot;<br>remotefn=&quot;$upload_path/test1.txt&quot;<br>drive pub $remotefn<br># echo &quot;share&quot;<br># drive share -no-prompt $remotefn<br>url=`drive url $remotefn`<br>url=&quot;${url/open?/uc?export=download&amp;}&quot;<br>drive share -no-prompt -emails $mailto -message &quot;firmware released at $url&quot; $remotefn</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f93aa23a06cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Windows的換行跟linux base的換行]]></title>
            <link>https://walterwu-22843.medium.com/windows%E7%9A%84%E6%8F%9B%E8%A1%8C%E8%B7%9Flinux-base%E7%9A%84%E6%8F%9B%E8%A1%8C-e35b558c2038?source=rss-7f3c3aa807b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e35b558c2038</guid>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Walter Wu]]></dc:creator>
            <pubDate>Sat, 30 Sep 2017 03:55:23 GMT</pubDate>
            <atom:updated>2017-09-30T03:55:23.032Z</atom:updated>
            <content:encoded><![CDATA[<p>回車符號和換行符號產生背景</p><p>關於「回車」（carriage return）和「換行」（line feed）這兩個概念的來歷和區別。</p><p>在計算機還沒有出現之前，有一種叫做電傳打字機（Teletype Model 33）的玩意，每秒鐘可以打10個字符。但是它有一個問題，就是打完一行換行的時候，要用去0.2秒，正好可以打兩個字符。要是在這0.2秒裡面，又有新的字符傳過來，那麼這個字符將丟失。</p><p>於是，研製人員想了個辦法解決這個問題，就是在每行後面加兩個表示結束的字符。一個叫做「回車」，告訴打字機把列印頭定位在左邊界；另一個叫做「換行」，告訴打字機把紙向下移一行。</p><p>這就是「換行」和「回車」的來歷，從它們的英語名字上也可以看出一二。</p><p>後來，計算機發明了，這兩個概念也就被般到了計算機上。那時，存儲器很貴，一些科學家認為在每行結尾加兩個字符太浪費了，加一個就可以。於是，就出現了分歧。</p><p>Unix 系統里，每行結尾只有「&lt;換行&gt;」，即「\n」；Windows系統裡面，每行結尾是「 &lt;回車&gt;&lt;換行&gt;」，即「 \r\n」；Mac系統里，每行結尾是「&lt;回車&gt;」。一個直接後果是，Unix/Mac系統下的文件在Windows里打開的話，所有文字會 變成一行；而Windows里的文件在Unix/Mac下打開的話，在每行的結尾可能會多出一個^M符號</p><p>windows創建的文件是 \r\n結束的， 而linux，mac這種unix類系統是\n結束的。</p><p>所以unix的文本到windows會出現換行丟失（ultraedit這種軟體可以正確識別）； 而反過來就會出現^M的符號了</p><p>Windows 等作業系統用的文本換行符和UNIX/Linux作業系統用的不同，Windows系統下輸入的換行符在UNIX/Linux下不會顯示為「換行」，而是 顯示為 ^M 這個符號（這是Linux等系統下規定的特殊標記，占一個字符大小，不是 ^ 和 M 的組合，列印不出來的）。Linux下很多文本編輯器（命令行）會在顯示這個標記之後，補上一個自己的換行符，以避免內容混亂（只是用於顯示，補充的換行 符不會寫入文件，有專門的命令將Windows換行符替換為Linux換行符）。 UNIX/Linux系統下的換行符在Windows系統的文本編輯器中會被忽略，整個文本會亂成一團。</p><p>windows換行是\r\n，十六進位數值是：0D0A。</p><p>具體的， \r的ascii 碼是：14</p><p>\n的ascii 碼是：10</p><p><em>常用到所以順手記一下，誰叫開發人員大部分是Unix base，但是使用者大部分是Windows呢</em></p><p><em>幫ＱＱ</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e35b558c2038" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[你應該用Git Log來講故事(譯]]></title>
            <link>https://walterwu-22843.medium.com/%E4%BD%A0%E6%87%89%E8%A9%B2%E7%94%A8git-log%E4%BE%86%E8%AC%9B%E6%95%85%E4%BA%8B-%E8%AD%AF-3d078ef6a53e?source=rss-7f3c3aa807b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d078ef6a53e</guid>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Walter Wu]]></dc:creator>
            <pubDate>Sat, 07 Jan 2017 01:57:36 GMT</pubDate>
            <atom:updated>2017-01-07T01:57:36.526Z</atom:updated>
            <content:encoded><![CDATA[<p>原文網址：<a href="https://goo.gl/YR6Mk4"> https://goo.gl/YR6Mk4</a></p><p>你曾經為了找一個很煩人的bug而且你知道最簡單的方式是追蹤上一個版本的發布改動了哪些原始碼，但是bug卻不在這些改動過的地方嗎？</p><p>有很多種方式可以做這件事，一個快速的方式是 git log 然後看看這些commit的訊息，當然前提是，你的commit 訊息告訴你一些有用的東西。</p><p>我們軟體開發者花很多的心思來手刻出好閱讀且有效率的原始碼，但是卻沒有花心思來寫出有用的commit。以下的logs是很常見的：</p><pre>$ git log --format=oneline --abbrev-commit  </pre><pre>5ab4e81 Cleanup <br>66105f6 Updated based on PR comments <br>aecb4de Forgot to add a file <br>63194e8 Tweaked custom pop animation parms <br>344eafd Implement new navigation style <br>43e06b3 Actually make status bar white <br>2e01356 Needs beer <br>aca1ff6 Not working <br>17107ab Fix status bar not being white <br>9c7f5d1 Make status bar white</pre><p>雖然這讀起來可能會很有趣，覺得好像寫原始碼的時候在喝酒，但是當有人在閱讀他的時候就不會很有用。</p><p>一筆名叫”Not working”的commit 要怎麼介紹整個code? 不知道，唯一的方法就是去看整個commit changes</p><p>“Update based on PR comments”又是什麼？是哪個PR? PR要求了神馬？在這個例子中我們光是看commit message還不夠，可能還要下一個pull request才能了解整個大範圍。</p><p>我比較想要看到的則是下面這種</p><pre>$ git log --format=oneline --abbrev-commit  </pre><pre>a6104f6 Extract custom durations in constants <br>63194e8 Tweak custom pop animation params <br>344eafd Implement new navigation style <br>ac5f5d3 Make status bar white</pre><p>這個log 直接告訴你一個故事，而且很好理解。任何一個讀這個log的讀者，像是那個已經忘記原始碼的細節的未來的你，也會在閱讀的時候了解發生了什麼事情。</p><p>如果你還有你的團隊養成了寫有描述性的commit的習慣，你就會增加你的歷史訊息裡面所包含的資訊，也會讓你的歷史訊息更加易懂，要找到你想的資訊也會更容易。</p><p>當每次下commit的時候問你自己，“我在這些檔案中做了哪些改動？”，盡量不要是“加了方法a到類別b”, “從元素y 中移除行為x”….. 這些都是好的commit標語，你可以commit的其他部分提供更多有用的訊息。</p><p>寫有用的commit跟縮小你的每次commit 的改動有關，而且知道如何呈現一個有互動性的rebase可以很有效的幫助歷史訊息看起來簡潔。</p><p><em>Leave the codebase better than you found it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d078ef6a53e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big Endian和Little Endian的比較]]></title>
            <link>https://walterwu-22843.medium.com/big-endian%E5%92%8Clittle-endian%E7%9A%84%E6%AF%94%E8%BC%83-e6ff572372c4?source=rss-7f3c3aa807b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6ff572372c4</guid>
            <dc:creator><![CDATA[Walter Wu]]></dc:creator>
            <pubDate>Mon, 26 Dec 2016 05:27:54 GMT</pubDate>
            <atom:updated>2016-12-26T05:27:54.075Z</atom:updated>
            <content:encoded><![CDATA[<p>endian指的是當物理上的最小單元比邏輯上的最小單元還要更小時，邏輯單元對映到物理單元的排布關係。</p><p>這篇文章將說明 Big Endian 和 Little Endian 的差異，並以一段 C 語言做範例。</p><h3>Big Endian 和 Little Endian 的實例</h3><p>如果你在文件上看到一個雙字組的data，Ex: long MyData=0x12345678，要寫到從0x0000開始的記憶體位址時。</p><ol><li>如果是Big Endian的系統：<br>存到記憶體會變成 0x12 0x34 0x56 0x78，最高位元組在位址最低位元，最低位元組在位址最高位元，依次排列。</li><li>如果是Little Endian的系統：<br>存到記憶體會變成 0x78 0x56 0x34 0x12，最低位元組在最低位元，最高位元組在最高位元，反序排列。</li></ol><p>比較的結果就是這樣：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*sHQPebT0oQUc8OCF5qYFug.png" /></figure><h3>Big Endian 和 Little Endian 的差異</h3><p>以目前常見的CPU為例：</p><ul><li>INTEL X86、DEC VAX 使用 LITTLE-ENDIAN 設計；</li><li>HP、IBM、MOTOROLA 68K 系列使用 BIG-ENDIAN 設計；</li><li>POWERPC 同時支援兩種格式，稱為 BI-ENDIAN。</li></ul><p>另外，以我目前在SID測試的程式testendian.c為例，我必須在以下的三個地方都必須指定Endian，否則即使Build時可以通過，但在計算時就可能會出現問題，因為放入記憶體內的資料可能是反過來的。</p><ol><li>在Compile時<br>就必須先指定是要採用那種Endian，如果不指定，會使用內定值；</li><li>在ToolChain內<br>也必須指定是要採用那種Endian，如果不指定，也會使用內定值；</li><li>在SID內<br>也是由設定來決定Endian，所以在模擬CPU的Configuration內也必須指定是要採用那種Endian。</li></ol><p>參考資料</p><ol><li><a href="http://libai.math.ncu.edu.tw/bcc16/pool/1.33.shtml">為啥叫Big/Little Endian？</a></li><li><a href="http://blog.vckbase.com/smileonce/archive/2005/02/22/3202.aspx">Big-Endian 和 Little-Endian 两者概念的区别</a></li><li><a href="http://libai.math.ncu.edu.tw/bcc16/pool/1.33.shtml">用 C 語言窺探記憶體</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6ff572372c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Internet]集線器(Hub)、交換器(Switch)、IP分享器、路由器(Router)的差別]]></title>
            <link>https://walterwu-22843.medium.com/internet-%E9%9B%86%E7%B7%9A%E5%99%A8-hub-%E4%BA%A4%E6%8F%9B%E5%99%A8-switch-ip%E5%88%86%E4%BA%AB%E5%99%A8-%E8%B7%AF%E7%94%B1%E5%99%A8-router-%E7%9A%84%E5%B7%AE%E5%88%A5-8bc83c503a08?source=rss-7f3c3aa807b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bc83c503a08</guid>
            <category><![CDATA[router]]></category>
            <category><![CDATA[switch]]></category>
            <category><![CDATA[internet]]></category>
            <dc:creator><![CDATA[Walter Wu]]></dc:creator>
            <pubDate>Wed, 14 Dec 2016 16:16:39 GMT</pubDate>
            <atom:updated>2016-12-14T16:16:39.330Z</atom:updated>
            <content:encoded><![CDATA[<p>由於我們公司是作Switch的，所以紀錄一下</p><p>要區分這些產品之前，一定要先知道幾個基本觀念。<br>1.封包：網路上資料的傳輸是以封包的方式傳遞，封包裡面通常含有來源和目的的IP位址，來源和目的的MAC位址，當然還有資料啦。</p><p>2.IP位址：我想這個大家都知道，要上網一定要有IP位址，如果IP位址不夠，那麼就需要IP分享器囉。</p><p>3.MAC位址：這個比較少人知道，每一張網路卡其實都有一個MAC位址，全世界絕對不會有跟你相同的MAC位址的網路卡或設備。</p><ol><li><strong>HUB：</strong><br> 我們稱做集線器，一般而言，HUB有兩大特性，一個就是廣播，一個就是半雙工。</li></ol><p>廣播是指，當A電腦要透過HUB送資料給B電腦的時候，A送出來的資料其實連接在這台HUB上的電腦都會收到，但是只有B電腦會將資料收起來，其他電腦則是將封包丟掉。</p><p>半雙工是指，收資料或送資料不能同時，你一次只能做其中一種。</p><p>由於HUB的這種特性，所以當HUB連接非常多電腦時，網路就會變慢。</p><p><strong>2. Switch：</strong><br>中文叫交換器，和HUB看起來一樣，但實際上差別很大。首先switch並不一直廣播，而且是全雙工的。主要是SWITCH會記錄封包中的MAC位址所以當電腦A傳送資料給電腦B時，其他電腦並不會也收到資料，而且這個時候別的電腦也可以同時互相傳送資料。<br> <br>雖然SWITCH有上述的好處，但是要傳送的資料封包每一個都必須經過SWITCH判斷決定要送往哪一台電腦，所以會有一些延遲，因此有時候電腦數少於五台，用HUB反而比SWITCH快。</p><p><strong>3. IP分享器：</strong><br>這個設備通常會有一個WAN port和1~4個不等的Lan port(其實是Switch)。WAN port一般是接ADSL modem(也就是小烏龜啦)，而Lan port則是接到PC電腦。這個設備主要的功能是NAT，也就是做IP分享的意思，他會將WAN port的真實IP(可以是固定IP或浮動IP)分享給LAN port的電腦使用。</p><p>備註解釋一下NAT功能：</p><p>一般IP分享器LAN port裡的電腦室使用虛擬IP，也就是俗稱的假IP，這個網段通常是192.168.X.X，最常見的是192.168.0.X與192.168.1.X。這個IP網段是保留的網段，在實際網際網路並不能使用。NAT這個功能負責記錄網卡MAC位址與假IP的關係並做轉換。</p><p>舉例來說，假設使用者有兩台PC透過IP分享器上網</p><p>A電腦IP為192.168.0.2，網路卡MAC位址是00046F12301A</p><p>B電腦IP為192.168.0.50，網路卡MAC位址是000879215B09</p><p>當A電腦想要連網站yahoo.com.tw時，A電腦會送出資料給yahoo，而IP分享器會記錄192.168.0.2的MAC是00046F12301A，並把資料內來源IP 192.168.0.2改成WAN port的真實IP，然後送往YAHOO。Yahoo收到以後會依照真實IP位址回傳資料給IP分享器，IP分享器再依照資料內的MAC位址判別出這封包是要給A電腦的，於是把目的IP改成192.168.0.2送往A電腦。</p><p>簡單的說，IP分享器是透過傳送封包內的MAC位址來分辨這個封包資料是要給哪一台電腦的，進而達到分享IP的功能。</p><p>請注意，有些IP分享器會說自己是IP sharing router或者是寬頻Router，但這與實際的Router有一段差距。</p><p><strong>4.Router：</strong><br>中文叫路由器，路由器通常最少會有兩個介面，而這兩個介面分別區隔不同的IP網段。例如IP分享器有WAN和LAN兩種介面，區隔WAN的實際IP與LAN的虛擬IP網段，所以說IP分享器是Router其實並沒有錯誤。不過我們技術人員口中所說的router都是那種超級貴死人，而且兩個介面都是用在真實IP網段的設備。</p><p>好像有點離題了，其實如果你對switch的原理有一點瞭解，那麼其實router有一點像switch，只不過Router是依照封包的目的IP來決定資料是要傳往哪一個介面的哪一個網域。</p><p>以上面IP分享器和AB電腦為例</p><p>假如A要傳資料給內部的電腦，所以當IP分享器收到封包時，發現目的IP是192.168.0.X網段的，於是根本不會把封包往WAN port送，而是會往LAN送。如果A電腦是要上網，那麼目的IP就不是192.168.0.X這個網段的，那麼這個封包就會往WAN送出去然後透過ADSL到網際網路。而ROUTER最主要的工作就是判別收到的IP封包要往哪一個介面送，就是這樣。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bc83c503a08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JS]2017年你最需要學習的JS框架跟主題(純翻譯)]]></title>
            <link>https://walterwu-22843.medium.com/js-2017%E5%B9%B4%E4%BD%A0%E6%9C%80%E9%9C%80%E8%A6%81%E5%AD%B8%E7%BF%92%E7%9A%84js%E6%A1%86%E6%9E%B6%E8%B7%9F%E4%B8%BB%E9%A1%8C-%E7%B4%94%E7%BF%BB%E8%AD%AF-66350840e62c?source=rss-7f3c3aa807b------2</link>
            <guid isPermaLink="false">https://medium.com/p/66350840e62c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Walter Wu]]></dc:creator>
            <pubDate>Mon, 12 Dec 2016 14:20:05 GMT</pubDate>
            <atom:updated>2016-12-12T15:34:12.215Z</atom:updated>
            <content:encoded><![CDATA[<p>原文網址：<a href="https://goo.gl/drUa1H">https://goo.gl/drUa1H</a></p><p>PS: 本文相關Javascript名詞翻譯都使用<a href="http://www.books.com.tw/products/0010542183">犀牛書</a>的翻譯</p><h3><strong><em>Warning：這篇文章很長，End也不會有懶人包。</em></strong></h3><p>JS的受歡迎程度讓它變成了一種科技，一種生態系還有一種Libraries，但是它的多元程度還有它的生態系的活力讓大多數的人相當困擾，到底哪項技術我該關心的呢？</p><p>到底把時間投資在哪項技術會讓我得到最多的利益？哪種技術人員是現在的公司們所需要的，哪種技術是最有成長潛力的？</p><p>哪種技術是你現在最需要知道的？這篇文章概括了介紹你所知道的一切東西，還附上連結。</p><p>記得一件事，如果你還在學著實驗一些code，<a href="http://codepen.io/">Codepen.io</a>會是你的好朋友，如果你還在學習ES6，你可以學著用線上轉譯器<a href="https://babeljs.io/repl/">Babel REPL</a></p><p>這篇文章會是一個很長的清單，但是不要太沮喪。你辦得到的，如果你現在正在看這個清單，而且很煩惱如何利用你所知道的一切來建立一個現代化的應用，請讀<a href="https://medium.com/javascript-scene/why-im-thankful-for-js-fatigue-i-know-you-re-sick-of-those-words-but-this-is-different-296fae0c888f">“Why I’m Thankful for JavaScript Fatigue”</a>，然後下定決心的開始工作吧。</p><h3><strong>建議學習但不是必須的符號＊</strong></h3><p>如題，有些技術嚴格來說只是建議學習的，換句話說，如果你有興趣的話，我會推薦這些技術，或是如果你會需要為了工作而學它。但是不用覺得學習它是一種義務。任何名詞加上*號(ex:”<strong>example*</strong>”)就會是建議學習</p><p>所有沒有加上星號的名詞就是你應該要學的。但是一樣，不需要覺得學習這些東西是一種義務。你必須了解這些名詞是必須要學習的事物，但是你不用成為所有技術的專家。</p><h3><strong>Javascript &amp; DOM的基本</strong></h3><p>當你要開始把JS當飯吃的時候，你應該要把這些JS的基礎掌握得很好:</p><ul><li><strong>內建的方法：<br></strong>學習這些標準的資料型態(特別是矩陣，物件，字串還有數字)</li><li><strong>函式還有</strong><a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976"><strong>純函式</strong></a><strong>(Function &amp; pure functions)：<br></strong>你可能已經覺得你已經掌握函式掌握得很好了，但是JS有一些不為人知的小技巧，而且你需要學習純函式來掌握Functional Programming</li><li><a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36"><strong>閉包</strong></a><strong>(Clourses)：<br></strong>學習Javascript的函式作用域的行為</li><li><strong>回呼(Callbacks)：<br></strong>回呼函式是一隻用來表示其他支函式的結果已經準備好的函式，它說”黑，做好你的工作，做完（到了）叫我（咦?”</li><li><a href="https://developers.google.com/web/fundamentals/getting-started/primers/promises"><strong>Promise</strong></a><strong>(不知道怎麼翻，所以決定不翻)：</strong><br>一個Promise物件是一種處理未來尚未發生的結果的方式，當一個function回傳了一個Promise，你可以利用 .then() 方法在Promise resolve (Promise.resolve是一個靜態方法，所以我就不翻譯了)之後執行你的callback，resolved value會傳進你的callback function中</li></ul><pre>const doSomething = (err) =&gt; new Promise((resolve, reject) =&gt; {<br>  if (err) return reject(err);<br><br>  setTimeout(() =&gt; {<br>    resolve(42);<br>  }, 1000);<br>});<br><br>const log = value =&gt; console.log(value);<br><br>// Using returned promises<br>doSomething().then(<br>  // on resolve:<br>  log, // logs 42<br>  // on reject (not called this time)<br>  log<br>);<br><br>// remember to handle errors!<br>doSomething(new Error(&#39;oops&#39;))<br>  .then(log) // not called this time<br>.catch(log); // logs &#39;Error: oops&#39;</pre><ul><li><a href="https://github.com/mzabriskie/axios"><strong>Ajax &amp; server API calls</strong></a>：<br>大部分有趣的應用程式最終都是需要跟網路溝通的，你應該要知道如何跟API(Application Interface 應用程式介面)溝通</li><li><a href="https://medium.com/javascript-scene/how-to-learn-es6-47d9a1ac2620"><strong>ES6</strong></a>：<br>現在最新版本的JS已經是ES2016了（又叫做ES7)，不過很多開發者都還沒好好的學習ES6</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"><strong>類別</strong></a>：(note: <a href="https://medium.com/javascript-scene/the-two-pillars-of-javascript-ee6f3281e7f3"><strong>Avoid class inheritance</strong></a>. See <a href="https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-9af8de78ccb4">How to Use Classes and Sleep at Night</a>.)</li><li><a href="https://ericelliottjs.com/premium-content/webcast-the-two-pillars-of-js-introduction-to-functional-programming/"><strong>函式型程式設計(Functional Programming)</strong></a>：<br>Functional Programming是由許多數學函式所組成，避免了共用的狀態跟可改變的資料。我上一次見到沒有使用大量的Functional Programming的JS app已經是一年多之前了，是時候要精通這些基礎了。</li><li><a href="https://medium.com/javascript-scene/7-surprising-things-i-learned-writing-a-fibonacci-generator-4886a5c87710"><strong>Generators</strong></a><strong> &amp; </strong><a href="https://medium.com/javascript-scene/the-hidden-power-of-es6-generators-observable-async-flow-control-cfa4c7f31435"><strong>async/await</strong></a>：<br>我個人的意見，這是讓你的非同步程式碼看起來像是同步原始碼的最好的方式，它需要花時間學習，但是你學完之後，會讓你的原始碼更容易閱讀。</li><li><strong>效能: </strong><a href="https://developers.google.com/web/fundamentals/performance/rail"><strong>RAIL</strong></a> — 從這裡開始 <a href="https://developers.google.com/speed/pagespeed/insights/">“PageSpeed Insights”</a> &amp; <a href="https://www.webpagetest.org/">“WebPageTest.org”</a></li><li><a href="https://medium.com/javascript-scene/introduction-to-node-express-90c431f9e6fd#.gl2r6gcnn"><strong>Node &amp; Express</strong></a>：<br>Node讓你在server端使用JS，Express是Node最受歡迎的框架</li><li>Lodash：<br>一個很棒，模組化的JS工具，把funcitonal programming的好處都包了進去，Import the data-last functional modules from lodash/fp.(這句不知道怎麼翻我就放上原文了)</li></ul><h3><strong>工具</strong></h3><ul><li><a href="https://developer.chrome.com/devtools"><strong>Chrome Dev Tools</strong></a><strong>:</strong> <a href="https://developer.chrome.com/devtools#dom-and-styles">DOM inspect</a> &amp; <a href="https://developer.chrome.com/devtools#debugging-javascript">JS debugger</a>:<br>最好的除蟲工具，雖然你可能也會想試試看Firefox的一些很棒的工具</li><li><a href="https://www.npmjs.com/"><strong>npm</strong></a><strong>:<br></strong> 原本是Node.js的套件管理工具，現在已經變成了一套開源的JS套件管理工具</li><li><a href="https://try.github.io/levels/1/challenges/1"><strong>git</strong></a><strong> &amp; </strong><a href="http://github.com/"><strong>GitHub</strong></a><strong>:<br></strong>分散式的版本管理系統，讓你總是可以追朔你的原始碼的改變。</li><li><a href="https://babeljs.io/"><strong>Babel</strong></a><strong>:</strong> <br>用來在一些比較舊的瀏覽器上轉譯你的ES6</li><li><a href="https://webpack.github.io/"><strong>Webpack</strong></a><strong>:</strong> <br>目前最受歡迎的打包工具，當你要創建一些簡單的範例的時候，方便你設定。</li><li><a href="https://atom.io/"><strong>Atom</strong></a><strong>, </strong><a href="https://code.visualstudio.com/d?utm_expid=101350005-35.Eg8306GUR6SersZwpBjURQ.3&amp;utm_referrer=https%3A%2F%2Fwww.google.com%2F"><strong>VSCode</strong></a><strong>, or </strong><a href="https://www.jetbrains.com/webstorm/"><strong>WebStorm</strong></a><strong> + </strong><a href="http://vim.rtorr.com/"><strong>vim</strong></a><strong>:</strong> <br>如果你需要一個編輯器， Atom and VSCode是目前最受歡迎的JS編輯器。Webstorm也是其中之ㄧ。我推薦學習vim，或是至少把相關的小抄(cheat sheet)加入你的瀏覽器書籤，因為早晚你都會需要用它來編輯在伺服器上的檔案，而這是最簡單的方式。vim 被安裝在所有Unix相容的作業系統上，而且利用SSH遠端連線操作起來相當方便。</li><li><a href="http://eslint.org/"><strong>ESLint:</strong></a> <br>提早把語法以及格式錯誤抓出來。排名在Code review跟TDD(Test Driven Development)之後，第三佳的方式讓你減少你原始碼的bug</li><li><a href="https://ternjs.net/"><strong>Tern.js(我沒用過所以我就保持原文了，怕翻錯):</strong></a> Type inference tools for standard JavaScript, and currently my favorite type related tool for JavaScript — no compile step or annotations required. I’ve kicked all the tires, and Tern.js delivers most of the benefits, and virtually none of the costs of using a static type system for JS.</li><li><a href="https://yarnpkg.com/"><strong>Yarn</strong></a><strong>*:</strong> <br>跟npm很像，但是安裝的行為卻是確定性的，而且Yarn看起來比npm還快。</li><li><a href="https://www.typescriptlang.org/"><strong>TypeScript*(一樣沒用過我就不翻譯了):</strong></a> Static types for JavaScript. <em>Completely optional</em> unless you’re learning Angular 2. If you’re not using Angular 2, you should evaluate carefully before choosing TypeScript. I like it a lot and I admire the TypeScript team’s excellent work, but there are tradeoffs you need to know about. <strong>Required reading:</strong> <a href="https://medium.com/javascript-scene/the-shocking-secret-about-static-types-514d39bf30a3">“The Shocking Secret About Static Types”</a> &amp; <a href="https://medium.com/javascript-scene/you-might-not-need-typescript-or-static-types-aa7cb670a77b">“You Might Not Need TypeScript”</a>.</li><li><a href="https://flowtype.org/"><strong>Flow*:</strong></a> Static type checker for JavaScript. See <a href="http://djcordhose.github.io/flow-vs-typescript/flow-typescript-2.html#/">“TypeScript vs Flow”</a> for an impressively informed and objective comparison of the two. Note that I’ve had some difficulty getting Flow to give me good IDE feedback, even using <a href="https://nuclide.io/">Nuclide</a>.</li></ul><h3><strong>React</strong></h3><p><a href="https://facebook.github.io/react/"><strong>React</strong></a> 是一個用來建立使用者介面的框架，由Facebook所創建，它的理念建立在於單向資料流，意思是所有的資料更新循環會是：</p><p>(我也沒用過React所以不確定的我就不亂翻譯了)</p><ol><li>React takes inputs to components as props and conditionally renders DOM updates if data has changed for specific parts of the DOM. Data updates during this phase can’t retrigger the render until the next drawing phase.</li><li>Event handling phase — after the DOM has rendered, React listens for and events, delegating events to a single event listener at the root of its DOM tree (for better performance). You can listen to those events and update data in response.</li><li>Using any changes to the data, the process repeats at 1.</li></ol><p>這是一個跟雙向資料綁定相反的方式，讓DOM的改變直接更新資料(舉例像是Angular 1還有Knockout)。使用雙向綁定的話，如果在DOM渲染過程中DOM又有改變的話(在Angular 1中叫做digest 循環)可能會在這個渲染過程還沒結束前又觸發另一個渲染過程，會讓效能變慢。</p><p>React 並沒有規定資料管理系統，不過Flux是強力推薦的，React的單向資料流借用了Function programming還有immutable data structure的想法，改變了我們對於前端框架結構的想法。</p><p>以下是更多相關資料</p><p>For more on React &amp; Flux architecture, read <a href="https://medium.com/javascript-scene/the-best-way-to-learn-to-code-is-to-code-learn-app-architecture-by-building-apps-7ec029db6e00">“The Best Way to Learn to Code is to Code: Learn App Architecture by Building Apps”</a>.</p><ul><li><a href="https://github.com/facebookincubator/create-react-app"><strong>create-react-app*:</strong></a> 最快開始建立一個React App的方法</li><li><a href="https://github.com/ReactTraining/react-router"><strong>react-router*:</strong></a> 簡單到死的React router</li><li><a href="https://zeit.co/blog/next"><strong>Next.js*:</strong></a> Dead simple Universal render &amp; Routing for Node &amp; React.</li><li><a href="https://github.com/twitter-fabric/velocity-react"><strong>velocity-react*:</strong></a> Animations for React — allows you to use the VMD bookmarklet for interactive visual motion design on your pages.</li></ul><h3>Redux</h3><p><a href="https://github.com/reactjs/redux"><strong>Redux</strong></a> 為你的應用提供了一個交易性(transactional)的，決定性的狀態管理方式。我們呈現了一個action物件來減少現有應用程式的狀態，要知道為什麼它很重要<a href="https://medium.com/javascript-scene/10-tips-for-better-redux-architecture-69250425af44">“10 Tips for Better Redux Architecture.”</a> To get started with Redux, check out the excellent courses by the creator of Redux, <a href="https://medium.com/u/a3a8af6addc1">Dan Abramov</a>:</p><ul><li><a href="https://egghead.io/courses/getting-started-with-redux"><strong>“Getting Started with Redux”</strong></a></li><li><a href="https://egghead.io/courses/building-react-applications-with-idiomatic-redux"><strong>“Building React Applications with Idiomatic Redux”</strong></a></li></ul><p>Redux是必學的</p><p>Redux是必學的</p><p>Redux是必學的</p><p>很重要所以說三次，就算你從來沒過它</p><p>為什麼呢？因為他會讓你練習而且教你使用 <strong>pure functions </strong>的價值，並且教你新的思考 <strong>reducers </strong>的方式，像是用來產生資料叢集的共用的函式 (<strong>general-purpose functions</strong>)並且從這中間提取一些資料。Reducers 是如此的重要以致於 Array.prototype.reduce 被加入到JS的標準中。</p><p>(以下這段很難翻所以我也保留原文)</p><p>Why? Because it will give you lots of practice and teach you the value of using <strong>pure functions</strong> and teach you new ways to think about <strong>reducers</strong>, which are <strong>general-purpose functions</strong> for iterating over collections of data and extracting some value from them. Reducers are so generally useful that Array.prototype.reduce was added to the JS specification.</p><p>Reducers 的重要性遠大於一個陣列，而且學習新的Reducer工作方式是相當有價值的。</p><ul><li><a href="https://github.com/yelouafi/redux-saga"><strong>redux-saga*(沒用過就不翻了):</strong></a> A synchronous-style side-effect library for Redux. Use this to manage I/O (such as handling network requests).</li></ul><h3>Angular 2*</h3><p>(其實我也沒用過，就盡量翻翻看)</p><p><a href="https://angular.io/"><strong>Angular 2</strong></a><strong> </strong>是Google 的超級受歡迎的框架 — Angular 的大成。因為它的瘋狂受歡迎的程度，所以放在你的履歷上會很漂亮 — 不過我還是推薦先學React</p><p>我相當推薦先學React因為</p><ol><li>簡單</li><li>相當受歡迎而且很多工作都需要他(Angular 2 也是)</li></ol><p>因為這些理由，所以我推薦先學React，不過我認為Angular 2 只是個建議學習的選項。如果你對它有強烈愛好，可以交換一下學習順序，任何一個都會讓你覺得受益。</p><p>不管你最後選了什麼，在拋棄它學習另一個之前，請至少專注於使用它六個月到一年，要讓它產生強大的效益需要時間，我想任何的學習都是一樣的。</p><h3>EDIT:你為什麼不列出&lt;你最喜歡的？&gt;</h3><p>有些人問我為何不列出他們最喜歡的框架，其中一個重要的原則是，我認為“這項技術在實際工作上是否有用？”</p><p>是的，這是一個歡迎程度的競賽。不過有機會知道一個框架會開放是當你在考慮你要如何投資你的學習時間的時候一個重要的考慮因素。</p><p>為了回答上面的問題，我找了一些資料。首先是Google Trends。如果你想要重新產生這個Google Trends的圖表，記得要選取by主題而不是by關鍵字。因為部分的字會產生負面結果。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Mg5X-7ZuWh_mnhj16WZzQ.png" /></figure><p>這張圖告訴我們的是這些不同的專案的相關關注程度。如果人們搜尋這些字，很有可能是他們正在探索他們的選項，或是尋找幫助或是技術文件。這是一個相當適合表示相關專案的使用程度的圖表。</p><p>另一個很好的資源是 Indeed.com，它是一個有大量且多樣資源的求職網站。雖然各項技能的受歡迎程度已經漸漸不能表示什麼了，但是他們仍然收集了足量的資料來告訴你現在人們正在用來產生實際專案的框架。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*ZruXZe2HKfu2av8h4WBDfA.png" /></figure><p>要重新產生這個圖表，你可以搜尋framework name in JS然後讓location 這一欄空白，結果就如你所見。</p><p><strong>Angular and React 支配了整個生態圈:甚至沒有可以望其項背的其他選項。 </strong>(jQuery 例外，因為它是被用來應用在所有網站，也包含非app類 — 因為它被幾乎所有 legacy system，包括熱門的CMS系統像是 WordPress)</p><p>你可能會發現Angular 有一個顯著的領先，但是為什麼我推薦React呢？</p><ol><li><a href="https://medium.com/@sachagreif/the-state-of-javascript-front-end-frameworks-1a2d8a61510">More people are interested in learning React than Angular</a></li><li><a href="https://medium.com/@sachagreif/the-state-of-javascript-front-end-frameworks-1a2d8a61510">React significantly leads Angular in user satisfaction</a></li></ol><p>換句話說，React是贏在mindshare還有使用者體驗上。而如果這個趨勢在往後延個一年或一年半，React會非常有機會成為主宰的前端框架。</p><p>Angular 2 有機會翻盤，不過目前React是表現相當的好</p><h3>RxJS*</h3><p>(沒用過，<a href="http://blog.techbridge.cc/2016/05/28/reactive-programming-intro-by-rxjs/">相關資料</a>)</p><p>is a collection of reactive programming utilities for JavaScript. Think of it as Lodash for streams. Reactive programming has officially arrived on the JavaScript scene. The ECMAScript Observables proposal is a stage-1 draft, and RxJS 5+ is the canonical standard implementation.</p><p>如果要使用，別引入整包RxJS，可以分批次使用，讓你的app少了大概200k以上，會讓你的app加快不少。</p><h4>下一個階段</h4><p>Now that you’ve studied up on all this hot tech, read <a href="https://medium.com/javascript-scene/how-to-land-your-first-development-job-in-5-simple-steps-4e9fb73314c">“How to Land Your First Development Job in 5 Simple Steps”</a>.</p><p><a href="https://ericelliottjs.com/product/lifetime-access-pass/">Level up your JavaScript game.</a> If you’re not a member, you’re missing out.</p><blockquote>翻了三個小時，眼睛都快脫窗了。有錯誤請不吝惜指教瞜</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66350840e62c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>