<?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 Wattanai Thangsrirojkul on Medium]]></title>
        <description><![CDATA[Stories by Wattanai Thangsrirojkul on Medium]]></description>
        <link>https://medium.com/@wattanai.tha?source=rss-95208f45ced7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*b4F4hpRGlbbdYlCn</url>
            <title>Stories by Wattanai Thangsrirojkul on Medium</title>
            <link>https://medium.com/@wattanai.tha?source=rss-95208f45ced7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 19:05:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wattanai.tha/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[Go Tutorial Series EP.3: ทำ Authorization ด้วย JWT และ Middlewareในภาษา Go]]></title>
            <link>https://medium.com/@wattanai.tha/go-tutorial-series-ep-3-%E0%B8%97%E0%B8%B3-authorization-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-jwt-%E0%B9%81%E0%B8%A5%E0%B8%B0-middleware%E0%B9%83%E0%B8%99%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B2-go-a98e7276e425?source=rss-95208f45ced7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a98e7276e425</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Wattanai Thangsrirojkul]]></dc:creator>
            <pubDate>Thu, 23 Dec 2021 09:51:23 GMT</pubDate>
            <atom:updated>2021-12-23T09:51:23.489Z</atom:updated>
            <content:encoded><![CDATA[<p>จากตอน EP ที่แล้วเราได้ทำการเก็บ Data ของ API เราลง SQLite Database กันเป็นที่เรียบร้อยแล้วด้วย Gorm Library</p><p>ในวันนี้เราจะมาทำการทำ Authorization ด้วย JSON Web Token หรือว่า JWT และใช้ Middleware ใน Gin Framework บนภาษา Go กัน</p><p>สำหรับใครที่ยังไม่เคยเขียน API ด้วยภาษา Go หรือไม่เคยใช้ Gin Framework มาก่อน ผมแนะนำให้ลองอ่านบทความ EP. 1 ของเราที่นี่ก่อนได้เลยครับ (<a href="https://medium.com/@wattanai.tha/go-tutorial-series-ep-1-building-rest-api-with-gin-7c17c7ab1d5b">https://medium.com/@wattanai.tha/go-tutorial-series-ep-1-building-rest-api-with-gin-7c17c7ab1d5b</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*cz2R21FhLqAKJznRLBs3fg.jpeg" /></figure><p>แต่ถ้าพร้อมแล้ว เรามาเริ่มจากการทำ Authorization แบบง่ายๆ กันก่อนเลยดีกว่า โดยเริ่มจากใน listBooksHandler ของเราเช่นเดิม</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42ee41d332fa9c9dfc6d54dd585a81c2/href">https://medium.com/media/42ee41d332fa9c9dfc6d54dd585a81c2/href</a></iframe><p>เราได้เพิ่ม Logic เกี่ยวกับการทำ Authorization เข้ามาในบรรทัดที่ 2 ถึงบรรทัดที่ 9 โดยเริ่มจากดึง Token ออกมาจาก Header ที่ชื่อ Authorization ใน HTTP Request ด้วยคำสั่ง c.Request.Header.Get(&quot;Authorization&quot;)</p><p>ต่อมาเราทำการตัดมาเฉพาะส่วนที่เป็น token จริงๆ โดยการตัดคำว่า Bearer ออก (เนื่องจากว่าหน้าตาของ Token จะเป็น Bearer MY_TOKEN_STRING )</p><p>หลังจากที่เราได้ Token มาแล้ว เราก็ทำการเช็ค token ว่าเป็น token ที่ถูกต้องหรือไม่ด้วยฟังก์ชัน validateToken ซึ่งจะเป็นฟังก์ชันที่เราจะมา implement กันต่อจากนี้ ซึ่งเมื่อฟังก์ชัน validateToken ของเรามี error เกิดขึ้น เราก็จะทำการส่ง status 401 Unauthorized กลับไปให้กับ client ของเรา</p><p>ต่อจากนั้นเราลองมา implement ฟังก์ชัน validateToken แบบง่ายๆ กันดูก่อน</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edea2b295dfcd9f0c8877245790cca77/href">https://medium.com/media/edea2b295dfcd9f0c8877245790cca77/href</a></iframe><p>โค้ดข้างบนคือการเช็ค token แบบง่ายๆ เลยก็คือแค่ส่งเข้ามาก็ถือว่า valid ไม่ว่า token จะเป็นอะไรก็ตาม</p><p>และเราก็มาลองทดสอบ Request กันแบบง่ายๆ ด้วย REST Client ของเรากันเหมือนเดิม โดยที่เราจะยังไม่ได้ใส่ Authorization Header เข้าไปก่อน</p><pre>GET <a href="http://localhost:8080/books">http://localhost:8080/books</a></pre><p>ผลลัพธ์ที่เราได้ก็จะเป็นแบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*T2AXLtjbP8EkOwG1kSItgw.png" /></figure><p>ซึ่งผลลัพธ์ก็จะเป็นตามที่คาดนั่นก็คือเราจะได้ status 401 Unauthorized เพราะว่าเราไม่ได้ส่ง Token ให้กับ Server ของเรา</p><p>ทีนี้เรามาลองยิง request กันอีกรอบ แต่คราวนี้เราจะส่ง Token เข้าไปด้วยแบบนี้</p><pre>GET <a href="http://localhost:8080/books">http://localhost:8080/books</a><br>Authorization: Bearer abcdefghijk</pre><p>ผลลัพธ์ที่ได้ก็จะเป็นแบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZjDf9uOyM9VOjalAOez6g.png" /></figure><p>ซึ่งเราก็จะสามารถเข้าถึงข้อมูลของ API ได้ตามปกติเหมือนก่อนหน้านี้ที่เราเคยทดสอบ API ไว้ใน EP ก่อนๆ</p><p>ทีนี้ถ้าสมมติว่าเราอยากจะนำ Logic นี้ไปใช้กับ route อื่นๆ อย่างเช่น POST และ DELETE ด้วย เราอาจจะสามารถทำได้แบบนี้</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8f5bf406db0f974f8f9045f02172929/href">https://medium.com/media/c8f5bf406db0f974f8f9045f02172929/href</a></iframe><p>ซึ่งสังเกตว่า เราจะต้องมีโค้ดการเช็ค Token อยู่ตามทุก Route ของเราเลย ซึ่งทำให้มี Duplicated Code จำนวนมากตามจำนวน Handler ที่เรามีเลย ซึ่งจะทำให้มีปัญหาการ Maintain โค้ดต่อในอนาคต เพราะถ้าหากต้องการที่จะแก้ Logic Authorization อันนี้ เราก็จะต้องมาไล่แก้กับทุกๆ Handler</p><p>ซึ่งปัญหานี้เราสามารถแก้ได้ด้วยการใช้ Middleware</p><h3>รู้จักกับ Middleware</h3><p>ตัว Middleware ใน Gin Framework นั้นถูกสร้างมาเพื่อให้มีการใส่โค้ดบางอย่างสำหรับหลายๆ route ที่เราต้องการได้ เพื่อแก้ปัญหาความซ้ำซ้อนของโค้ดอย่างแบบเมื่อกี้นี้เราเจอกัน</p><p>ทีนี้เราลองมา Implement ตัว Middleware ของเรากันดูเลยดีกว่า</p><p>โดยเริ่มจากการแยก Logic ของการเช็ค Authorization Token มาเป็น Middleware Function ก่อนแบบนี้</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ac694d9359436e74126ad9a3a5350d6/href">https://medium.com/media/8ac694d9359436e74126ad9a3a5350d6/href</a></iframe><p>หลังจากนั้นก็ทำการสร้าง route group ใน main function และเปลี่ยนการ register route เดิมมาใช้ route group แทนแบบนี้ (บรรทัดที่ 14 ถึง 18)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d5ca89655347cd348cdb23448f8a62b/href">https://medium.com/media/0d5ca89655347cd348cdb23448f8a62b/href</a></iframe><p>ทีนี้เราก็สามารถที่จะทำ Logic การ Authorization ไว้ในที่เดียวใน authorizationMiddleware เรียบร้อย ซึ่งทำให้เราสามารถ Maintain โค้ดของเราได้ง่ายขึ้นมากๆ เพราะ Logic จะถูกเก็บไว้อยู่ในที่เดียวใน Middleware</p><h3>สร้าง Route เพื่อ Generate Token</h3><p>โดยปกติแล้ว การทำ Authorization นั้น จะต้องมี route เพื่อที่จะ Generate Token ให้กับ Client เพื่อที่ให้ Client สามารถ Access เข้า API ต่างๆ ซึ่ง route นั้นมักจะเป็น route POST /login (ซึ่งใน Tutorial นี้เราจะทำ Route นี้แบบง่ายๆ โดยที่จะไม่ได้มีการเช็ค Logic เรื่องการ Login แต่จะเน้นเรื่อง Middleware และ JWT เป็นหลัก)</p><p>โดยเรามาเริ่มการสร้าง Route POST /login</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9b125b654723e860306fe46bf68f2e3/href">https://medium.com/media/d9b125b654723e860306fe46bf68f2e3/href</a></iframe><p>และก็ทำการ Register Route Login บน router แบบปกติที่เราทำกันใน main function (บรรทัดที่ 14)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c42c2936c81092382829a68badebaccd/href">https://medium.com/media/c42c2936c81092382829a68badebaccd/href</a></iframe><p>และเราก็ทำการเปลี่ยน Logic ในฟังก์ชัน validateToken ของเราเป็นแบบนี้แทน เพื่อให้สอดคล้องกันกับ loginHandler ที่เราสร้างขึ้นเมื่อกี้นี้</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0c5c80e27b7560d47d0689b79930057/href">https://medium.com/media/b0c5c80e27b7560d47d0689b79930057/href</a></iframe><p>และเราลองทดสอบกันเช่นเดิม โดยเริ่มจาก Login Route เพื่อเอา Token มาก่อน</p><pre>POST <a href="http://localhost:8080/login">http://localhost:8080/login</a></pre><p>ซึ่งเราก็จะได้ Token ออกมาแบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*AcXq3HQJHNKQL7_NU1XuFQ.png" /></figure><p>และนำ Token ที่ได้มาใช้ในการเข้าถึง API โดยใส่เข้าไปใน Authorization Header</p><pre>GET <a href="http://localhost:8080/books">http://localhost:8080/books</a><br>Authorization: Bearer ACCESS_TOKEN</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LCiiZuTlAdmnmWsc-eEiUQ.png" /></figure><p>ซึ่งถ้าเราลองเปลี่ยน Token เป็นแบบอื่นๆ ดู</p><pre>GET <a href="http://localhost:8080/books">http://localhost:8080/books</a><br>Authorization: Bearer ANOTHER_TOKEN</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*_DICg-BqgtfsVSWVJsWxoQ.png" /></figure><p>ก็จะเป็น 401 Unauthorized ตามที่เราคาดไว้</p><p>แต่ว่าการใช้ Token แบบง่ายๆ ที่เราทำกันนี้ จะมีจุดอ่อนเรื่องของการที่อาจจะมี Third Party ที่มีเจตนาไม่ดี เข้ามาปลอมแปลงตัว Token มาเพื่อที่จะโจมตีระบบของเราได้ และ Server ก็จะถูกหลอกได้ง่ายๆ เพราะ Server ไม่รู้ว่า Token นั้นเป็น Token จริงๆ ที่ Server นี้เป็นคนสร้างหรือไม่ เพราะไม่ได้มีหลักฐานอะไรเป็นตัวบอกว่า Token นี้ถูกสร้างโดย Server นี้</p><p>ซึ่งถ้าเรามีสิ่งที่เป็นเหมือนลายเซ็นของ Server แล้วเราสามารถ “เซ็น” ลายเซ็นเหล่านี้ลงบน Token นี้ได้เพื่อที่เราจะสามารถรู้ได้ว่า Token นี้เป็นของ Server เราจริงๆ ก็น่าจะดี และหนึ่งในวิธีการทำสิ่งนี้ก็คือการทำ JWT หรือ JSON Web Token นั่นเอง</p><h3>ใช้ JWT ในการทำ Authorization Token</h3><p>JSON Web Token หรือ JWT เป็นหนึ่งรูปแบบของ Token ที่เรานำมาใช้ในการเก็บข้อมูลในการส่งเพื่อทำการ Authentication และ Authorization<br>(สำหรับคนที่ยังไม่รู้จักว่า JWT คืออะไร ใช้งานยังไง ผมแนะนำให้ศึกษาเพิ่มเติมเกี่ยวกับ JWT ได้ที่นี่เลยครับ <a href="https://jwt.io/introduction">https://jwt.io/introduction</a>)</p><p>ซึ่งในภาษา Go เองก็มี library เกี่ยวกับการทำ JWT อยู่ใน Repository <a href="https://github.com/golang-jwt/jwt">https://github.com/golang-jwt/jwt</a></p><p>โดยเราจะแก้ loginHandler ของเราให้ Generate ตัว JWT Token เป็นแบบนี้</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a7a0d3300532ace310aaa901d65dad7/href">https://medium.com/media/1a7a0d3300532ace310aaa901d65dad7/href</a></iframe><p>ซึ่งในโค้ดนี้ เราจะสร้าง token ด้วยคำสั่ง jwt.NewWithClaims และทำการระบุ signing algorithm ของเราเข้าไป พร้อมกับการใส่ Claim เข้าไป ซึ่งในทีนี้เราจะใส่เพียงแค่เวลาที่หมดอายุของ Token นี้</p><p>หลังจากนั้นเราก็จะทำการ “เซ็น” ด้วยลายเซ็นหรือ Signature ของ Server เรา (ซึ่ง Signature นี้จะต้องเก็บไว้เป็นความลับ ไม่ควรมีใครรู้) ซึ่งในทีนี้เราจะใช้เป็น string (&quot;MySignature&quot;) ที่แปลงเป็น []byte</p><p>และถ้าไม่ได้มี error อะไรจากการที่ทำการ sign signature นั้น เราก็สามารถที่จะคืน token ของเรากลับไปได้ตามปกติ</p><p>ทีนี้เราลองมาเทส Route Login เพื่อดู Token ของเรากันใหม่ดีกว่า</p><pre>POST <a href="http://localhost:8080/books">http://localhost:8080/</a>login</pre><p>ผลลัพธ์ที่ได้ก็จะเป็นแบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gdSSurGTo5tzgRCmHne0fA.png" /></figure><p>เราก็จะได้ JSON Web Token ที่ถูก Generate ออกมาเรียบร้อย</p><p>ซึ่งถ้าเรานำ Token อันนี้ไปลองใส่ดูใน <a href="https://jwt.io/">https://jwt.io/</a> ดูก็จะสามารถเห็นข้อมูลต่างๆ ที่เราสร้างมาไว้กันเมื่อกี้นี้ได้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_taXGPcJ7W5zAaCEUkqDyw.png" /></figure><p>ขั้นตอนต่อไปคือเราจะไปแก้ Logic การตรวจสอบ token ที่ฟังก์ชัน validateToken</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64f1988019702569c1e207386700912b/href">https://medium.com/media/64f1988019702569c1e207386700912b/href</a></iframe><p>เราสามารถอ่าน token ได้ด้วยคำสั่ง jwt.Parse โดยเราใส่ token เข้าไป และ function ที่เอาไว้ return signature ที่เราทำการ sign ตัว JWT ไว้ ซึ่งนั้นก็คือ []byte(&quot;MySignature&quot;) นั่นเอง</p><p>นอกจากนี้ภายใน function เราก็มีการเช็คว่า signing method นั้นตรงกับที่เราได้ทำการ signed ไว้ตอนแรกหรือไม่ ซึ่งถ้าไม่ตรงเราก็จะทำการคืนค่า error กลับไป</p><p>เมื่อเสร็จเรียบร้อยเราก็ทำการทดสอบ API ของเราด้วย JWT ที่เรา Generate ออกมากันเมื่อกี้นี้</p><pre>GET <a href="http://localhost:8080/books">http://localhost:8080/books</a><br>Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDAxNjU0MTZ9.fInd5mOn7nd92-fV30oLTatx13Cun3TeceiY6r0A2E8</pre><p>ผลลัพธ์ที่เราได้ก็จะเป็นแบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7xprKLwYhKNJcGImxHX_w.png" /></figure><p>ซึ่งตรงนี้ถ้าหากว่าใครเกิดเจอว่าขึ้นเป็น 401 Unauthorized ก็อาจจะเป็นเพราะว่าตัว JWT ที่เรา Generate ขึ้นมาในตอนแรกนั้น ได้หมดอายุหรือ expire ไปแล้ว ซึ่งเราก็สามารถแก้ไขได้ง่ายๆ โดยการ Generate Token อันใหม่ที่ POST /login เช่นเดิม</p><h3>Code ฉบับเต็ม</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd70c98841fed43235a510c57a0701a1/href">https://medium.com/media/fd70c98841fed43235a510c57a0701a1/href</a></iframe><p>เสร็จเรียบร้อย! เท่านี้เราก็สามารถใช้ JWT คู่กับ Middleware ใน Gin Framework ในการทำ Authorization ตัว API ของเราได้เรียบร้อยแล้ว</p><h3>ตอนต่อไปใน Series นี้</h3><p>ใน EP ถัดไปของ Tutorial นี้เราจะมาดูวิธีการ Deploy Go Application ของเราด้วย Docker กัน</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a98e7276e425" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Tutorial Series EP.2: เก็บข้อมูล API ใน Database ด้วย Gorm Library]]></title>
            <link>https://medium.com/@wattanai.tha/go-tutorial-series-ep-2-%E0%B9%80%E0%B8%81%E0%B9%87%E0%B8%9A%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B8%A1%E0%B8%B9%E0%B8%A5-api-%E0%B9%83%E0%B8%99-database-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-gorm-library-ade5b63a29c1?source=rss-95208f45ced7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ade5b63a29c1</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[go-tutorial]]></category>
            <dc:creator><![CDATA[Wattanai Thangsrirojkul]]></dc:creator>
            <pubDate>Wed, 15 Dec 2021 09:03:38 GMT</pubDate>
            <atom:updated>2021-12-15T09:03:38.213Z</atom:updated>
            <content:encoded><![CDATA[<p>ยินดีต้อนรับเข้าสู่ EP ที่ 2 ของ Go Tutorial Series ของเรากันครับ ใน EP ที่แล้ว เราได้ทำการสร้าง API โดยใช้ Gin Framework ขึ้นมากัน โดยเราจะเก็บข้อมูลต่างๆ ของ API ไว้ใน Memory ของ Server ของเรา</p><p>ซึ่งใน EP นี้เราจะมาเรียนรู้วิธีการเก็บข้อมูลเหล่านี้ลงใน Database ด้วย Gorm Library กันครับ โดยเราจะทำการเก็บข้อมูลลงใน SQLite Database ที่เป็น Database ประเภทที่น้ำหนักเบา และใช้งานได้ง่าย เพราะมันจะเก็บข้อมูลเป็นไฟล์ปกติในเครื่องเราเลย (ซึ่งจริงๆ แล้ว Gorm สามารถเอาไปใช้กับ SQL Database ได้เหมือนกันครับไม่ว่าจะเป็น MySQL หรือ PostgresSQL ก็สามารถทำได้เช่นกัน)</p><p>สำหรับคนที่ยังไม่เคยสร้าง REST API ด้วยภาษา Go หรือ Gin Framework มาก่อน ผมแนะนำให้ลองอ่านบทความ EP. 1 ของเราที่นี่ก่อนได้เลยครับ (<a href="https://medium.com/@wattanai.tha/go-tutorial-series-ep-1-building-rest-api-with-gin-7c17c7ab1d5b">https://medium.com/@wattanai.tha/go-tutorial-series-ep-1-building-rest-api-with-gin-7c17c7ab1d5b</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*9Ej41FkDCrNgQp6K5BiK4Q.png" /></figure><h3>เริ่มต้นจากการ Implement แบบง่ายๆ</h3><h4>1. Import Gorm และ SQLite Driver</h4><p>Import Gorm และ SQLite driver ในไฟล์ main.go ของเรา</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19da614d09824545b4c7b7041e8a8319/href">https://medium.com/media/19da614d09824545b4c7b7041e8a8319/href</a></iframe><p>ติดตั้ง dependencies ต่างๆ โดยใช้คำสั่ง</p><pre>go get<br>go mod tidy</pre><h4>2. ทำการ Initialize Gorm ใน main function</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e89a45ea0ee985cfa4ffe193e00c2cc5/href">https://medium.com/media/e89a45ea0ee985cfa4ffe193e00c2cc5/href</a></iframe><p>เราเริ่มต้นจากการสร้าง global variable ที่ชื่อdb เพื่อทำการเก็บ instance จากการสร้าง instance ด้วยคำสั่ง gorm.Open ประกอบกับการใช้ driver ที่สร้างโดยคำสั่ง sqlite.Open ซึ่งเราทำการตั้งชื่อไฟล์ของฐานข้อมูลเราว่า test.db ซึ่งจริงๆ สามารถที่จะตั้งชื่อเป็นอะไรก็ได้ตามต้องการ แค่ให้มีนามสกุลเป็น .db ก็เพียงพอ</p><p>หลังจากนั้นเราใช้คำสั่ง db.AutoMigrate ในการสร้าง Table ต่างๆ ของเราเข้ามา ซึ่งเราจะต้องทำการใส่ pointer ของ Struct Book ของเราเข้าไปเพื่อทำให้ Gorm รู้ได้ว่า Table ต่างๆ นั้นต้องสร้าง Table ชื่ออะไร และมีหน้าตาแบบไหนบ้าง อย่างเช่นในกรณีนี้ ชื่อ Table ก็จะเป็น books ตามชื่อของ Struct Book ของเรานั่นเอง</p><h4>3. ปรับ List Handler ให้มาใช้ Gorm</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de9f7a4ff746bf7a201877774ca5f0b1/href">https://medium.com/media/de9f7a4ff746bf7a201877774ca5f0b1/href</a></iframe><p>เรามาเริ่มต้นจากการเปลี่ยนใน GET handler ของเรา จากเดิมที่เป็น Logic ในการเอาข้อมูล Slice มาเป็น Response เปลี่ยนเป็นการดึงข้อมูลจาก Database แทนโดยใช้คำสั่ง db.Find(&amp;books)</p><p>สังเกตว่าข้อมูลที่เรา query ออกมาจาก database นั้นจะไม่ได้ออกมาจาก return value ของคำสั่ง db.Find แต่ว่ามันจะอยู่ในตัวแปร books ที่เราใส่เป็น argument เข้าไปแทน และในส่วนของ return value จะเป็นข้อมูลต่างๆ เกี่ยวกับการ query แทน เช่น error ต่างๆ ที่อาจจะเกิดขึ้นในตอนที่ query ข้อมูลเป็นต้น</p><p>ซึ่งเมื่อการ query จาก database นั้น อาจจะมีโอกาสที่เกิด error ขึ้นได้ ดังนั้นเราก็จำเป็นที่จะต้องทำการ handle error เหล่านี้ และคืน response เป็น 500 Internal Server Error พร้อมกับ error message ไปยัง client ของเรา</p><h4>4. ปรับ Create Handler ให้มาใช้ Gorm</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/757e079dd5be27481497b1432d430555/href">https://medium.com/media/757e079dd5be27481497b1432d430555/href</a></iframe><p>ต่อมาเรามาทำการเปลี่ยน Logic เดิมใน POST handler เป็นการ insert ข้อมูลของเราเข้าไปใน Database แทนด้วยคำสั่ง db.Create(&amp;book) ซึ่งสังเกตว่าเราจะทำการส่งเป็น pointer เข้าไป เนื่องจากว่าอาจจะมี field บางอย่างที่ตัว database จะสร้างให้เราแบบอัตโนมัติ เช่น auto-increment id หรือ timestamps ต่างๆ</p><h4>5. ปรับ Delete Handler ให้มาใช้ Gorm</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3674c0351bcfa4ddc2ecd908a579ec8c/href">https://medium.com/media/3674c0351bcfa4ddc2ecd908a579ec8c/href</a></iframe><p>และสุดท้าย เรามาปรับ DELETE handler ของเราให้มาใช้คำสั่ง db.Delete ในการลบข้อมูลจาก database แทน ซึ่งเราจะต้องใส่ argument เข้าไป 2 อัน นั่นก็คือ Pointer ของ Struct Book ของเรา และ ID ของ row ที่เราต้องการจะลบเข้าไป</p><p>สาเหตุที่เราต้องใส่ Pointer ของ Struct Book เข้าไปนั้นก็เพราะว่า Gorm จะได้รู้ว่าเรากำลังต้องการจะ Delete ข้อมูลใน Table ไหน ซึ่งในทีนี้ก็คือ Table books ของเรานั่นเอง</p><h4>6. ตอนนี้ไฟล์ main.go จะมีหน้าตาเป็นแบบนี้</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d80e91cb3974f0482fff73d70be250a/href">https://medium.com/media/8d80e91cb3974f0482fff73d70be250a/href</a></iframe><h3>วิธีการทดสอบ API</h3><p>ตอนนี้เราก็สามารถทดสอบ API ของเราเหมือนกับที่เราเคยทำก่อนหน้านี้ด้วย REST API client extension บน VSCode (สามารถดูวิธีการเพิ่มเติมได้ที่ Tutorial EP.1 <a href="https://medium.com/@wattanai.tha/go-tutorial-series-ep-1-building-rest-api-with-gin-7c17c7ab1d5b">https://medium.com/@wattanai.tha/go-tutorial-series-ep-1-building-rest-api-with-gin-7c17c7ab1d5</a>)</p><h3>ปัญหาของการใช้ Global DB Variables</h3><p>ตอนนี้เรากำลังใน global variable ชื่อ db ภายในโค้ดของเรา ซึ่งมันสามารถทำให้เกิดปัญหาในอนาคตได้ เพราะมีโอกาสที่บาง function ที่สามารถเข้ามาเปลี่ยนแปลงตัวแปร db ของเราได้ ซึ่งเราจะมาดูวิธีการแก้ไขปัญหานี้กัน</p><h3>ใช้วิธีการ Dependency Injection</h3><p>หลักการ Dependency Injection เราอาจจะคุ้นเคยกับภาษาในรูปแบบที่เป็น OOP อย่าง Java และมันอาจจะฟังดูยากและซับซ้อน แต่ในความเป็นจริงแล้ว มันเป็นเพียงแค่การเอา dependencies ต่างๆ ที่เราต้องการใช้ ตัวอย่างเช่น ตัวแปร db ของเรานั้น ให้คนอื่นเป็นคนสร้าง และส่งต่อให้กับ class ที่จะใช้ db ผ่าน constructor ได้</p><p>ซึ่งในภาษา Go จะไม่มี class เหมือนกับภาษาอื่นๆ ที่เป็น OOP แต่ว่าเรามีซึ่งที่ใกล้เคียงกันนั่นก็คือ Struct นั่นเอง ซึ่งเราจะทำการสร้าง Handler struct ขึ้นมาเพื่อทำการเก็บตัวแปร dependencies ต่างๆ ของเรา ซึ่งในที่นี้ก็คือ *gorm.DB นั่นเอง และเราก็ทำการเปลี่ยน handler function ของเราเป็น method แทน และสุดท้ายก็สร้าง method สำหรับการสร้าง Handler struct นี้ก็เป็นอันเสร็จ</p><p>พูดแล้วก็ไม่ค่อยเห็นภาพ เรามาดูตัวอย่างการเขียนโค้ดกันเลยดีกว่า!</p><h4>1. สร้าง Handler Struct และฟังก์ชัน newHandler</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c92ce0ad07ae6eda64ffeda10b69d12/href">https://medium.com/media/5c92ce0ad07ae6eda64ffeda10b69d12/href</a></iframe><p>เราจะทำการสร้าง struct ที่ชื่อว่า Handler ขึ้นมาพร้อมกับ function newHandler ของเราที่ทำหน้าที่คล้ายๆ กับ constructor ในภาษา OOP อื่นๆ โดยการจะสร้าง Handler ด้วยnewHandler นั้นจะต้องใช้ dependency อย่าง *gorm.DB</p><h4>2. Make handler function to be method and use the db from Handler</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/784ccb69ee8c7f53fefac95ad6462941/href">https://medium.com/media/784ccb69ee8c7f53fefac95ad6462941/href</a></iframe><p>ต่อมาเราจะทำการเปลี่ยน Handler Function ต่างๆ ก่อนหน้านี่ให้กลายเป็น Method ของ Struct Handler ซึ่งเราสามารถทำได้อย่างง่ายดายโดยการใส่ Receiver (h *Handler) เข้าไปในแต่ละ method แค่นี้เราก็ได้ method มาใช้งานแล้ว</p><p>และเราก็เปลี่ยนจากการที่เราใช้ Global Variable db มาเป็นใช้ Field h.db ใน Struct Handler แทน</p><h4>3. เปลี่ยน main function ให้มาใช้ Handler struct แทน</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09f45655cebb000b70872909e7c87d48/href">https://medium.com/media/09f45655cebb000b70872909e7c87d48/href</a></iframe><p>สุดท้าย เราก็จะมาสร้าง db instance ใน main function และทำการส่ง instance นี้ไปใน newHandler function เพื่อทำการสร้าง Handler ขึ้นมา และเราก็สามารถใช้ method ของ Handler มาแทน function ของเราก่อนหน้านี้ได้เลยตามโค้ดด้านบนนี้</p><h3>สุดท้ายหน้าตาของ Code เราจะเป็นแบบนี้</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a693edf1d14c83ac60b6398bb62da2d/href">https://medium.com/media/2a693edf1d14c83ac60b6398bb62da2d/href</a></iframe><p>เสร็จแล้ว! ที่นี้เราก็สามารถสร้าง REST API โดยเก็บข้อมูลลง Database ด้วย Gorm ได้เรียบร้อยแล้ว</p><h3>ตอนต่อไปใน Series นี้</h3><p>ใน EP ถัดไป เราจะมาลองดูวิธีการทำ Authorization กับ API ของเราโดยการใช้ JSON Web Token (JWT) และ Middleware ของ Gin</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ade5b63a29c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Tutorial Series EP.2: Persisting API Data with Gorm]]></title>
            <link>https://medium.com/@wattanai.tha/go-tutorial-series-ep-2-persisting-api-data-with-gorm-c89103cd266b?source=rss-95208f45ced7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c89103cd266b</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[go-tutorial]]></category>
            <dc:creator><![CDATA[Wattanai Thangsrirojkul]]></dc:creator>
            <pubDate>Wed, 15 Dec 2021 07:03:51 GMT</pubDate>
            <atom:updated>2021-12-15T07:23:34.512Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the episode 2 of our Go Tutorial Series. From the last episode, we create an API with Gin and store our data in the Go Slices in server memory. And today we will learn how to persist our data in the database.</p><p>In this article, we will go through how to use Go database library called Gorm and how to connect it to SQLite (but you can change the driver to be another SQL provider you like)</p><p>If you haven’t see our first episode of building REST API with Gin in this series yet, I recommend checking it out in this link first (<a href="https://medium.com/@wattanai.tha/go-tutorial-series-ep-1-building-rest-api-with-gin-7c17c7ab1d5b">https://medium.com/@wattanai.tha/go-tutorial-series-ep-1-building-rest-api-with-gin-7c17c7ab1d5b</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*9Ej41FkDCrNgQp6K5BiK4Q.png" /></figure><h3>Basic Implementation</h3><h4>1. Import Gorm and SQLite Driver</h4><p>Import Gorm and SQLite driver in your main.go code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19da614d09824545b4c7b7041e8a8319/href">https://medium.com/media/19da614d09824545b4c7b7041e8a8319/href</a></iframe><p>Install dependencies using the command.</p><pre>go get<br>go mod tidy</pre><h4>2. Initialize Gorm in the main function</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e89a45ea0ee985cfa4ffe193e00c2cc5/href">https://medium.com/media/e89a45ea0ee985cfa4ffe193e00c2cc5/href</a></iframe><p>We create a global variable named db and initialize it in main function using the gorm.Open command with the driver sqlite.Open command and Gorm configuration. Also note that the SQLite database filename test.db can be any name you would like.</p><p>After that we use the db.AutoMigrate method and passing the pointer of empty Book struct to tell Gorm to automatically create table and fields correctly (the table will be named books according to the struct name).</p><h4>3. Implement List Handler to use Gorm</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de9f7a4ff746bf7a201877774ca5f0b1/href">https://medium.com/media/de9f7a4ff746bf7a201877774ca5f0b1/href</a></iframe><p>Now we start from rewriting our GET handler for listing books by replacing previous logic to be querying from the database instead using db.Find(&amp;books) command.</p><p>Note that the rows queried by the Gorm will be store on the books slice that we passed into the method. And the result variable will have only other information like errors of query (not the rows of book data).</p><p>We also have to handle the error in case of database query errors occurring by returning the 500 Internal Server Error to the client with the error message.</p><h4>4. Implement Create Handler to use Gorm</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/757e079dd5be27481497b1432d430555/href">https://medium.com/media/757e079dd5be27481497b1432d430555/href</a></iframe><p>Next we will replace the old logic in the POST handler to insert the book data into our database using the db.Create(&amp;book) command. This time we also passing the pointer of book to the method in case we have some autogenerated field by the database (e.g. auto-increment id, timestamps, etc.).</p><h4>5. Implement Delete Handler to use Gorm</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3674c0351bcfa4ddc2ecd908a579ec8c/href">https://medium.com/media/3674c0351bcfa4ddc2ecd908a579ec8c/href</a></iframe><p>Lastly, we reimplement our DELETE handler with our database logic by using the db.Delete method to delete our book.</p><p>Note that in the db.Delete method we have to pass the pointer of empty struct of Book and the id that we want to delete. The reason for passing the first argument is that we need to tell Gorm what table we want to run the delete query, which in this case is our books table.</p><h4>6. Now the main.go file will look like this</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d80e91cb3974f0482fff73d70be250a/href">https://medium.com/media/8d80e91cb3974f0482fff73d70be250a/href</a></iframe><h3>Testing the API</h3><p>We can now test the new implementation of our API like before using the REST API client extension in VSCode (you can learn more about how to test the API in our first episode here <a href="https://medium.com/@wattanai.tha/go-tutorial-series-ep-1-building-rest-api-with-gin-7c17c7ab1d5b">https://medium.com/@wattanai.tha/go-tutorial-series-ep-1-building-rest-api-with-gin-7c17c7ab1d5b</a>)</p><h3>Global DB Variables!</h3><p>Right now we are using the global db variables in our code, which is not optimal because there could be some possibility that some method will mutate the db instance. Let’s see how can we fix this.</p><h3>Implementing Handler Pattern</h3><p>We wil create a Handler struct to store our dependencies which is our *gorm.DB in this case. And we will make our handler function to be struct method instead. Not sure how it works? Let’s see the code!</p><h4>1. Create Handler Struct and newHandler function</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c92ce0ad07ae6eda64ffeda10b69d12/href">https://medium.com/media/5c92ce0ad07ae6eda64ffeda10b69d12/href</a></iframe><p>We create the struct called Handler with our newHandler method for creating the Handler by passing our required dependency *gorm.DB</p><h4>2. Make handler function to be method and use the db from Handler</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/784ccb69ee8c7f53fefac95ad6462941/href">https://medium.com/media/784ccb69ee8c7f53fefac95ad6462941/href</a></iframe><p>Now we can add the method receiver of *Handler to our previous handler function and replacing the global variable db to be a field of Handler struct h.db instead.</p><h4>3. Edit the main function use Handler struct instead</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09f45655cebb000b70872909e7c87d48/href">https://medium.com/media/09f45655cebb000b70872909e7c87d48/href</a></iframe><p>Lastly, we need to create and initialize the db instance like before and pass it to our Handler struct that we just implemented. And replace the previous handler function to use the handler method instead.</p><h3>The Final Code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a693edf1d14c83ac60b6398bb62da2d/href">https://medium.com/media/2a693edf1d14c83ac60b6398bb62da2d/href</a></iframe><p>Done! We can now have our REST API with data persistence using Gorm.</p><h3>Coming up next in the Series</h3><p>In the next article, we will explore how we can add authorization to our API using JWT and Gin middleware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c89103cd266b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Tutorial Series EP.1: สร้าง REST API ด้วย Gin Framework]]></title>
            <link>https://medium.com/@wattanai.tha/go-tutorial-series-ep-1-%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87-rest-api-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-gin-framework-64194c39d6e4?source=rss-95208f45ced7------2</link>
            <guid isPermaLink="false">https://medium.com/p/64194c39d6e4</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Wattanai Thangsrirojkul]]></dc:creator>
            <pubDate>Mon, 13 Dec 2021 08:05:13 GMT</pubDate>
            <atom:updated>2021-12-13T09:41:52.356Z</atom:updated>
            <content:encoded><![CDATA[<p>ยินดีต้อนรับเข้าสู่ Go Tutorial Series ของผมนะครับ ซึ่งใน Series นี้เราจะมาใช้ภาษา Go ในการทำ Web Service ซึ่งเริ่มตั้งแต่การทำ REST API เบื้องต้น, การเชื่อมต่อกับ Database, การทำ Authorization และการ Deploy</p><p>สำหรับใน EP นี้ เราจะมาเน้นเรื่องการสร้าง API ด้วย Gin Framework กันครับ (<a href="https://github.com/gin-gonic/gin">https://github.com/gin-gonic/gin</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*HtCjHzGwf6iWNqXu5Cndsg.png" /></figure><p>ในบทความนี้จะเหมาะสำหรับคนที่มีพื้นฐานการเขียนโปรแกรมด้วยภาษาเบื้องต้นมาแล้วนะครับ ซึ่งสำหรับคนที่ยังไม่รู้จักภาษา Go หรือยังไม่เคยเขียนภาษา Go มาก่อนเลย ผมแนะนำให้ลองฝึกภาษา Go แบบเบื้องต้นดูก่อนครับผ่าน Go Tour Official (<a href="https://go.dev/tour/">https://go.dev/tour</a>/)</p><p>และถ้าอยากเรียนภาษา Go แบบแน่นๆ เลย ทาง Skooldio ก็มีคอร์สสอน Go ตั้งแต่พื้นฐานจน Advanced เลยครับ สามารถดูรายละเอียดเพิ่มเติมได้ที่นี่เลยครับ (<a href="https://www.skooldio.com/bundles/the-ultimate-go-series">https://www.skooldio.com/bundles/the-ultimate-go-series</a>)</p><p>และสำหรับคนที่เขียนภาษา Go เบื้องต้นเป็นอยู่แล้ว เราก็มาลุยกันเลยดีกว่าครับ!</p><h3>Prerequisites — ก่อนเริ่ม</h3><p>0. เริ่มต้นจากติดตั้ง Go (ดูวิธีเพิ่มเติมได้ที่ <a href="https://go.dev/doc/install">https://go.dev/doc/install</a>)</p><h3>Project Setup — ขึ้นโปรเจกต์ใหม่</h3><p>1.สร้าง Directory หรือ Folder ใหม่ขึ้นมาด้วการรันคำสั่งใน Command Line</p><pre>mkdir go-rest-api</pre><p>2. รันคำสั่ง go mod init เพื่อสร้างไฟล์ go.mod ในโปรเจกต์ของเรา</p><pre>go mod init example/go-rest-api</pre><p>3. สร้างไฟล์ชื่อ main.go และเขียนโค้ด Hello World ง่ายๆ กันก่อน</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09c5e5739ee019e7398f754931fe7355/href">https://medium.com/media/09c5e5739ee019e7398f754931fe7355/href</a></iframe><p>4. ลองรันโค้ดด้วยคำสั่งใน Command Line</p><pre>go run main.go</pre><p>5. ซึ่งเราก็จะเห็นผลลัพธ์แบบนี้ใน Command Line ของเรา</p><pre>Hello World!</pre><h3>สร้าง API แบบง่ายๆ ด้วย Gin Framework</h3><p>1. เรามาเริ่มจากการเขียน API คืน Response เป็น JSON แบบง่ายๆ</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cfb3c19f43a5b57ece2ee1b9cb2ae1f/href">https://medium.com/media/4cfb3c19f43a5b57ece2ee1b9cb2ae1f/href</a></iframe><p>ในโค้ดนี้เราเริ่มจากการสร้าง router ขึ้นมาด้วยคำสั่ง gin.New() และเราก็ทำการลงทะเบียน Route / ด้วยคำสั่ง r.GET พร้อมใส่ Handler Function และปิดท้ายด้วยการรัน Router ด้วยคำสั่ง r.Run()</p><p>ซึ่งใน Handler Function เราก็จะทำการส่ง Response กลับไปในรูปแบบของ JSON ด้วยคำสั่ง c.JSON เพื่อทำการส่งข้อมูลที่มีหน้าตาแบบนี้กลับไป</p><pre>{<br>    &quot;message&quot;: &quot;Hello World!&quot;<br>}</pre><p>2. เมื่อเขียนโค้ดเสร็จแล้วก็ทำการรันคำสั่งใน Command Line เพื่อติดตั้ง dependencies ต่างๆ ของโปรแกรมนี้</p><pre>go get<br>go mod tidy</pre><p>3. และรันคำสั่งนี้เพื่อทำการเริ่ม API Server ของเราขึ้นมา</p><pre>go run main.go</pre><p>4. เราสามารถทดสอบ API ของเราได้โดยการไปที่ URL http://localhost:8080 เพื่อดูผลลัพธ์ ใน Web Browser ที่เราใช้กันเช่น Chrome, Firefox, และอื่นๆ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*cpIK6oghVJx1skAN9I_Vag.png" /></figure><h3>มาเริ่มสร้าง REST API กันจริงๆ เลยดีกว่า</h3><h4>1. เริ่มจากการสร้าง Struct และ Mock Data ลงใน Slice</h4><p>สร้าง Struct ที่ชื่อ Book และตัวแปร Slice ที่เก็บข้อมูล API ของเรากัน</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/336002af807a1163cfd8a94bb821a6a4/href">https://medium.com/media/336002af807a1163cfd8a94bb821a6a4/href</a></iframe><p>สังเกตว่าในแต่ละ Field ใน Book Struct จะมี Tag `json:&quot;xxx&quot;` ต่อท้ายอยู่ ซึ่ง tag เหล่านี้มีไว้สำหรับให้ Go สามารถรู้ว่าควรจะเชื่อมเอา Field อันไหนใน JSON มาเชื่อมกับ Field ไหนใน Struct ของเรานั่นเอง</p><h4>2. สร้าง GET Endpoint สำหรับข้อมูล Book List</h4><p>เขียนโค้ดสร้าง GET /books Endpoint แบบนี้ได้เลย</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/670d748a331534756ac2ba381cbe9704/href">https://medium.com/media/670d748a331534756ac2ba381cbe9704/href</a></iframe><p>สังเกตว่าเราสามารถใส่ Slice ไปตรงๆ ได้เลย แล้วเราก็จะสามารถคืนค่า Book List ตามที่เราต้องการใน Response ได้เลย</p><p>ซึ่งตอนนี้หน้าตาของ main.go ทั้งไฟล์เลยจะเป็นแบบนี้</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/245059d7258cec6cdce0e635477135a0/href">https://medium.com/media/245059d7258cec6cdce0e635477135a0/href</a></iframe><p>รันโค้ดเพื่อเริ่ม API Server เหมือนเดิม</p><pre>go run main.go</pre><p>ทดสอบ API โดยการใส่ URL http://localhost:8080/books ใน Browser และเราก็จะเห็น Book List ที่เราสร้างไว้แบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xB2FdMyxwJuyxcLjjJMGcA.png" /></figure><h4>3. สร้าง POST Endpoint สำหรับการสร้าง Book</h4><p>มาต่อกันที่ Endpoint POST /albums ตามโค้ดด้านล่างนี้เลย</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a6f175e20aad0d3dcb204f94b7b34ce/href">https://medium.com/media/9a6f175e20aad0d3dcb204f94b7b34ce/href</a></iframe><p>สำหรับ Handler นี้ จะมีเพิ่มเติมในส่วนของการนำ Body ของ Request มาใช้ ผ่านคำสั่ง c.ShouldBindJSON และทำการ Bind ตัวข้อมูลใน Body เข้ากับตัวแปร Struct ที่เราสร้างขึ้นที่ชื่อว่า book</p><p>ซึ่งถ้าหากมี Validation Error ในตอนที่ Bind เราก็ต้องทำจัดการ Error นั้นและส่ง 400 Bad Request พร้อมกับ Error Message กลับไปให้กับผู้ที่ใช้งาน API ของเรา</p><p>พอเสร็จเรียบร้อยเราก็ทำการเพิ่ม Struct Book อันใหม่ของเราเพิ่มเข้าไปใน Slice และคืนค่า Struct Book อันใหม่ของเราให้กับ Client</p><p>ซึ่งตอนนี้หน้าตาของ main.go ทั้งไฟล์เลยจะเป็นแบบนี้</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06afafd9afebbf1143ec35c9649314ad/href">https://medium.com/media/06afafd9afebbf1143ec35c9649314ad/href</a></iframe><p>มาถึงขั้นตอนการทดสอบ API เราเหมือนเดิม แต่ว่าคราวนี้เราไม่สามารถที่จะทดสอบผ่านการเข้า Browser แบบตรงๆ เหมือนก่อนหน้านี้ได้แล้ว เพราะว่าถ้าใส่ URL เข้าไปใน Browser ตรงๆ นั้น มันจะเป็นยิง Request แบบ GET แต่เราต้องการจะทดสอบ แบบ POST</p><p>ซึ่งทำให้เราต้องใช้เครื่องมือเสริมในการทดสอบ POST Request ซึ่งในบทความนี้ ผมเลือกใช้ Tools ที่ชื่อว่า REST Client ซึ่งเป็น Extension ตัวหนึ่งของ VSCode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOWx-Dbav5nPartTWDkoqg.png" /></figure><p>วิธีการใช้ก็คือทำการสร้างไฟล์ test.http แบบนี้เลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*ReOuPLs6Eq6uQ7Wx0FTzdw.png" /></figure><p>และก็สามารถกดปุ่ม Send Request ที่ด้านบนเพื่อทำการทดสอบ API ของเราได้เลย โดยเราจะเริ่มทดสอบจากการ POST และส่ง Body ที่เป็น JSON เพื่อสร้าง Book อันใหม่เข้าไปก่อน ที่ Endpoint POST http://localhost:8080/books</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*SlB3ofNZCtNdnqzL7uSBjQ.png" /></figure><p>ต่อจากนั้นเราก็ทดสอบยิง Request ไปที่ GET http://localhost:8080/books อีกครั้งเพื่อให้มั่นใจว่า Book อันใหม่ของเรานั้นได้ถูกสร้างขึ้นมาเรียบร้อยแล้ว</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTBrULgp4cZqTADYyY1mGg.png" /></figure><p>**ตรงนี้อยากให้โน้ตไว้ครับว่าข้อมูล Book ต่างๆ ของเรานั้น จะเก็บอยู่ใน Memory ซึ่งถ้าหากว่าเราทำการปิด Server ตัวนี้แล้วเปิดใหม่ ข้อมูลทั้งหมดก็จะหายไป เพราะว่าเรายังไม่ได้ทำการบันทึกข้อมูลต่างๆ เหล่านี้ลง Database ที่เป็น Persistence (ซึ่งเราก็จะมาดูวิธีการต่อกับ Database แบบนี้ใน EP ถัดไปของ Tutorial นี้ครับ)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0xyuR9mKtBB_uiKd1Na_Cw.png" /></figure><h4>4. สร้าง DELETE Endpoint เพื่อทำการลบ Book</h4><p>มาถึง Endpoint สุดท้ายของเรา DELETE /albums/:id</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc71dd4929205d29f2f1e2ed504d5566/href">https://medium.com/media/bc71dd4929205d29f2f1e2ed504d5566/href</a></iframe><p>ในครั้งนี้เราจำเป็นต้องใช้ข้อมูลเสริมอีกตัวหนึ่ง นั่นก็คือ Book ID ที่ Client ต้องการจะลบนั่นเอง ซึ่งเราสามารถใช้ Feature ของ Gin ที่เป็น Path Parameters โดยการใช้ :id เข้าไปใน Route ของเรา และก็ทำการเรียกใช้ผ่านคำสั่ง c.Param(&quot;id&quot;) เพื่อดึง Param เข้ามาใช้ในตัวแปรของเรา</p><p>หลังจากที่ได้ ID มาจาก Param มาแล้ว เราก็ทำการเขียน Logic ในการลบ Book ที่มี ID ตรงกับที่ได้รับมาออกจาก Slice ของเรา และพอเสร็จเรียบร้อยก็คืน Status 204 No Content กลับไปก็เป็นอันเสร็จ</p><p>ซึ่งตอนนี้หน้าตาของ main.go ทั้งไฟล์เลยจะเป็นแบบนี้</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/102c36d87aab62f0f790d357dd973402/href">https://medium.com/media/102c36d87aab62f0f790d357dd973402/href</a></iframe><p>และเช่นเดิม เราก็จะมาทดสอบ API ของเรากันโดยเพิ่ม Request DELETE เข้าไปในไฟล์ test.http แบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nlOyZ2e_2G68wNzHl69Vzw.png" /></figure><p>แต่ก่อนที่เราจะยิง DELETE Request เรามาเริ่มจากการยิง GET Request กันก่อนเพื่อดูว่าข้อมูลก่อนหน้าที่เราจะลบนั้น เป็นอย่างไรบ้าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0xyuR9mKtBB_uiKd1Na_Cw.png" /></figure><p>ต่อมาเราก็ทำการยิง DELETE Request ไป จะได้ผลลัพธ์แบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*7o8iI5z4jcyMkYhQijrQUg.png" /></figure><p>และสุดท้ายกลับมายิง GET Request เพื่อดูว่าข้อมูล Book ของเราที่ต้องการจะลบ ได้ถูกลบไปเรียบร้อยแล้วรึเปล่า</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hg_BXyAHZZpZZGVivBynaQ.png" /></figure><h3>มา Refactor โค้ดเรากันเถอะ!</h3><p>เพื่อความง่ายในการอ่านและการ Maintain ของ Code นี้ เราจะทำการแยก Handler ออกมาเป็น Function แยกด้วยตัวมันเองแบบนี้</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/617e6e14196fd332726ae01304a4af80/href">https://medium.com/media/617e6e14196fd332726ae01304a4af80/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f55c827cc35ca4d25ed7df5d844d60f/href">https://medium.com/media/3f55c827cc35ca4d25ed7df5d844d60f/href</a></iframe><p>ปิดท้ายด้วยการย้าย Book Struct และ Slice ลงมาอยู่ด้านล่าง Main Function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e34fec2b8c3187c066d7bdb355f0d441/href">https://medium.com/media/e34fec2b8c3187c066d7bdb355f0d441/href</a></iframe><p>เสร็จเรียบร้อยแล้ว! กับ API Service แบบง่ายๆ ของเราที่สร้างด้วย Gin Framework.</p><h3>The Final Code</h3><p>สุดท้ายหน้าตาของไฟล์ main.go ของเราก็จะเป็นแบบนี้</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1467a0cf139b91f235f485df3bd52c2c/href">https://medium.com/media/1467a0cf139b91f235f485df3bd52c2c/href</a></iframe><h3>ตอนต่อไปใน Series นี้</h3><p>ใน​ EP ถัดไป เราจะมาเรียนรู้การใช้ Database เพื่อทำการเก็บข้อมูลต่างๆ เหล่านี้เพื่อไม่ให้สูญหาย แม้ว่าเราจะปิด Server ไปแล้วก็ตาม โดยการใช้ GORM Library</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64194c39d6e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Tutorial Series EP.1: Building REST API with Gin]]></title>
            <link>https://medium.com/@wattanai.tha/go-tutorial-series-ep-1-building-rest-api-with-gin-7c17c7ab1d5b?source=rss-95208f45ced7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c17c7ab1d5b</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Wattanai Thangsrirojkul]]></dc:creator>
            <pubDate>Fri, 10 Dec 2021 03:56:02 GMT</pubDate>
            <atom:updated>2021-12-10T06:05:24.139Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to our Go tutorial series, which we will go through the practical concept and how-to write a Go Web Service which will cover about REST API, Database, Authorization, and Deployment.</p><p>In this episode, we will focusing on the topic of create API using the Gin Framework (<a href="https://github.com/gin-gonic/gin">https://github.com/gin-gonic/gin</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*HtCjHzGwf6iWNqXu5Cndsg.png" /></figure><p>This tutorial will assume you have some basic Go programming knowledge (e.g. Syntax and Fundamentals Concept). If you don’t know what Go is or how to write basic Go programming, I recommend you to start learning from here first (<a href="https://go.dev/tour/">https://go.dev/tour</a>/) or you can learn from our course at Skooldio. (<a href="https://www.skooldio.com/courses/go-the-fundamentals">https://www.skooldio.com/courses/go-the-fundamentals</a>)</p><h3>Prerequisites</h3><p>0. Install Go (Learn how to install Go here <a href="https://go.dev/doc/install">https://go.dev/doc/install</a>)</p><h3>Project Setup</h3><p>1. Create Project Directory</p><pre>mkdir go-rest-api</pre><p>2. Init the Go Modules</p><pre>go mod init example/go-rest-api</pre><p>3. Create main.go file and write the Basic Hello World Code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09c5e5739ee019e7398f754931fe7355/href">https://medium.com/media/09c5e5739ee019e7398f754931fe7355/href</a></iframe><p>4. Run the code in command line</p><pre>go run main.go</pre><p>5. You should see the output in the command line</p><pre>Hello World!</pre><h3>Basic API with Gin</h3><p>1. Now Starting from implementing Basic API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cfb3c19f43a5b57ece2ee1b9cb2ae1f/href">https://medium.com/media/4cfb3c19f43a5b57ece2ee1b9cb2ae1f/href</a></iframe><p>First we create the router with gin.New(), then we register the route /with method r.GET with our request handler function and lastly we run the router using r.Run()</p><p>In our handler function, we write the response back to the client using c.JSON method to return our JSON {&quot;message&quot;: &quot;Hello World!&quot;}</p><p>2. Install dependencies using the command.</p><pre>go get<br>go mod tidy</pre><p>3. Run the code to start the API server.</p><pre>go run main.go</pre><p>4. Testing the API by entering the URL http://localhost:8080 in your browser and you should see the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*cpIK6oghVJx1skAN9I_Vag.png" /></figure><h3>Implementing the REST API</h3><h4>1. Create our data structure and mock data</h4><p>Add the Book Struct and a Slice of books to store our mock API data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/336002af807a1163cfd8a94bb821a6a4/href">https://medium.com/media/336002af807a1163cfd8a94bb821a6a4/href</a></iframe><p>Note that in the Book struct each field will have a tag `json:&quot;xxx&quot;` following the field declaration. This is for the JSON serialization of the API to make the service know which field in the JSON is linked to which field in the Struct.</p><h4>2. Implement the GET endpoint to list all books.</h4><p>Implement the GET /books endpoint like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/670d748a331534756ac2ba381cbe9704/href">https://medium.com/media/670d748a331534756ac2ba381cbe9704/href</a></iframe><p>Note that we can simply pass the slice that we created to return our books list for the response.</p><p>And the full main.go file will now look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/245059d7258cec6cdce0e635477135a0/href">https://medium.com/media/245059d7258cec6cdce0e635477135a0/href</a></iframe><p>Run the code to start the API server.</p><pre>go run main.go</pre><p>Testing the API by entering the URL http://localhost:8080/books in your browser and you should see our list of books.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xB2FdMyxwJuyxcLjjJMGcA.png" /></figure><h4>3. Implement the POST endpoint to create a book.</h4><p>Then Implement the POST /albums</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a6f175e20aad0d3dcb204f94b7b34ce/href">https://medium.com/media/9a6f175e20aad0d3dcb204f94b7b34ce/href</a></iframe><p>This handler will need to receive the request body in order to create a new book and we do this by using the c.ShouldBindJSON method and passing the pointer &amp;book to it to bind the data body into our struct.</p><p>Also note that the c.ShouldBindJSON will validate request body and return the error if there is any validation problem. And we will handle it to return with 400 Bad Request status and our error message.</p><p>After that we add the new book struct to the slice and then we return the newly created book.</p><p>And the full main.go file will now look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06afafd9afebbf1143ec35c9649314ad/href">https://medium.com/media/06afafd9afebbf1143ec35c9649314ad/href</a></iframe><p>Now we will test the post endpoint but putting the URL in the browser will be the GET request. So we need another tools for testing the POST request.</p><p>There are many alternative tools to do this, but I will use the VSCode Extension called REST Client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOWx-Dbav5nPartTWDkoqg.png" /></figure><p>And then you create a test.http file like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*ReOuPLs6Eq6uQ7Wx0FTzdw.png" /></figure><p>And now you can send the POST request and the result will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*SlB3ofNZCtNdnqzL7uSBjQ.png" /></figure><p>And we test the GET http://localhost:8080/books again using the extension and you should see that the new book was created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTBrULgp4cZqTADYyY1mGg.png" /></figure><p>**Note that the created book will not be persistent, which means that if we restart the API service and run go run main.go again, the created book will be lost. (We will discuss how to persist the data in our next episode of this Tutorial Series)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0xyuR9mKtBB_uiKd1Na_Cw.png" /></figure><h4>4. Implement the DELETE endpoint</h4><p>And the final endpoint DELETE /albums/:id</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc71dd4929205d29f2f1e2ed504d5566/href">https://medium.com/media/bc71dd4929205d29f2f1e2ed504d5566/href</a></iframe><p>This time we have to get the path parameters from the requested URL and we can do this by using the :id in our path and get it in our handler using the c.Param(&quot;id&quot;)</p><p>After that we implement our logic of deleting a book from the slice with book id and then return the 204 No Content http status to the client.</p><p>And the full main.go file will now look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/102c36d87aab62f0f790d357dd973402/href">https://medium.com/media/102c36d87aab62f0f790d357dd973402/href</a></iframe><p>And again, we will test our API to see the result by adding the delete request to our test.http file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nlOyZ2e_2G68wNzHl69Vzw.png" /></figure><p>Run the GET endpoint to see our book list first</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0xyuR9mKtBB_uiKd1Na_Cw.png" /></figure><p>Then run the DELETE endpoint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*7o8iI5z4jcyMkYhQijrQUg.png" /></figure><p>Then run the GET endpoint to check the result again and we will see that the second book was removed from our book list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hg_BXyAHZZpZZGVivBynaQ.png" /></figure><h3>Refactor the code</h3><p>For more code readability, we will extract handler func to its own function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/617e6e14196fd332726ae01304a4af80/href">https://medium.com/media/617e6e14196fd332726ae01304a4af80/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f55c827cc35ca4d25ed7df5d844d60f/href">https://medium.com/media/3f55c827cc35ca4d25ed7df5d844d60f/href</a></iframe><p>And move the Book Struct and Slice to be under the main function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e34fec2b8c3187c066d7bdb355f0d441/href">https://medium.com/media/e34fec2b8c3187c066d7bdb355f0d441/href</a></iframe><p>And Done! Our simple API service with Gin framework.</p><h3>The Final Code</h3><p>And the final main.go file will look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1467a0cf139b91f235f485df3bd52c2c/href">https://medium.com/media/1467a0cf139b91f235f485df3bd52c2c/href</a></iframe><h3>Coming up next in the Series</h3><p>In the next episode we will use database to store all these data using GORM (Database and ORM library for Go).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c17c7ab1d5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NoSQL Cloud Service Benchmarking: DynamoDB vs. Datastore]]></title>
            <link>https://medium.com/@wattanai.tha/nosql-cloud-service-benchmarking-dynamodb-vs-datastore-3f57b6951fb?source=rss-95208f45ced7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f57b6951fb</guid>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Wattanai Thangsrirojkul]]></dc:creator>
            <pubDate>Sat, 01 Dec 2018 07:07:53 GMT</pubDate>
            <atom:updated>2018-12-01T07:31:05.037Z</atom:updated>
            <content:encoded><![CDATA[<p>Many new applications are tending to use more NoSQL databases (such as MongoDB, Cassandra) instead of relational databases (MySQL, PostgreSQL) . NoSQL databases have no schema for their stored data and have no ACID (Atomicity, Consistency, Isolation, Durability) guarantee. As a result, they tend to have more scalability and flexibility which are some of the reasons why NoSQL database became popular recently.</p><p><strong>NoSQL Cloud service<br></strong>Other than self-hosted NoSQL databases stated above, there are also have some NoSQL services like AWS DynamoDB or Google Cloud Datastore which help you manage the NoSQL database setup like auto-scaling.</p><p><strong>Which one should we use?<br></strong>There are many aspects to consider when choosing NoSQL cloud services such as performance, scalability, ease of use, pricing, consistency mode, etc. <br>In this experiment, we will focus on the performance of 2 NoSQL cloud services which are AWS DynamoDB and Google Cloud Datastore.</p><p><strong>Overall</strong></p><p>In this experiment, we will …</p><ol><li>Benchmark the <strong>average throughput and latency</strong> of both services on different workloads.</li><li>Test on the <strong>free tier</strong> of both NoSQL service.</li><li>Use Iaas service of <strong>both provider </strong>(Google Compute Engine and AWS EC2) as a client to benchmark the NoSQL service.</li><li>Use <a href="https://github.com/brianfrankcooper/YCSB"><strong>YCSB</strong></a> (Yahoo! Cloud System Benchmark) as a library for benchmarking.</li><li>Test for 7 days, each day we will run each workload twice (once by Compute Engine and once by EC2).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*whUvd49QKyNRfRsXGef1Pw.png" /><figcaption>Overall experiment setup diagram</figcaption></figure><p><strong>Metrics<br></strong>We will measure the performance on average throughput and latency for each different workloads.</p><p><strong>Workloads<br></strong>We will use 4 different workload. Every workload will have 1000 operations.</p><ol><li>Workload A: 95% read, 5% update (read mostly)</li><li>Workload B: 50% read, 50% update (balanced)</li><li>Workload C: 5% read, 95% update (write mostly)</li><li>Workload D: 70% read, 15% update, 15% insert (read mostly with insert)</li></ol><p><strong>NoSQL cloud service configuration</strong></p><p><strong>AWS DynamoDb<br></strong>We will set the configuration based on the free tier pricing of DynamoDB which are …</p><ul><li>25 RCU (Read Capacity Unit)</li><li>25 WCU (Write Capacity Unit)</li><li>No auto scaling</li><li>Tokyo region</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/0*pR-FnAesaua8PbP1" /><figcaption>Free tier pricing of DynamoDB</figcaption></figure><p><strong>Google Cloud Datastore</strong></p><p>Because the Datastore free tier does not limit the RCU and WCU and there is no configuration about them, we will use the default configuration and set the region to Tokyo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*veUR3yrHgZxZwe3l" /><figcaption>Free tier pricing of Google Cloud Datastore</figcaption></figure><p><strong>Prepare the benchmarking script</strong></p><p>This script will be run on both Iaas service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NStfzpfJFZvSsh_60csIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/0*QKkHr_gMmn2kgsux" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/0*0x8c_xrUqLfrug49" /></figure><p><strong>EC2 &amp; Compute Engine instances setup</strong></p><p>AWS EC2 setup</p><ul><li>t2.micro</li><li>Tokyo region</li></ul><p>Google Compute Engine setup</p><ul><li>f1.micro</li><li>Tokyo region (ap-northeast)</li></ul><p>For both instances, we will have to</p><ul><li>Set credentials to connect both DynamoDB and Datastore</li><li>Install YCSB</li><li>Schedule crontab to run the script</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*Vy0Y7EuXs-ec9EuwBX3Z1g.png" /><figcaption>Script running schedule</figcaption></figure><p><strong>Results</strong></p><p>For workload A (read mostly), DynamoDB has higher average throughput and lower average latency than the Google Cloud Datastore</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xIV2uBmnoOCXTQUy" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*pVkVB-V_66iObLhU" /></figure><p>For workload B(balanced), DynamoDB has higher average throughput and lower average latency than the Google Cloud Datastore</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*b2SfrdSWYKpdybRj" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/0*xln2sYTkdNKxiV-O" /></figure><p>For workload C(write mostly), DynamoDB has higher average throughput and lower average latency than the Google Cloud Datastore</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/0*c2KwUZaZnlzn19UI" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*3mBJancG6EfCZ5H7" /></figure><p>For workload D(read mostly with insert), DynamoDB has higher average throughput and lower average latency than the Google Cloud Datastore</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*Qz2GPVuYdWzPrXI-" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/0*ekZkeYSOQTHtq0KC" /></figure><p><strong>Conclusion</strong></p><ol><li>DynamoDB has significantly higher average throughput and lower average latency on all different workloads which means DynamoDB free tier has better performance.</li><li>DynamoDB still can be scaled higher if needed while Google Datastore does not have scaling option.</li><li>DynamoDB average throughput and average latency fluctuate on different days and workloads while Google Datastore’s are stable.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f57b6951fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>