<?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 Pasit Sri-intarasut on Medium]]></title>
        <description><![CDATA[Stories by Pasit Sri-intarasut on Medium]]></description>
        <link>https://medium.com/@ong.pasit?source=rss-1f4ef4ec3d88------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pylOn2vEGJzFlgIGm65KkA.jpeg</url>
            <title>Stories by Pasit Sri-intarasut on Medium</title>
            <link>https://medium.com/@ong.pasit?source=rss-1f4ef4ec3d88------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 02:13:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ong.pasit/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[golang: จัดการ null ใน sql ด้วย และให้มัน return สวยๆด้วย MarshalJSON]]></title>
            <link>https://medium.com/@ong.pasit/golang-%E0%B8%88%E0%B8%B1%E0%B8%94%E0%B8%81%E0%B8%B2%E0%B8%A3-null-%E0%B9%83%E0%B8%99-sql-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-%E0%B9%81%E0%B8%A5%E0%B8%B0%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B8%A1%E0%B8%B1%E0%B8%99-return-%E0%B8%AA%E0%B8%A7%E0%B8%A2%E0%B9%86%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-marshaljson-afa100b33a92?source=rss-1f4ef4ec3d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/afa100b33a92</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[junior-developer]]></category>
            <dc:creator><![CDATA[Pasit Sri-intarasut]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 10:27:42 GMT</pubDate>
            <atom:updated>2023-10-10T10:27:42.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bygvj5CsmKmUNuJX" /><figcaption>Photo by <a href="https://unsplash.com/@zal3wa?utm_source=medium&amp;utm_medium=referral">Damian Zaleski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>สวัสดีครับ หลังจากที่ไม่ได้เขียน block มานาน คราวนี้ผมได้มีโอกาสมาเขียน golang อีกครั้ง โดยจะมาแนะนำวิธีการแก้ปัญหาเมื่อเราดึงข้อมูลใน sql ออกมา แต่ข้อมูลมันเป็น null นี่สิ เราจะสามารถแก้ไขอย่างไรได้บ้าง มาดูกันครับ</p><p>ก่อนอื่นเราจะสร้าง struct ขึ้นมาชื่อว่า SubOptionResponse</p><pre>type Person struct {<br> ID        int     `json:&quot;id&quot;`<br> Name      string  `json:&quot;name&quot; `<br> Age       int `json:&quot;age&quot;`<br>}</pre><p>แน่นอนว่าใช้วิธีนี้จะเกิดปัญหาที่ว่า</p><pre>sql: Scan error on column index 3, name &quot;age&quot;: converting NULL to int is unsupported</pre><p>เนื่องจาก age มีค่าเป็น null และโดย type ของมันคือ int ไม่ support การที่ค่าของมันเป็น null ได้</p><p>## วิธีแรก: ใช้ sql.NullXXX</p><p>ใน library ของ sql นั้นจะมี type ที่เราสามารถใช้เพื่อจัดการ null อยู่แล้วเช่น sql.NullInt64, sql.NullString เป็นต้น</p><p>โดยจะได้หน้าตาประมาณนี้</p><pre>type Person struct {<br> ID        sql.NullInt64   `json:&quot;id&quot;`<br> Name      sql.NullString  `json:&quot;name&quot; `<br> Age       sql.NullInt64   `json:&quot;age&quot;`<br>}</pre><p>แต่หน้าตาของ output ที่ได้จะออกมาแบบนี้</p><pre>{<br>  &quot;id&quot;: {<br>    &quot;Int64&quot;: 5,<br>    &quot;Valid&quot;: true<br>  },<br>  &quot;name&quot;: {<br>      &quot;string&quot;: &quot;good&quot;,<br>      &quot;Valid&quot;: true<br>    },<br>  &quot;age&quot;: {<br>      &quot;Int64&quot;: 0,<br>      &quot;Valid&quot;: false<br>    },<br>}</pre><p>แน่นอนว่ามันไม่สวยเลยถ้าจะต้องส่ง response ด้วยหน้าตาแบบนี้</p><p>## วิธีที่ 2: สร้าง type ขึ้นมาเอง</p><p>เป็นวิธีที่นิยมที่สุด โดยเราจะสร้าง type ขึ้นมาเอง และทำการ implement MarshalJSON เพื่อกำหนดหน้าตาของการ return</p><pre>// NullInt64 is an alias for sql.NullInt64 data type<br>type NullInt64 struct {<br> sql.NullInt64<br>}<br><br>// MarshalJSON for NullInt64<br>func (ni *NullInt64) MarshalJSON() ([]byte, error) {<br> if !ni.Valid {<br>  return []byte(&quot;null&quot;), nil<br> }<br> return json.Marshal(ni.Int64)<br>}<br><br>// NullString is an alias for sql.NullString data type<br>type NullString struct {<br> sql.NullString<br>}<br><br>// MarshalJSON for NullString<br>func (ns *NullString) MarshalJSON() ([]byte, error) {<br> if !ns.Valid {<br>  return []byte(&quot;null&quot;), nil<br> }<br> return json.Marshal(ns.String)<br>}</pre><p>จาก code ด้านบน เราได้ทำการสร้าง type ที่ชื่อว่า NullInt64 และ NullString โดยทั้ง 2 struct นี้จะได้รับคุณสมบัติของ sql.NullInt64 และ sql.NullString ตามลำดับ และทำการ implement MarshalJson โดยทำการ check ว่าหาก type ของเรานั้น valid ให้ทำการส่งค่าจริงๆออกไป แต่หากไม่ valid ให้ส่งเป็น null</p><p>และหน้าตาของ struct Person ของเราจะได้ว่า</p><pre>type Person struct {<br> ID        NullInt64   `json:&quot;id&quot;`<br> Name      NullString  `json:&quot;name&quot; `<br> Age       NullInt64   `json:&quot;age&quot;`<br>}</pre><p>และ response ที่ออกมาคือ</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;name&quot;: &quot;good&quot;,<br>  &quot;age&quot;: null<br>}</pre><p>หวังว่าจะเป็นประโยชน์กับทุกคนไม่มากก็น้อยครับ หากตรงไหนที่ผิดพลาดหรืออยากให้ปรับปรุงให้ดีขึ้นตรงไหนก็สามารถบอกกันได้ครับ</p><p>## reference</p><p><a href="https://medium.com/aubergine-solutions/how-i-handled-null-possible-values-from-database-rows-in-golang-521fb0ee267">https://medium.com/aubergine-solutions/how-i-handled-null-possible-values-from-database-rows-in-golang-521fb0ee267</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afa100b33a92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ทำ integration test ด้วย docker compose]]></title>
            <link>https://medium.com/@ong.pasit/%E0%B8%97%E0%B8%B3-integration-test-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-docker-compose-10637a8fea8a?source=rss-1f4ef4ec3d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/10637a8fea8a</guid>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Pasit Sri-intarasut]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 12:59:39 GMT</pubDate>
            <atom:updated>2023-02-11T13:00:22.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hgfxRmm2ICixa4th" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>ผมเคยติดปัญหาที่ว่าเราจะ test function ที่มีการติดต่อกับ database ได้ยังไง โดยหากเป็น unit test เราอาจจะ mock ข้อมูลของมันได้ แต่เราจะรู้ได้ยังไงว่า function ของเราสามารถติดต่อกับ database ได้</p><p>วิธีที่ว่าคือการสร้าง container ของ database และสร้าง container ของ app เราเพื่อทำการ test โดยใช้ docker compose นั่นเอง</p><pre># Dockerfile.test<br><br>FROM node:19.4.0-buster-slim as development<br>WORKDIR /usr/src/app<br><br>CMD [ &quot;npm&quot;, &quot;test&quot; ]</pre><pre># docker-compose.test.yaml<br><br>version: &#39;3.1&#39;<br><br>services:<br><br>  it_tests:<br>    build:<br>      context: .<br>      dockerfile: ./Dockerfile.test<br>    volumes:<br>      - $PWD:/usr/src/app<br>    environment:<br>      MYSQL_HOST: db<br>      MYSQL_USER: dsy<br>      MYSQL_PASSWORD: 1234<br>      MYSQL_DATABASE: users<br>    depends_on:<br>      db:<br>        condition: service_healthy<br><br>  db:<br>    image: mysql<br>    restart: on-failure<br>    environment:<br>      MYSQL_ROOT_PASSWORD: 1111<br>      MYSQL_USER: dsy<br>      MYSQL_PASSWORD: 1234<br>      MYSQL_DATABASE: users<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;mysqladmin&quot; ,&quot;ping&quot;, &quot;-h&quot;, &quot;localhost&quot;]<br>      timeout: 20s<br>      retries: 5</pre><p>จากที่กล่าวไว้โดยเราจะมี container 2 ตัวคือ it_tests และ db</p><p>โดย it_tests คือ container ที่เก็บ code ของเราไว้โดยทำการ</p><ul><li>volumes folder ของ project ของเราไว้</li><li>depends_on คือเราจะให้มันสร้าง db จนเสร็จ จากนั้นค่อยสร้าง container ตัวเอง</li></ul><p>สามารถ run ได้โดยใช้คำสั่ง</p><pre>docker compose -f docker-compose.test.yaml up --build --abort-on-container-exit</pre><p>เมื่อเรา test จำเป็นต้องใช้คำสั่งด้านล่าง เพื่อทำการลบ container ออก</p><pre>docker compose -f docker-compose.test.yaml down</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10637a8fea8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[สิ่งที่ได้จาก GO software engineering Bootcamp ]]></title>
            <link>https://medium.com/@ong.pasit/%E0%B8%AA%E0%B8%B4%E0%B9%88%E0%B8%87%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B9%84%E0%B8%94%E0%B9%89%E0%B8%88%E0%B8%B2%E0%B8%81-go-software-engineering-bootcamp-5aaaa5e419a0?source=rss-1f4ef4ec3d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aaaa5e419a0</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[engineer]]></category>
            <category><![CDATA[workshop]]></category>
            <category><![CDATA[bootcamp]]></category>
            <category><![CDATA[experience]]></category>
            <dc:creator><![CDATA[Pasit Sri-intarasut]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 16:14:47 GMT</pubDate>
            <atom:updated>2023-01-17T03:02:39.399Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WpdtMHfdYt7qa7iA" /><figcaption>Photo by <a href="https://unsplash.com/@sebastien_bonneval?utm_source=medium&amp;utm_medium=referral">Sebastien Bonneval</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>เป็น workshop ที่สนุกและได้รับความรู้มากๆ รู้สึกว่าได้เติบโตเป็น software engineer ที่ดีขึ้น เลยอยากจะมา share สักหน่อยว่า 2 วันที่ผ่านมาได้ทำอะไรไปบ้าง เพื่อทบทวนตัวเองไปด้วย</p><h3>วันที่ 1</h3><p>จะเป็นการอธิบาย Project ที่เราได้รับว่าต้องทำอะไรบ้าง และให้แต่ละทีมทำการ design api ให้เหมาะสม ในส่วนนี้เราจะได้ prioritize ว่า feature อะไรสำคัญที่สุด เนื่องจากเรามีเวลาที่จำกัด และมีอีกส่วนคือการทำ devops เพื่อ setting environment ให้เพื่อนร่วมทีมทำงานได้อย่างมีประสิทธิภาพ</p><p>โดยหลังจากการประชุมกันจะให้จับคู่ทำ pair programming โดยให้แต่ละคู่หยิบ card เพื่อนำมาช่วยกันทำ ก่อนจบวันแรกจะมีการ review code ของแต่ละกลุ่มจากพี่หน่อง โค้ชสุดหล่อประจำ workshop โดยจะสรุปเท่าที่จำได้</p><ul><li>golang ใช้ camel case เป็นชื่อของ function, variable</li><li>test ควรอ่านง่าย มีการแบ่งสัดส่วนให้ดี</li><li>database ไม่ควรอยู่ใน handler</li><li>database ควรทำให้ simple ที่สุด (read, write)</li><li>ชื่อ package ไม่ควรเป็น sneak case</li><li>golang เป็นภาษาที่ simple มากๆ ทำให้ code ของแต่ละทีมคล้ายๆกัน</li><li>variable ไม่ควรอยู่ห่างจากที่ๆเราจะใช้มากเกินไป เนื่องจากเวลาอ่าน code แล้วจะได้รู้ว่าจะใช้เมื่อไร</li><li>defer เจ๋งมาก</li><li>error handling ของ go ที่เราสามารถเลือกได้ว่าจะ handle หรือ ignore มันก็ได้ มันจะไม่ throw exception ให้เรากลัว</li><li>เวลาตั้งชื่อของตัวแปรควรจะอ่านแล้วรู้ว่าจะเน้นอะไร เช่น</li></ul><pre>// ❌<br>cloundPocketHandler = NewCloundPocketHandler()<br>cloundPocketHandler.GetPocketByID()<br><br>// ✔<br>c = NewCloundPocketHandler()<br>c.GetPocketByID()</pre><ul><li>… ผมจำไม่ได้ละครับ5555</li></ul><p>หลังจาก code review จบจะมีการทำ retrospective กัน โดยจะให้ทุกคนในทีมระบุ 3 สิ่งคือ Like, Learn, Lacked ใน post it และแปะกันดู โดยส่วนตัวชอบมาก เนื่องจากได้เห็น feedback ของพี่ๆแต่ละคน ทำให้ทีมสามารถนำเอาจุดด้อยมาปรับปรุงได้อย่างรวดเร็ว</p><h3>วันที่ 2 🔥🔥🔥</h3><p>วันนี้ทีมเรา plan ไว้ว่าจะทำ feature ที่เหลือให้เสร็จ แต่ว่าโค้ชสุดหล่อของเราอยากให้ทุกคนทำงานใน branch main ขออธิบายก่อนว่าในทีมผมจะทำ feature ใน branch ของตัวเองไว้ก่อน แน่นอนว่าพอนำมารวมกันก็ระเบิดครับ แล้วแต่ละคนก็แก้กันยาวๆ ในตอนนั้นผมจดจ่อแต่กับ code ตัวเอง ไม่สนอะไรเลย แต่พี่โค้ชสุดหล่อคนเดิมได้พูดประโยคที่ผมชอบที่สุดใน workshop ครั้งนี้ออกมา</p><blockquote>“คิดว่าการเขียน code ไปเรื่อยๆจะทำให้ software ที่ออกมามีประสิทธิภาพหรือเปล่า”</blockquote><p>ตรงนี้พี่เค้าได้อธิบายไว้ว่าเราควรจะมีการวางแผนกันว่าเราควรจะแก้อะไรกันก่อน รวมตัวกันไปมุงช่วยเพื่อนที่ติดปัญหา และต้องมีการทำ test ในทุก feature เนื่องจากหากเราทำ feature ใหม่ๆ เราจะรู้ได้ว่ามันจะกระทบกับ feature เก่าหรือไม่จาก test เก่าๆที่เราได้ทำไว้นั่นเอง</p><p>หลังจากพักกลางวัน ก็ได้มีเหตุด่วนเข้ามา? อะไรนะ 0.1 + 0.2 ได้ 0.30000000000000004 อย่างงั้นเหรอ!!! ปัญหานี้ทำให้เราได้รู้วิธีการจัดการปัญหาที่อยู่บน production โดยการแก้ hotfix แบบเร่งด่วน ฝั่ง devops จะสร้าง environment ของ hotfix ไว้ให้ เมื่อทำการ push ขึ้น branch hotfix จะทำให้ deploy ไปยัง environment ของ hotfix</p><p>ทีมเราแก้ปัญหาโดยใช้ library ที่ชื่อว่า <a href="http://github.com/shopspring/decimal">decimal</a> ทำให้ปัญหานี้หมดไป และในระหว่างนั้น พี่ๆในทีมผมช่วยแก้บักจนทำให้ pipeline จาก github action เขียวได้แล้ว สุดยอดมากครับ หลังจากนั้นก็เป็น code review และตอบคำถามเล็กน้อย</p><ul><li>ที่เรา comment code ทั้ง file แสดงว่า code อาจจะ complex เกินไป ทำให้อ่านง่ายกว่านี้ได้มั้ย</li><li>CAP theorem หลักการเลือก database</li><li>เริ่มจาก monolith ไป microservices, ควรจะแยกไปทำ microservices เมื่อมีส่วนหนึ่งใน monolith ถูกเรียกใช้งานเยอะๆ</li></ul><p>ก่อนจบมีพี่ขึ้นมาพูดถึง 3 สิ่งที่เราจะได้ติดตัวจาก workshop นี้ (ผมจำได้คร่าวๆนะครับ เนื่องจากผมเองก็เบลอมากๆละ)</p><ul><li>good programmer หลักการเขียน Program ที่มีประสิทธิภาพ</li><li>good engineer การสร้าง software ให้อยู่ในไปได้นานๆ</li><li>good manager การจัดการ task, การพูดคุยกับคนในทีม</li></ul><p>สุดท้ายคือถ่ายรูปครับ</p><h3>conclusion</h3><p>ผมทำในส่วนของ devops ของทีมครับ คิดว่าจะเอาตัวไม่รอดแต่ก็ผ่านมาได้ครับ นึกว่าผมจะได้อยู่คนเดียวเหงาๆ แต่ทีมนี้ทุกคน friendly มากครับ</p><p>coding นั้นเป็นแค่ส่วนหนึ่งของการพัฒนา software ครับ</p><p>เพิ่งรู้จัก retrospective จริงๆเป็นครั้งแรก ชอบมากครับ จะนำไปใช้แน่นอนครับ</p><p>วันที่สองทำให้ผมได้รู้ซึ้งถึงความสำคัญของ test <strong><em>อย่างแท้จริง</em></strong> ครับ</p><p>devops สุดยอดมากครับ รู้สึกเปิดโลกมาก เป็นที่สิ่งสำคัญของทีมจริงๆ อยากให้มีสอนอีกเยอะๆเลยครับ</p><p>พี่โค้ชทั้ง 2 คนสุดยอดมากครับ คอยดูทุกทีมอยู่ห่างๆและเข้ามาให้คำแนะนำในเวลาที่ต้องการเสมอ มีสอดแทรกแนวคิดในการทำงานอยู่ตลอด เปิดมุมมองใหม่ๆที่มีต่อการทำงานมากครับ</p><p>สุดท้ายขอขอบคุณ KBTG มากๆที่ทำ workshop นี้ขึ้นมา ขอบคุณพี่ๆทีมงานทุกคน ดูแลดีมากครับ ขอบคุณแม่บ้านครับ เป็นกันเองมาก ขอบคุณทีมของผมมากๆๆๆครับ รู้สึกเป็นตัวถ่วงมาก5555 ผู้เข้าร่วมทุกคนเป็นกันเองมากครับ ดีใจมากที่ได้เข้าร่วม workshop นี้</p><p>และสุดท้ายของสุดท้ายครับ ผมเขียนบทความนี้เพื่อตัวเองครับ แต่ถ้าเป็นประโยชน์กับคนที่มาอ่านผมก็ดีใจครับ หากบทความนี้ผิดพลาดตรงไหนก็ email แจ้งที่ ong.pasit@gmail.com นะครับ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aaaa5e419a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ประสบการณ์ทำงานกับ legacy code ด้วย docker]]></title>
            <link>https://medium.com/@ong.pasit/%E0%B8%9B%E0%B8%A3%E0%B8%B0%E0%B8%AA%E0%B8%9A%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%93%E0%B9%8C%E0%B8%97%E0%B8%B3%E0%B8%87%E0%B8%B2%E0%B8%99%E0%B8%81%E0%B8%B1%E0%B8%9A-legacy-code-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-docker-8becbdb0714d?source=rss-1f4ef4ec3d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/8becbdb0714d</guid>
            <category><![CDATA[legacy-code]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Pasit Sri-intarasut]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 17:43:35 GMT</pubDate>
            <atom:updated>2023-01-06T17:43:35.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oqj_qj8Q492MdASg.jpg" /></figure><p>เคยมั้ย เวลาที่เราได้ใช้ library เก่าๆ แล้ว library เหล่านั้นไม่ได้ถูก update มานาน 7–8 ปี พอนำมาใช้ก็เกิด error บานเบอะ เนื่องจาก environment ที่เปลี่ยนไป ทำให้ไม่สามารถทำงานได้เหมือนแต่ก่อน</p><p>วันนี้ผมมีโอกาสได้เจอกับตัว เรื่องมีอยู่ว่าผมได้ลองเขียน code ตามหนังสือเรื่อง <a href="https://www.amazon.com/Go-Programming-Blueprints-Development-Challenges/dp/1783988029">Go Programming Blueprints: Ryer, Mat</a> ซึ่งหนังสือเขียนไว้หลายปีแล้ว โดยในหนังสือมีการอ้างอิงถึง library ชื่อว่า <a href="https://github.com/go-mgo/mgo">go-mgo/mgo</a> โดยเป็น library ที่ใช้เชื่อมต่อกับ <a href="https://www.mongodb.com/">mongodb</a> ซึ่งเป็น project ที่ไม่ได้ถูกดูแลมาสักพักแล้ว (4 year ago 🤯)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QhxJcfbHFOxdUr2LpP7wOA.png" /></figure><p>และเมื่อลอง run code ดูก็หวังว่าจะไม่ error แต่ไม่รอด</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*CsV5KyLxO69EYqTo45SSnQ.png" /></figure><p>งั้นลองมาอ่าน log ของ mongo กันดีกว่า ว่าสาเหตุมันเกิดจากอะไร</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRiNj16vwNCr-C3t0jvfoQ.png" /><figcaption>เจอแล้ววววว</figcaption></figure><p>โอเค มันบอกว่า version ที่เราใช้สูงเกินไป ถ้าหากอยากใช้ feature นี้ให้ลด version ลงนะ งั้นเราก็ต้องลบ mongodb แล้วติดตั้งใหม่งั้นสิ 🤮</p><p>งั้นก็ถึงเวลาที่ docker ของเราต้องออกโรงแล้ว โดยผมจะเขียน docker compose ไว้ประมาณนี้</p><pre>version: &#39;3&#39;<br>service:<br>  mongo:<br>    image: mongo4.4<br>    ports:<br>      - 27017:27017</pre><p>สังเกตว่าผมได้ระบุ version ของ docker ไว้เป็น version 4.4 เนื่องจากผมใช้ version ล่าสุด</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*DxFqZT7kQ6GEhj6ONA8edQ.png" /><figcaption>ทำงานได้แล้ววววว</figcaption></figure><p>และแล้ว code ก็สามารถทำงานได้อย่างปกติ happy ending</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8becbdb0714d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[วิธีใช้ ticker ใน golang]]></title>
            <link>https://medium.com/@ong.pasit/%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5%E0%B9%83%E0%B8%8A%E0%B9%89-ticker-%E0%B9%83%E0%B8%99-golang-ed9e2219d6a0?source=rss-1f4ef4ec3d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed9e2219d6a0</guid>
            <category><![CDATA[interval]]></category>
            <category><![CDATA[time]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Pasit Sri-intarasut]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 12:58:08 GMT</pubDate>
            <atom:updated>2023-01-03T12:58:08.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZnGd8tGy0uDXPo0V" /><figcaption>Photo by <a href="https://unsplash.com/@arielbesagar?utm_source=medium&amp;utm_medium=referral">Ariel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>ในแต่ละงานจะมี function ที่เราต้องการให้มันทำซ้ำๆเป็นช่วงๆ เราสามารถใช้ ticker ใน golang เพื่อกำหนดเวลาในการส่งสัญญาณเพื่อให้ function นั้นทำซ้ำๆ ได้</p><p>เริ่มจากการสร้าง ticker ขึ้นมา โดยตัว ticker จะทำหน้าที่ส่งสัญญาณ(เนื่องจาก type เป็น channel)</p><pre> ticker := time.NewTicker(1 * time.Second)</pre><p>โดยเรากำหนดให้มันส่งสัญญาณมาทุก 1 วินาที</p><pre> for _ = range ticker.C {<br>  fmt.Println(&quot;tick...&quot;)<br> }</pre><p>จาก code ด้านบน ticker.C คือ channel ที่จะส่งสัญญาณทุกครั้งตามที่เราได้ตั้งค่าไว้ในตอนสร้าง ticker และจะแสดงค่า “tick…” ทุก 1 วินาที</p><p>คราวนี้เรามาลองใช้กับ goroutine ดู โดยเราจะให้มันทำงานใน background และเมื่อเกิด interrupt หรือเมื่อหมดเวลาหลังจาก 5 วินาที ให้มันออกจากการทำงาน</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;os&quot;<br> &quot;os/signal&quot;<br> &quot;syscall&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> ticker := time.NewTicker(1 * time.Second)<br> termChan := make(chan os.Signal, 1)<br> go func() {<br>  for t := range ticker.C {<br>   fmt.Println(&quot;Tick at :&quot;, t)<br>  }<br> }()<br><br> signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)<br> select {<br> case &lt;-termChan:<br>  fmt.Println(&quot;job done&quot;)<br> case &lt;-time.After(5 * time.Second):<br>  fmt.Println(&quot;time job done&quot;)<br> }<br>}</pre><p>output:</p><pre>$ go run .<br>Tick at : 2023-01-03 19:51:41.80709436 +0700 +07 m=+1.000194619<br>Tick at : 2023-01-03 19:51:42.807211305 +0700 +07 m=+2.000311561<br>Tick at : 2023-01-03 19:51:43.807307424 +0700 +07 m=+3.000407638<br>time job done</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed9e2219d6a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[สร้าง database local ตัวไหนก็ได้ด้วย docker]]></title>
            <link>https://medium.com/@ong.pasit/%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87-database-local-%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%84%E0%B8%AB%E0%B8%99%E0%B8%81%E0%B9%87%E0%B9%84%E0%B8%94%E0%B9%89%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-docker-cc76b94f2d51?source=rss-1f4ef4ec3d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc76b94f2d51</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Pasit Sri-intarasut]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 15:18:07 GMT</pubDate>
            <atom:updated>2022-12-29T15:18:07.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*NH4JKL1hFt7sOmUG.png" /></figure><p>เป็นวิธีส่วนตัวที่เราอยากจะใช้ database สักตัว แต่ไม่อยากติดตั้งให้มันวุ่นวาย พอได้มารู้จัก docker รู้สึกว่าช่วยได้มากกกก</p><p>ในกรณีนี้ขอยกตัวอย่างเป็น postgres</p><p>โดยเรามาที่หน้าของ docker image ที่เราต้องการจะใช้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r5-XRXfP9ebHERaZlGDGMg.png" /><figcaption><a href="https://hub.docker.com/_/postgres">postgres — Official Image | Docker Hub</a></figcaption></figure><pre>$ docker run --rm -d -e POSTGRES_PASSWORD=1234 -p 5432:5432 postgres</pre><p>จากนั้นก็ใช้ docker command ด้านบน โดยทำการ expose port ออกมานอก container ทำให้ local สามารถใช้ database ได้ โดยที่ไม่จำเป็นต้องติดตั้ง database เลย</p><p>ด้วยวิธีนี้ทำให้ผมสามารถเลือก database ตัวไหนก็ได้ตามที่อยากใช้เลยครับ โดยหากเราขี้เกียจเขียน command ทุกครั้งที่จะทำ project ก็สามารถเขียนเป็น docker compose ได้อีกด้วย</p><p>แต่เราก็ต้องศึกษา database ที่เราจะใช้ให้ดีด้วยว่าต้องตั้งค่าอย่างไรบ้าง โดยสามารถอ่านได้จาก docker hub ของ database ที่เรานำมาใช้</p><p>อย่างในตัวอย่าง เราใช้ port 5432 เนื่องจากเป็น default ของ postgres แต่ถ้าเป็น mariadb จะใช้ port 3306 และ environment variable ก็จะไม่เหมือนกันอีก ก็ต้องดูดีๆนะครับ หวังว่าจะเป็นประโยชน์ครับ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc76b94f2d51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[วิธีลบไฟล์ใน git ที่ commit เก่ามากๆ]]></title>
            <link>https://medium.com/@ong.pasit/%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5%E0%B8%A5%E0%B8%9A%E0%B9%84%E0%B8%9F%E0%B8%A5%E0%B9%8C%E0%B9%83%E0%B8%99-git-%E0%B8%97%E0%B8%B5%E0%B9%88-commit-%E0%B9%80%E0%B8%81%E0%B9%88%E0%B8%B2%E0%B8%A1%E0%B8%B2%E0%B8%81%E0%B9%86-4afd7f7dd86e?source=rss-1f4ef4ec3d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/4afd7f7dd86e</guid>
            <dc:creator><![CDATA[Pasit Sri-intarasut]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 11:56:01 GMT</pubDate>
            <atom:updated>2022-12-27T13:50:12.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-rrxsQXDCitTfais" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych 🇺🇦</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>วันนี้ผมได้เขียน project เล่นๆ แล้วเพิ่งสังเกตว่าตัวเองได้ commit ไฟล์ที่เก็บ secret key ไว้ เมื่อลองหาดูจึงเห็นว่า ผมได้ commit ไว้ในหลาย commit ที่แล้ว</p><p>พอลองหาวิธีลบก็มีแต่ให้ใช้ git reset HEAD แต่ของผมมันต้องย้อนไปไกลมากๆ และมันทำให้เสียเวลากับการต้องมานั่ง commit ใหม่หมด เลยอยากมา share วิธีนี้ไว้ครับ</p><pre>$ git log --oneline --decorate<br>824a40c (HEAD -&gt; main) add animal folder<br>99525a1 add file1 file2<br>f0789ce add secret file<br>a60135f add README.md</pre><p>สมมติว่าเราได้ add secret file ไว้ใน <strong>commit</strong> ที่ f0789ce แล้วได้ทำการ commit เพิ่ม commit อีก 2 commit</p><pre>git rebase f0789ce^ -i</pre><p>คำสั่งนี้จะทำให้มีการ rebase ใหม่ของ commit นั้นๆ โดย ^ นั้นสำคัญมาก เนื่องจากเป็น character ที่บอกว่าให้ไปที่ commit ก่อนที่เราจะ modify</p><pre>e f0789ce add secret file<br>pick 99525a1 add file1 file2<br>pick 824a40c add animal folder</pre><p>เปลี่ยนจาก pick เป็น e หรือ edit เพื่อบอกว่าเราจะแก้ commit นั้น</p><pre>git rm secret<br>git rebase --continue</pre><p>ใช้คำสั่ง git rm &lt;filename&gt; เพื่อลบไฟล์และ git rebase — continue เพื่อ จบการ edit</p><ul><li>*คำเตือน: เมื่อใช้วิธีนี้ ไฟล์ที่เราได้ลบไปจะไม่ถูก track ใน git ทำให้ไม่สามารถกู้คืนไฟล์ได้ คิดให้ดีๆก่อนใช้นะครับ เพราะอย่างกรณีผม ผมไม่ต้องการให้ secret key ถูก git track ไว้เลยใช้วิธีนี้ครับ</li></ul><h3>reference sources</h3><ul><li><a href="https://stackoverflow.com/questions/1186535/how-do-i-modify-a-specific-commit">https://stackoverflow.com/questions/1186535/how-do-i-modify-a-specific-commit</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4afd7f7dd86e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Login ด้วย OAuth2 ใน golang โดยใช้ go-omniauth กันเถอะ]]></title>
            <link>https://medium.com/@ong.pasit/login-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-oauth2-%E0%B9%83%E0%B8%99-golang-%E0%B9%82%E0%B8%94%E0%B8%A2%E0%B9%83%E0%B8%8A%E0%B9%89-go-omniauth-%E0%B8%81%E0%B8%B1%E0%B8%99%E0%B9%80%E0%B8%96%E0%B8%AD%E0%B8%B0-b24f7f6ab953?source=rss-1f4ef4ec3d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/b24f7f6ab953</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Pasit Sri-intarasut]]></dc:creator>
            <pubDate>Sun, 25 Dec 2022 16:39:17 GMT</pubDate>
            <atom:updated>2022-12-25T16:39:17.169Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JP1zQ91Rh4KikyMz" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>วันนี้วันดี เรามาลอง login โดยใช้ oauth2 กัน</p><h3>Oauth2 คืออะไร ?</h3><p>OAuth <em>[อ่านว่า โอ-อ๊อท]</em> ย่อมาจาก Open Authentication เป็นมาตรฐานการยืนยันสิทธ์ (Authentication) และการตรวจสอบสิทธ์ (Authorization) ซึ่งเป็นมาตรฐานแบบเปิด ปัจจุบันเป็นเวอร์ชั่น 2 หรือ OAuth 2.0 (<a href="http://sdm.ubu.ac.th/blog/suttichai-160">http://sdm.ubu.ac.th/blog/suttichai-160</a>)</p><p>โดยคร่าวๆก็ประมาณนี้ งั้นเรามาเริ่ม project กันเถอะ</p><p>ก่อนอื่นเราจะใช้ oauth ของ Google โดยเราจะต้องทำการสมัคร เพื่อขอใช้ api ของ google นะครับ</p><p><a href="https://console.cloud.google.com/apis/credentials">https://console.cloud.google.com/apis/credentials</a> มาที่ link โดยหากยังไม่สร้าง project ให้สร้างก่อนนะครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wH8oQItFpS3iw39SPq3zwQ.png" /><figcaption><a href="https://console.cloud.google.com/apis/credentials">https://console.cloud.google.com/apis/credentials</a></figcaption></figure><p>ทำการสร้าง credentials โดยทำการเลือกหัวข้อ<strong> Create OAuth client ID</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*p-yMZNyONYrLPOEizfUroA.png" /></figure><p>ให้ใส่ <a href="http://localhost:3000/auth/callback/google">http://localhost:3000/auth/callback/google</a> ใน Authorized redirect URIs เพื่อให้ redirect กลับมาที่ page ของเราหลังจาก login เรียบร้อยแล้ว</p><p>** ทำการเก็บ client_id และ client_secret ไว้ด้วย</p><h3>Coding time</h3><p>ในเริ่มต้น project เรามีหน้าตาแบบนี้</p><pre>// main.go<br>package main<br><br>import (<br> &quot;log&quot;<br> &quot;net/http&quot;<br>)<br><br>func main() {<br> mux := http.NewServeMux()<br> mux.HandleFunc(&quot;/&quot;, func(w http.ResponseWriter, _ *http.Request) {<br>  w.Write([]byte(&quot;Hello world&quot;))<br> })<br><br> server := http.Server{<br>  Handler: mux,<br>  Addr:    &quot;:3000&quot;,<br> }<br><br> log.Println(&quot;serve by port :3000&quot;)<br> if err2 := server.ListenAndServe(); err != nil {<br>  log.Fatal(err)<br> }<br>}</pre><p>เอ๊ะ แต่เราต้องมีหน้า login นิ งั้นเรามาสร้างหน้า login กันก่อน</p><pre>&lt;!-- templates/login.html --&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br> &lt;title&gt;Login&lt;/title&gt;<br> &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css&quot; integrity=&quot;sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T&quot; crossorigin=&quot;anonymous&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br> &lt;div class=&quot;container&quot;&gt;<br>  &lt;div class=&quot;page-header&quot;&gt;<br>   &lt;h1&gt;Sign in&lt;/h1&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;panel panel-danger&quot;&gt;<br>   &lt;div class=&quot;panel-heading&quot;&gt;<br>    &lt;h3 class=&quot;panel-title&quot;&gt;In order to chat, you must be signed in&lt;/h3&gt;<br>   &lt;/div&gt;<br>   &lt;div class=&quot;panel-body&quot;&gt;<br>    &lt;p&gt;Select the service you would like to sign in with:&lt;/p&gt;<br>    &lt;ul&gt;<br>     &lt;li&gt;&lt;a href=&quot;/auth/login/google&quot;&gt;Google&lt;/a&gt;&lt;/li&gt;<br>    &lt;/ul&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>และเราก็เพิ่ม templateHandler struct ใน main.go</p><pre>package main<br><br>import (<br> &quot;html/template&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;path/filepath&quot;<br> &quot;sync&quot;<br>)<br><br>type templateHandler struct {<br> once     sync.Once<br> filename string<br> tmpl     *template.Template<br>}<br><br>func (t templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {<br> t.once.Do(func() {<br>  t.tmpl = template.Must(template.ParseFiles(filepath.Join(&quot;templates&quot;, t.filename)))<br> })<br> t.tmpl.Execute(w, nil)<br>}<br><br>func main() {<br> mux := http.NewServeMux()<br> mux.HandleFunc(&quot;/&quot;, func(w http.ResponseWriter, _ *http.Request) {<br>  w.Write([]byte(&quot;Hello world&quot;))<br> })<br> mux.Handle(&quot;/login&quot;, &amp;templateHandler{filename: &quot;login.html&quot;})<br><br> server := http.Server{<br>  Handler: mux,<br>  Addr:    &quot;:3000&quot;,<br> }<br><br> log.Println(&quot;serve by port :3000&quot;)<br> if err := server.ListenAndServe(); err != nil {<br>  log.Fatal(err)<br> }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*kuUb_aTBMs_XAZzLwx7QWQ.png" /><figcaption><a href="http://localhost:3000/login">http://localhost:3000/login</a></figcaption></figure><p>จากนั้นทำการติดตั้ง <a href="https://github.com/outrightmental/go-omniauth">go-omniauth</a> เพื่อใช้ login โดยใช้ google account</p><pre>go get https://github.com/outrightmental/go-omniauth<br>go get github.com/stretchr/signature</pre><p>โดยเราจะให้ path ที่ใช้ในการ login and callback เป็น</p><p><em>/auth/:action/:provider</em></p><p>โดย action จะมี login ที่เราใช้เพื่อเชื่อม api กับ google และ provider ก็คือ google นั้นเอง</p><pre>// main.go<br>func main() {<br> gomniauth.SetSecurityKey(signature.RandomKey(64))<br> gomniauth.WithProviders(<br>  google.New(os.Getenv(&quot;CLIENT_ID&quot;), os.Getenv(&quot;CLIENT_SECRET&quot;), &quot;http://localhost:3000/auth/callback/google&quot;),<br> )<br>  // ...<br>}</pre><p>ทำการเพื่ม code ส่วนที่ขอใช้ api จาก google โดย client_id และ client_secret ได้มาจากการที่เราได้สร้าง project</p><pre>// auth.go<br>package main<br><br>import (<br> &quot;net/http&quot;<br> &quot;strings&quot;<br><br> &quot;github.com/stretchr/gomniauth&quot;<br>)<br><br>func loginHandler(w http.ResponseWriter, r *http.Request) {<br> segs := strings.Split(r.URL.Path, &quot;/&quot;)<br> action := segs[2]<br> provider := segs[3]<br> switch action {<br> case &quot;login&quot;:<br>  provider, err := gomniauth.Provider(provider)<br>  if err != nil {<br>   http.Error(w, &quot;loginHandler can&#39;t choose provider&quot;, http.StatusInternalServerError)<br>  }<br>  authUrl, err := provider.GetBeginAuthURL(nil, nil)<br>  if err != nil {<br>   http.Error(w, &quot;loginHandler can&#39;t choose provider&quot;, http.StatusInternalServerError)<br>  }<br>  w.Header().Set(&quot;Location&quot;, authUrl)<br>  w.WriteHeader(http.StatusTemporaryRedirect)<br> }<br>}<br><br>// main.go<br>func main() {<br>  // ...<br>  mux.HandleFunc(&quot;/auth/&quot;, loginHandler)<br>  // ...<br>}</pre><p>สร้าง ไฟล ์ auth.go และสร้าง function loginHandler เพื่อจัดการการ path ที่ใช้ในการ login and callback โดยในการ login เราจะทำการระบุ provider และขอ url เพื่อใช้ในการ login</p><p>จากนั้นทำการ run ตู้ม</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*POvX0kKC99oagCSfDCpLxQ.png" /><figcaption>มาแล้ววววว !!!!</figcaption></figure><p>พอทำการ login แล้วจะได้หน้าดำๆ ไม่ต้องตกใจนะครับ เดี๋ยวมาทำกันต่อ</p><pre>// auth.go<br><br>// ...<br><br>func loginHandler(w http.ResponseWriter, r *http.Request) {<br> // ...<br>  case &quot;callback&quot;:<br>  provider, err := gomniauth.Provider(provider)<br>  if err != nil {<br>   http.Error(w, &quot;loginHandler can&#39;t choose provider&quot;, http.StatusInternalServerError)<br>   return<br>  }<br>  creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))<br>  if err != nil {<br>   http.Error(w, &quot;loginHandler can&#39;t complete login&quot;, http.StatusInternalServerError)<br>   return<br>  }<br>  user, err := provider.GetUser(creds)<br>  if err != nil {<br>   http.Error(w, &quot;loginHandler can&#39;t get user information&quot;, http.StatusInternalServerError)<br>   return<br>  }<br>  authCookie := objx.New(map[string]interface{}{<br>   &quot;email&quot;: user.Email(),<br>   &quot;name&quot;:  user.Name(),<br>  }).MustBase64()<br>  http.SetCookie(w, &amp;http.Cookie{<br>   Name:   &quot;auth&quot;,<br>   Value:  authCookie,<br>   MaxAge: 300,<br>   Path:   &quot;/&quot;,<br>  })<br>  w.Header().Set(&quot;Location&quot;, &quot;/secret&quot;)<br>  w.WriteHeader(http.StatusTemporaryRedirect)<br> }</pre><p>ผมได้เพิ่มส่วนที่ เป็น callback ไว้ โดยอธิบายง่ายๆว่าเป็นการรับ credentials จากฝั่งของ google และใช้ creds ในการเข้าถึงข้อมูลใน google account โดยผมได้ทำการใช้ objx เพื่อจัดการแปลงข้อมูลที่ใช้เป็น base64 และเก็บไว้ใน cookie ครับ</p><p>จาก code ด้านบนมันจะทำการ redirect ไปหา /secret ผมจึงสร้าง handle ไว้แบบคร่าวๆ</p><pre>func main(){<br>  // ...<br>  mux.HandleFunc(&quot;/secret&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  var data map[string]interface{}<br>  if authCookie, err := r.Cookie(&quot;auth&quot;); err == nil {<br>   data = objx.MustFromBase64(authCookie.Value)<br>  }<br>  log.Printf(&quot;%#v\n&quot;, data)<br>  w.WriteHeader(http.StatusOK)<br>  fmt.Fprintf(w, &quot;Hi %s&quot;, data[&quot;email&quot;])<br> })<br>  // ...<br>}</pre><p>แต่แบบนี้ใครจะเข้า /secret ของเราก็ได้นะสิ งั้นเราก็จับมันใส่ middleware ซะก็พอ</p><pre>// auth.go<br><br>type authMiddleware struct {<br> next http.HandlerFunc<br>}<br><br>func (m authMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {<br> c, err := r.Cookie(&quot;auth&quot;)<br> if err == http.ErrNoCookie || c.Value == &quot;&quot; {<br>  w.Header().Set(&quot;Location&quot;, &quot;/login&quot;)<br>  w.WriteHeader(http.StatusTemporaryRedirect)<br> }<br> if err != nil {<br>  http.Error(w, err.Error(), http.StatusInternalServerError)<br> }<br> m.next.ServeHTTP(w, r)<br>}<br><br>// main.go <br>func main(){<br>  // ...<br> mux.Handle(&quot;/secret&quot;, &amp;authMiddleware{next: func(w http.ResponseWriter, r *http.Request) {<br>  var data map[string]interface{}<br>  if authCookie, err := r.Cookie(&quot;auth&quot;); err == nil {<br>   data = objx.MustFromBase64(authCookie.Value)<br>  }<br>  log.Printf(&quot;%#v\n&quot;, data)<br>  w.WriteHeader(http.StatusOK)<br>  fmt.Fprintf(w, &quot;Hi %s&quot;, data[&quot;email&quot;])<br> }})<br> // ...<br>}</pre><p>ทำการสร้าง middleware เพื่อทำการ check cookie ก่อนจะเข้า path ของ secret</p><p>เมื่อเราทำจะพยายามเข้าไปยัง path /secret หากมันไม่เจอ cookie ก็ไม่สามารถเข้าได้</p><pre>func main(){<br>  // ...<br>  mux.HandleFunc(&quot;/logout&quot;, func(w http.ResponseWriter, _ *http.Request) {<br>  http.SetCookie(w, &amp;http.Cookie{<br>   Name:   &quot;auth&quot;,<br>   Value:  &quot;&quot;,<br>   Path:   &quot;/&quot;,<br>   MaxAge: -1,<br>  })<br>  w.Header().Set(&quot;Locatoin&quot;, &quot;/login&quot;)<br>  w.WriteHeader(http.StatusTemporaryRedirect)<br> })<br> // ...<br>}</pre><p>จบด้วยการสร้าง path /logout เพื่อทำการลบ cookie ทิ้ง และ redirect ไปยัง login</p><h3><strong>Conclusion</strong></h3><p>หลักๆคือ</p><ul><li>การใช้ lib <a href="https://github.com/outrightmental/go-omniauth">go-omniauth</a> ในการ connect กับ api ของ google</li><li>การ handle action ของแต่ละ uri เช่น auth/login/google, auth/login/google</li><li>สร้าง middleware เพื่อใช้ในการ check ว่ามีการ login ไว้หรือไม่</li></ul><p>เหตุผลที่เขียนส่วนหนึ่งเพราะอยากทบทวนความรู้ตัวเองด้วย หวังว่าจะเป็นประโยชน์ไม่มากก็น้อยครับ</p><ul><li>source code: <a href="https://github.com/Dsypasit/go-simple-oauth2.git">https://github.com/Dsypasit/go-simple-oauth2.git</a></li></ul><p><strong>references</strong></p><ul><li><a href="https://www.amazon.com/Go-Programming-Blueprints-Development-Challenges/dp/1783988029">https://www.amazon.com/Go-Programming-Blueprints-Development-Challenges/dp/1783988029</a></li><li><a href="https://github.com/outrightmental/go-omniauth">https://github.com/outrightmental/go-omniauth</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b24f7f6ab953" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[golang ทำ logging ใน net/http ง่ายๆ ด้วยการเขียน middleware กันเถอะ]]></title>
            <link>https://medium.com/@ong.pasit/golang-%E0%B8%97%E0%B8%B3-logging-%E0%B9%83%E0%B8%99-net-http-%E0%B8%87%E0%B9%88%E0%B8%B2%E0%B8%A2%E0%B9%86-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%82%E0%B8%B5%E0%B8%A2%E0%B8%99-middleware-%E0%B8%81%E0%B8%B1%E0%B8%99%E0%B9%80%E0%B8%96%E0%B8%AD%E0%B8%B0-d1ec2eef6277?source=rss-1f4ef4ec3d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1ec2eef6277</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[middleware]]></category>
            <dc:creator><![CDATA[Pasit Sri-intarasut]]></dc:creator>
            <pubDate>Mon, 19 Dec 2022 02:49:54 GMT</pubDate>
            <atom:updated>2022-12-19T02:49:54.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xiOzBRjDR_NICWCk4OUfOQ.png" /></figure><p>ในการจะสร้าง web application เราอาจจะมีบาง function ที่เราต้องการให้มัน run ในทุก HTTP request เช่นการ log หรือ check auth</p><p><em>middleware</em> ก็เป็น 1 ในวิธีการในการเหล่านั้น โดยในตัวมันจะมี code ที่เราต้องการให้มันทำก่อนหรือหลัง normal application</p><p>โดยในเริ่มแรก เราให้ application ของเราหน้าตาแบบนี้</p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;net/http&quot;<br>)<br><br>func Hello(w http.ResponseWriter, r *http.Request) {<br> w.Write([]byte(&quot;hello\n&quot;))<br> return<br>}<br>func test(w http.ResponseWriter, r *http.Request) {<br> w.Write([]byte(&quot;test\n&quot;))<br> return<br>}<br><br>func main() {<br> mux := http.NewServeMux()<br> mux.HandleFunc(&quot;/hello&quot;, Hello)<br> mux.HandleFunc(&quot;/test&quot;, test)<br><br> srv := http.Server{<br>  Addr:    &quot;:3000&quot;,<br>  Handler: mux,<br> }<br> log.Println(&quot;Server up by port 3000&quot;)<br> log.Fatal(srv.ListenAndServe())<br>}</pre><p>สังเกตว่าเราส่ง mux เป็น Handler ของ server เรามาดูกันว่า Handler ของ server นั้นหน้าตาเป็นอย่างไร</p><pre>// A Handler responds to an HTTP request.<br>//<br>// ServeHTTP should write reply headers and data to the ResponseWriter<br>// and then return. Returning signals that the request is finished; it<br>// is not valid to use the ResponseWriter or read from the<br>// Request.Body after or concurrently with the completion of the<br>// ServeHTTP call.<br>//<br>// Depending on the HTTP client software, HTTP protocol version, and<br>// any intermediaries between the client and the Go server, it may not<br>// be possible to read from the Request.Body after writing to the<br>// ResponseWriter. Cautious handlers should read the Request.Body<br>// first, and then reply.<br>//<br>// Except for reading the body, handlers should not modify the<br>// provided Request.<br>//<br>// If ServeHTTP panics, the server (the caller of ServeHTTP) assumes<br>// that the effect of the panic was isolated to the active request.<br>// It recovers the panic, logs a stack trace to the server error log,<br>// and either closes the network connection or sends an HTTP/2<br>// RST_STREAM, depending on the HTTP protocol. To abort a handler so<br>// the client sees an interrupted response but the server doesn&#39;t log<br>// an error, panic with the value ErrAbortHandler.<br>type Handler interface {<br> ServeHTTP(ResponseWriter, *Request)<br>}</pre><p>สังเกตว่า interface ของ Handler มีแค่ method เดียวคือ ServeHTTP หมายความว่าถ้าเราสร้าง struct ที่มี method ServeHTTP เราก็สามารถใส่ middleware ก่อนหรือหลังที่มันจะทำ function หลักได้</p><p>โดยเราจะสร้าง struct ที่ชื่อ Log เพื่อทำการ log ทุก request ที่ส่งเข้ามา</p><pre>type Log struct {<br> Handler http.Handler<br>}<br><br>func (l Log) ServeHTTP(w http.ResponseWriter, r *http.Request) {<br> start := time.Now()<br> l.Handler.ServeHTTP(w, r)<br> log.Printf(&quot;Server http middlware: %s %s %s %s&quot;, r.RemoteAddr, r.Method, r.URL, time.Since(start))<br>}</pre><p>สังเกตว่าใน struct ของ log จะมีการรับ field ที่ชื่อว่า Handler เพื่อนำมาใช้ใน middleware ของเรา</p><p>โดยใน method ServeHTTP ของ Log จะเห็นได้ว่ามีการเรียกใช้ Handler.ServeHTTP แล้วค่อยทำการแสดงค่าที่ทำการ log ไว้</p><p>เราสามารถเรียกใช้ Log ได้ดังนี้</p><pre>func main() {<br> mux := http.NewServeMux()<br> mux.HandleFunc(&quot;/hello&quot;, Hello)<br> mux.HandleFunc(&quot;/test&quot;, test)<br><br> logMux := Log{<br>  Handler: mux,<br> }<br><br> srv := http.Server{<br>  Addr:    &quot;:3000&quot;,<br>  Handler: logMux,<br> }<br> log.Println(&quot;Server up by port 3000&quot;)<br> log.Fatal(srv.ListenAndServe())<br>}</pre><p>สังเกตว่าเราได้ทำการแทนที่ mux ด้วย logMux เพื่อให้มันไปทำ method ใน logMux ก่อน แล้วค่อยไปทำใน function หลัก</p><h4>code เต็ม</h4><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;time&quot;<br>)<br><br>func Hello(w http.ResponseWriter, r *http.Request) {<br> w.Write([]byte(&quot;hello\n&quot;))<br> return<br>}<br>func test(w http.ResponseWriter, r *http.Request) {<br> w.Write([]byte(&quot;test\n&quot;))<br> return<br>}<br><br>type Log struct {<br> Handler http.Handler<br>}<br><br>func (l Log) ServeHTTP(w http.ResponseWriter, r *http.Request) {<br> start := time.Now()<br> l.Handler.ServeHTTP(w, r)<br> log.Printf(&quot;Server http middlware: %s %s %s %s&quot;, r.RemoteAddr, r.Method, r.URL, time.Since(start))<br>}<br><br>func main() {<br> mux := http.NewServeMux()<br> mux.HandleFunc(&quot;/hello&quot;, Hello)<br> mux.HandleFunc(&quot;/test&quot;, test)<br><br> logMux := Log{<br>  Handler: mux,<br> }<br><br> srv := http.Server{<br>  Addr:    &quot;:3000&quot;,<br>  Handler: logMux,<br> }<br> log.Println(&quot;Server up by port 3000&quot;)<br> log.Fatal(srv.ListenAndServe())<br>}</pre><h3><strong>Conclusion</strong></h3><p>ในการทำ middleware ใน golang นั้น เราจำเป็นต้องดู interface ของสิ่งที่เราเข้าไปแทนที่ แล้วค่อยเพิ่มส่วนที่เราอยากจะให้ทำ</p><p>นี่เป็น blog แรกๆของผม รู้สึกเขินๆที่ได้มาเขียน แต่ชอบมากที่ได้มา share knowledge กับเพื่อนๆ หลังจากนี้ผมจะเขียนลงเรื่อยๆครับ ฝากติดตามด้วยนะครับ 😙😙</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1ec2eef6277" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>