<?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 Kexin Lu on Medium]]></title>
        <description><![CDATA[Stories by Kexin Lu on Medium]]></description>
        <link>https://medium.com/@langhxs?source=rss-fa4435f59620------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*grO7_sdhByOUt4vB.</url>
            <title>Stories by Kexin Lu on Medium</title>
            <link>https://medium.com/@langhxs?source=rss-fa4435f59620------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:01:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@langhxs/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[Mount NAS SharedFolder to Linux with CIFS]]></title>
            <link>https://medium.com/@langhxs/mount-nas-sharedfolder-to-linux-with-cifs-6149e2d32dba?source=rss-fa4435f59620------2</link>
            <guid isPermaLink="false">https://medium.com/p/6149e2d32dba</guid>
            <category><![CDATA[network-drive]]></category>
            <category><![CDATA[cif]]></category>
            <category><![CDATA[nas]]></category>
            <category><![CDATA[synology]]></category>
            <dc:creator><![CDATA[Kexin Lu]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 19:18:35 GMT</pubDate>
            <atom:updated>2024-06-24T19:22:19.668Z</atom:updated>
            <content:encoded><![CDATA[<p>Mount NAS SharedFolder to linux with with SMB/CIFS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lKbE7EjtExgnyx93" /><figcaption>Photo by <a href="https://unsplash.com/@alexcpl?utm_source=medium&amp;utm_medium=referral">Alex Cheung</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As developers and system administrators, we often need to mount network-attached storage (NAS) to our local machines for easy access to shared files and resources. In this article I will walk you through the process of mounting a SharedDirecotry with CIFS.</p><h3>TL;DR</h3><ol><li>Enable SMB on NAS</li><li>Edit SharedFolder permission to allow your user’s write and read permission</li><li>Read, modify and execute <a href="https://github.com/KexinLu/KexinBash/blob/main/mount_nas_drive.sh">https://github.com/KexinLu/KexinBash/blob/main/mount_nas_drive.sh</a></li></ol><h3>IMPORTANT!!!</h3><p><strong>Always read the script you are going to execute, especially when it requires root privilege!!!</strong></p><h3>Preparation on NAS Side</h3><p>On NAS side, you need to enable <strong>SMB/CIFS</strong>. I will use Synology as an example.</p><p>Go to Control Panel</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*tNT_7SlYU6IB4EIwH-Uz2w.png" /></figure><p>Open File Services</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*LYeebD-M6pk9_zR1oPWndA.png" /></figure><p>Enable SMB service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r6cErYTrDeTRSWhCJQdVIA.png" /></figure><p>Next you need to Config your Shared Folder, let’s use this VideoAsset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FgGKOKaWexLccTd2TPT1mQ.png" /></figure><p>Right click on this folder and click Edit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*Y-cHR93frfVnS8p2bJdetg.png" /></figure><p>Under permissions tab, give the user you want to use to access this folder <strong>Read/Write</strong> permission and Save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*mS-u0wqwAvAzBWNqxidxvw.png" /></figure><h3>Linux Side</h3><p>We need to</p><ul><li>Installs cifs-utils if not already installed.</li><li>Creates the mount point directory.</li><li>Creates a credentials file to store NAS login details.</li><li>Backs up the existing fstab file.</li><li>Adds an entry to /etc/fstab to mount the NAS folder automatically.</li><li>Reloads the systemd daemon to apply the changes.</li></ul><p>The method I’m going to show you would only attempt to mount the NAS folder when you try to access the directory.</p><h3>Script</h3><p>This script is created for archlinux, if you are using other distro, you want to find the correct cifs util on your distro and use your package manager.</p><p>For example on Ubuntu apt-get install cifs-utils</p><pre>#!/bin/bash<br><br># This script will try to mount a folder on your NAS to a mount point you specify on Linux<br># It will:<br># 1. Attempt to install cifs-utils<br># 2. Create your mount point directory<br># 3. Create a new file at the credentials location you declared<br># 4. Add username and password to the credentials file created in step 3<br># 5. Backup your fstab file to ./fstab.bak<br># 6. Add an entry to /etc/fstab for the mount<br># 7. Reload the system daemon<br><br># Variables (Replace these with your actual values)<br>NAS_IP=&quot;192.168.***.***&quot;<br>SHARED_FOLDER=&quot;VideoAsset&quot;<br>MOUNT_POINT=&quot;/mnt/VideoAsset&quot;<br>USERNAME=&quot;your_username&quot;<br>GROUPNAME=&quot;your_main_group&quot;<br>CREDENTIALS_DIR=&quot;/etc/samba&quot;<br>CREDENTIALS_FILE=&quot;$CREDENTIALS_DIR/credentials&quot;<br>SYNOLOGY_USERNAME=&quot;your_nas_username&quot;<br>SYNOLOGY_PASSWORD=&quot;your_nas_password&quot;<br>DRYRUN=false<br><br># Parse command-line arguments<br>for arg in &quot;$@&quot;; do<br>  case $arg in<br>    --dryrun)<br>      DRYRUN=true<br>      shift<br>      ;;<br>    *)<br>      shift<br>      ;;<br>  esac<br>done<br><br># Function to execute commands with optional dry run<br>execute() {<br>  if [ &quot;$DRYRUN&quot; = true ]; then<br>    echo &quot;[DRY RUN] $@&quot;<br>  else<br>    eval &quot;$@&quot;<br>  fi<br>}<br><br># Check if running as root<br>if [ &quot;$DRYRUN&quot; = false ] &amp;&amp; [ &quot;$EUID&quot; -ne 0 ]; then<br>  echo &quot;Please run as root&quot;<br>  exit 1<br>fi<br><br># Install cifs-utils<br>echo &quot;Installing cifs-utils...&quot;<br>execute &quot;pacman -S --noconfirm cifs-utils&quot;<br><br># Create mount point<br>echo &quot;Creating mount point at $MOUNT_POINT...&quot;<br>execute &quot;mkdir -p $MOUNT_POINT&quot;<br><br># Create credentials file<br>echo &quot;Creating credentials file at $CREDENTIALS_FILE...&quot;<br>execute &quot;mkdir -p $CREDENTIALS_DIR&quot;<br>execute &quot;echo \&quot;username=$SYNOLOGY_USERNAME\&quot; &gt; $CREDENTIALS_FILE&quot;<br>execute &quot;echo \&quot;password=$SYNOLOGY_PASSWORD\&quot; &gt;&gt; $CREDENTIALS_FILE&quot;<br><br># Secure the credentials file<br>echo &quot;Securing the credentials file...&quot;<br>execute &quot;chmod 600 $CREDENTIALS_FILE&quot;<br><br># Back up fstab<br>echo &quot;Backing up fstab to ./fstab.bak&quot;<br>execute &quot;cp /etc/fstab ./fstab.bak&quot; <br><br># Add entry to /etc/fstab<br>FSTAB_ENTRY=&quot;//${NAS_IP}/${SHARED_FOLDER} ${MOUNT_POINT} cifs credentials=${CREDENTIALS_FILE},iocharset=utf8,uid=${USERNAME},gid=${GROUPNAME},file_mode=0770,dir_mode=0770,_netdev,x-systemd.automount 0 0&quot;<br>if ! grep -qxF &quot;$FSTAB_ENTRY&quot; /etc/fstab; then<br>  echo &quot;Entry does not exist, adding entry to /etc/fstab...&quot;<br>  execute &quot;echo -e &gt;&gt; /etc/fstab&quot;<br>  execute &quot;echo -e \&quot;$FSTAB_ENTRY\&quot; &gt;&gt; /etc/fstab&quot;<br>else<br>  echo &quot;Entry already exists in /etc/fstab&quot;<br>fi<br><br># Reload systemd daemon<br>echo &quot;Reloading systemd daemon...&quot;<br>execute &quot;systemctl daemon-reload&quot;<br><br>echo -e<br>echo -e &quot;credential: $CREDENTIALS_FILE&quot;<br>echo -e &quot;fstab: /etc/fstab&quot;<br>echo -e &quot;mount_point: $MOUNT_POINT&quot;<br>echo -e &quot;Finished, exiting...&quot;<br>echo -e &quot;You can reboot now&quot;<br>echo -e</pre><h3>Variables in this script</h3><pre>NAS_IP=&quot;192.168.***.***&quot;<br>SHARED_FOLDER=&quot;VideoAsset&quot;<br>MOUNT_POINT=&quot;/mnt/VideoAsset&quot;<br>USERNAME=&quot;your_username&quot;<br>GROUPNAME=&quot;your_main_group&quot;<br>CREDENTIALS_DIR=&quot;/etc/samba&quot;<br>CREDENTIALS_FILE=&quot;$CREDENTIALS_DIR/credentials&quot;<br>SYNOLOGY_USERNAME=&quot;your_nas_username&quot;<br>SYNOLOGY_PASSWORD=&quot;your_nas_password&quot;<br>DRYRUN=false</pre><p><strong>NAS_IP</strong>: the IP address of your NAS on your LAN. If using synology you can go to <a href="https://find.synology.com/">https://find.synology.com/</a></p><p><strong>SHARED_FOLDER</strong>: name of the NAS shared folder we want to use, in our case it’s VideoAsset</p><p><strong>MOUNT_POINT</strong>: where do you want to mount this folder to?</p><p><strong>USERNAME</strong> and <strong>GROUPNAME</strong>: on Linux, which user and group should own this mounted directory? You can use ‘id’ to find out</p><p><strong>CREDENTIAL_DIR</strong> and <strong>CREDENTIAL_FILE</strong>: on Linux, where do you want to store your NAS username and password. NOTE: This script will wipe that file and put new username and password in there</p><p><strong>SYNOLOGY_USERNAME</strong> and <strong>SYNOLOGY_PASSWORD</strong>: put your NAS username and NAS password here. I’d recommend creating a user specifically for fs mount.</p><p><strong>DRYRUN</strong>: this script takes the --dryrun arg, when set to true or --dryrun is present, nothing would actually happen, but script will print out the commands it is going to execute.</p><pre>Installing cifs-utils...<br>[DRY RUN] pacman -S --noconfirm cifs-utils<br>Creating mount point at /mnt/VideoAsset...<br>[DRY RUN] mkdir -p /mnt/VideoAsset<br>Creating credentials file at /etc/samba/credentials...<br>[DRY RUN] mkdir -p /etc/samba<br>[DRY RUN] echo &quot;username=your_nas_username&quot; &gt; /etc/samba/credentials<br>[DRY RUN] echo &quot;password=your_nas_password&quot; &gt;&gt; /etc/samba/credentials<br>Securing the credentials file...<br>[DRY RUN] chmod 600 /etc/samba/credentials<br>Backing up fstab to ./fstab.bak<br>[DRY RUN] cp /etc/fstab ./fstab.bak<br>Entry does not exist, adding entry to /etc/fstab...<br>[DRY RUN] echo -e &gt;&gt; /etc/fstab<br>[DRY RUN] echo -e &quot;//192.168.***.***/VideoAsset /mnt/VideoAsset cifs credentials=/etc/samba/credentials,iocharset=utf8,uid=your_username,gid=your_main_group,file_mode=0770,dir_mode=0770,_netdev,x-systemd.automount 0 0&quot; &gt;&gt; /etc/fstab<br>Reloading systemd daemon...<br>[DRY RUN] systemctl daemon-reload<br><br>credential: /etc/samba/credentials<br>fstab: /etc/fstab<br>mount_point: /mnt/VideoAsset<br>Finished, exiting...<br>You can reboot now</pre><h3>fstab<strong> entry</strong></h3><p>Let me elaborate on this fstab entry</p><pre>//192.168.*.*/VideoAsset /mnt/VideoAsset cifs credentials=/etc/samba/credentials,iocharset=utf8,uid=kexinlu,gid=kexinlu,file_mode=0770,dir_mode=0770,_netdev,x-systemd.automount 0 0</pre><p>//192.168.*.*/VideoAsset refer to the SharedFolder on your NAS</p><p>/mnt/VideoAsset is where you want to mount this SharedFolder to</p><p>cifs is the file system type to be mounted</p><p>credentials=/etc/samba/credentials is where you put your NAS username and password at</p><p>iocharset=utf8is the character set to be used for IO</p><p>uid=kexinlu is the owner of this mount</p><p>gid=kexinlu is the owner group of this mount</p><p>file_mode=0700 only the owner and group have read/write and execute.</p><p>dir_mode=0700 directories in this mounted share folder also only allow owner and group to read/write and execute</p><p>_netdev is an option to indicate the mount is a network device and should only be mounted when network is available</p><p>x-systemd.automount tells systemd to auto matically mount this filesystem when it is <strong>accessed</strong></p><p>0 0 are options for dump and fsck for dump, 0 means this filesystem should not be backedup when dump is called. second 0 means when booting, fsck should not check this filesystem.</p><h3>Finally</h3><p>Hope this article is helpful for your NAS adventure. Leave a like and share with people who need this. Happy Hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6149e2d32dba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang sliceedge cases]]></title>
            <link>https://medium.com/@langhxs/golang-sliceedge-cases-4557514eecef?source=rss-fa4435f59620------2</link>
            <guid isPermaLink="false">https://medium.com/p/4557514eecef</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[slice]]></category>
            <dc:creator><![CDATA[Kexin Lu]]></dc:creator>
            <pubDate>Sat, 02 Feb 2019 07:25:45 GMT</pubDate>
            <atom:updated>2022-01-15T05:51:19.144Z</atom:updated>
            <content:encoded><![CDATA[<h3>Slice in Go</h3><p>Did you change the underlying array unknowingly?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jru_EVVgi04rf3K1CQDWwQ.png" /></figure><p>Slice, one of the most important data structure every go programmer needs to utilize. One needs to understand slice in detail in order to avoid some of the “gotcha”s of slices.</p><h4>What is a slice?</h4><p>A slice describes a piece of an array.</p><p>A slice is a data structure consisting of the address of the first elements of the slice, length of its self and capacity of its self.</p><p>To help ourselves visualize a slice, we will use the following function to help us see the details of a slice.</p><pre>func printSlice(s []int) {<br> sh := (*reflect.SliceHeader)(unsafe.Pointer(&amp;s))<br> ptr := (*int)(unsafe.Pointer(sh.Data))</pre><pre>fmt.Println(&quot;==================  SLICE  ==================&quot;)<br> fmt.Printf(&quot;Content               : %v\n&quot;, s)<br> fmt.Printf(&quot;First Element Address : %p\n&quot;, s)<br> fmt.Printf(&quot;First Elemnt Value    : %v\n&quot;, *ptr)<br> fmt.Printf(&quot;Length                : %v\n&quot;, sh.Len)<br> fmt.Printf(&quot;Capacity              : %v\n&quot;, sh.Cap)<br> fmt.Println(&quot;==================SLICE END==================&quot;)</pre><pre>}</pre><p>Result looks like</p><pre>printSlice([]int{1, 2, 3, 4, 5, 6})<br>/**<br>==================  SLICE  ==================<br>Content               : [1 2 3 4 5 6]<br>First Element Address : 0x452000<br>First Element Value   : 1<br>Length                : 6<br>Capacity              : 6<br>==================SLICE END==================<br>**/</pre><h4>Why is Capacity important</h4><p>Array in Golang has fixed length, and slice uses Array to store data. Consider a intslice with a capacity of 3,[]int{2,5,7} The array underneath is a [3]int with 2,5,7 inside. When we use the built-in append function to put more elements into this slice, it has to get more space to store the new elements, thus resulting in the following actions</p><p>(1) the creation of a new array with more space</p><p>(2) copying elements from the old array to the new array</p><p>(3) tossing away the old array and point to the new array</p><p>Append uses an algorithm to calculate the size of the new array, but we are not going into the detail of this topic here.</p><p>When you have a slice with lots of data, adding beyond the capacity frequently is considered resource intensive, thus you want to give the slice a reasonable capacity.</p><h3>Creating slices from an array</h3><p>Consider this piece of code</p><pre>func demoCreation() {<br>    // Creating the array as basis<br>    arr := [5]int{1, 2, 3, 4, 5}</pre><pre>for i := 0; i &lt; len(arr); i++ {<br>          fmt.Printf(&quot;position: %v,value: %v, address: %v\n&quot;, i, arr[i], &amp;arr[i])<br>     }</pre><pre>s1 := arr[:]<br>    printSlice(&quot;S1&quot;, s1)</pre><pre>s2 := arr[1:3]<br>    printSlice(&quot;S2&quot;, s2)</pre><pre>s3 := arr[3:]<br>    printSlice(&quot;S3&quot;, s3)</pre><pre>s4 := arr[:4]<br>    printSlice(&quot;S4&quot;, s4)<br>}</pre><p>Result</p><pre>[1 2 3 4 5]<br>position: 0, value: 1, address: <strong><em>0x452000  &lt;-------------+---+</em></strong><br>position: 1, value: 2, address: <strong><em>0x452004   &lt;-----------+ |   </em></strong>|<br>position: 2, value: 3, address: 0x452008               <strong><em>| </em></strong>|   |<br>position: 3, value: 4, address: <strong><em>0x45200c   &lt;---------+ | |   </em></strong>|<br>position: 4, value: 5, address: 0x452010             | <strong><em>|</em></strong> |   |<br>================  SLICE S1 =================         | <strong><em>|</em></strong> |   |<br>Content               : [1 2 3 4 5]                  | <strong><em>|</em></strong> |   |<br>First Element Address : <strong><em>0x452000      ---------------+-+-+   </em></strong>|<br>First Element Value   : 1                            | <strong><em>|     </em></strong>|<br>Length                : 5                            | <strong><em>|     </em></strong>|<br>Capacity              : 5                            | <strong><em>|     </em></strong>|<br>===============  SLICE END   ===============         | <strong><em>|     </em></strong>|<br>================  SLICE S2 =================         | <strong><em>|     </em></strong>|<br>Content               : [2 3]                        | <strong><em>|     </em></strong>|<br>First Element Address : <strong><em>0x452004      ---------------+-+     </em></strong>|<br>First Element Value   : 2                            |       |<br>Length                : 2                            |       |<br>Capacity              : 4                            |       |<br>===============  SLICE END   ===============         |       |<br>================  SLICE S3 =================         |       |<br>Content               : [4 5]                        |       |<br>First Element Address : <strong><em>0x45200c     ----------------+       </em></strong>|<br>First Element Value   : 4                                    |<br>Length                : 2                                    |<br>Capacity              : 2                                    |<br>===============  SLICE END   ===============                 |<br>================  SLICE S4 =================                 |<br>Content               : [1 2 3 4]                            |<br>First Element Address : <strong><em>0x452000</em></strong>     <strong><em>-----------------------</em></strong>-+<br>First Element Value   : 1                                    <br>Length                : 4                                    <br>Capacity              : 5                                    <br>===============  SLICE END   ===============</pre><p>As you can see, the four slices above are pointing to the<strong> same array</strong>.</p><p>Capacity is capped at the <strong>length</strong> of the array <strong>minus</strong> the <strong>starting index</strong> of the slice.</p><p>There are several important questions when considering edge cases of slice</p><p>Q1: Would change one of the slices resulting in changes in another slice?</p><p>Q2: Does append function affect the original array?</p><p>Q3: What happens when we append over the capacity of a slice?</p><p>Q4: Does copied slice share the same array?</p><p>In the next section, we are going to find out the answers for all of the above.</p><p>Q1: Would change one of the slices resulting in changes in another slice?</p><p>Consider the following setup:</p><pre>func q1() {<br>// BEFORE<br>   arr := [4]int{3, 6, <strong><em>2</em></strong>, 22}<br>/**<br>[3 6 2 22]<br>position: 0, value: 3, address: 0x416020<br>position: 1, value: 6, address: 0x416024<br><strong><em>position: 2, value: 2, address: 0x416028</em></strong><br>position: 3, value: 22, address: 0x41602c<br>**/</pre><pre>s1 := arr[:3]<br>/**<br>================  SLICE S1 BEFORE =================<br>Content               : [3 6 <strong><em>2</em></strong>]<br>First Element Address : 0x416020<br>First Element Value   : 3<br>Length                : 3<br>Capacity              : 4<br>===============  SLICE END   ===============<br>**/<br>s2 := arr[3:]</pre><pre>printSlice(&quot;S1 BEFORE&quot;, s1)<br>/**<br>================  SLICE S2 BEFORE =================<br>Content               : [<strong><em>2</em></strong> 22]<br>First Element Address : 0x416028<br>First Element Value   : 2<br>Length                : 2<br>Capacity              : 2<br>===============  SLICE END   ===============<br>**/<br>// AFTER<br>   s1[2] = 99</pre><pre>/** The array becomes<br>[3 6 <strong><em>99</em></strong> 22]<br>position: 0, value: 3, address: 0x416020<br>position: 1, value: 6, address: 0x416024<br><strong><em>position: 2, value: 99, address: 0x416028</em></strong><br>position: 3, value: 22, address: 0x41602c</pre><pre>s1 becomes:<br>================  SLICE S1 AFTER =================<br>Content               : [3 6 <strong><em>99</em></strong>]<br>First Element Address : 0x416020<br>First Element Value   : 3<br>Length                : 3<br>Capacity              : 4<br>===============  SLICE END   ===============</pre><pre>s2 becomes:<br>================  SLICE S2 AFTER =================<br>Content               : [<strong><em>99</em></strong> 22]<br>First Element Address : 0x416028<br>First Element Value   : 99<br>Length                : 2<br>Capacity              : 2<br>===============  SLICE END   ===============<br>**/<br>}</pre><p>Thus the Answer is: Changing one slice will modify other slices sharing the same array, and will modify the array underneath.</p><h4>Q2: Does append function affect the original array?</h4><p>Appending’s behavior is quite interesting.</p><h4>Q2 Part1:</h4><pre>func q2part1() {</pre><p>Create an array with 2, 4, 6, 8, 10, 12</p><pre>arr := [6]int{2, 4, 6, 8, 10, 12}<br>s1 := arr[1:5]<br>s2 := arr[:3]<br> <br>printArray(arr[:])<br>printSlice(&quot;S1 BEFORE&quot;, s1)<br>printSlice(&quot;S2 BEFORE&quot;, s2)<br>================  ARRAY START =================<br>[2 4 6 8 10 12]<br>position: 0, value: 2, address: 0x456000<br>position: 1, value: 4, address: 0x456004<br>position: 2, value: 6, address: 0x456008<br>position: 3, value: 8, address: 0x45600c<br>position: 4, value: 10, address: 0x456010<br>position: 5, value: 12, address: 0x456014<br>================  ARRAY END =================<br>================  SLICE S1 BEFORE =================<br>Content               : [4 6 8 10]<br>First Element Address : 0x456004<br>First Element Value   : 4<br>Length                : 4<br>Capacity              : 5<br>===============  SLICE END   ===============<br>================  SLICE S2 BEFORE =================<br>Content               : [2 4 6]<br>First Element Address : 0x456000<br>First Element Value   : 2<br>Length                : 3<br>Capacity              : 6<br>===============  SLICE END   ===============</pre><p>Now append to s2, but assign the value to s3</p><p>s3 := append(s2, 100)</p><pre>printSlice(&quot;S1 AFTER&quot;, s1)<br>printSlice(&quot;S2 AFTER&quot;, s2)<br>printSlice(&quot;S3&quot;, s3)<br>printArray(arr[:])</pre><pre>================  SLICE S1 AFTER =================<br>Content               : [4 6 <strong><em>100</em></strong> 10] // <strong>CHANGED</strong><br>First Element Address : 0x456004<br>First Element Value   : 4<br>Length                : 4<br>Capacity              : 5<br>===============  SLICE END   ===============<br>================  SLICE S2 AFTER =================<br>Content               : [2 4 6]<br>First Element Address : 0x456000<br>First Element Value   : 2<br>Length                : 3<br>Capacity              : 6<br>===============  SLICE END   ===============<br>================  SLICE S3 =================<br>Content               : [2 4 6 <strong><em>100</em></strong>] // <strong>CHANGED</strong><br>First Element Address : 0x456000<br>First Element Value   : 2<br>Length                : 4<br>Capacity              : 6<br>===============  SLICE END   ===============<br>================  ARRAY START =================<br>[2 4 6 100 10 12]<br>position: 0, value: 2, address: 0x456000<br>position: 1, value: 4, address: 0x456004<br>position: 2, value: 6, address: 0x456008<br><strong><em>position: 3, value: 100, address: 0x45600c   </em></strong>// <strong>CHANGED</strong><br>position: 4, value: 10, address: 0x456010<br>position: 5, value: 12, address: 0x456014<br>================  ARRAY END =================</pre><h4>Q2 Part2:</h4><p>What happens when we assign the result of the append to s2 itself?</p><pre>arr := [6]int{2, 4, 6, 8, 10, 12}<br>s1 := arr[1:5]<br>s2 := arr[:3]<br> <br>printArray(arr[:])<br>printSlice(&quot;S1 BEFORE&quot;, s1)<br>printSlice(&quot;S2 BEFORE&quot;, s2)</pre><pre>================  ARRAY START =================<br>[2 4 6 8 10 12]<br>position: 0, value: 2, address: 0x452000<br>position: 1, value: 4, address: 0x452004<br>position: 2, value: 6, address: 0x452008<br>position: 3, value: 8, address: 0x45200c<br>position: 4, value: 10, address: 0x452010<br>position: 5, value: 12, address: 0x452014<br>================  ARRAY END =================<br>================  SLICE S1 BEFORE =================<br>Content               : [4 6 8 10]<br>First Element Address : 0x452004<br>First Element Value   : 4<br>Length                : 4<br>Capacity              : 5<br>===============  SLICE END   ===============<br>================  SLICE S2 BEFORE =================<br>Content               : [2 4 6]<br>First Element Address : 0x452000<br>First Element Value   : 2<br>Length                : 3<br>Capacity              : 6<br>===============  SLICE END   ===============</pre><p>Result</p><pre>s2 = append(s2, 100)</pre><pre>printSlice(&quot;S1 AFTER&quot;, s1)<br>printSlice(&quot;S2 AFTER&quot;, s2)<br>printArray(arr[:])<br>================  SLICE S1 AFTER =================<br>Content               : [4 6 <strong><em>100</em></strong> 10] // <strong>CHANGED</strong><br>First Element Address : 0x452004<br>First Element Value   : 4<br>Length                : 4<br>Capacity              : 5<br>===============  SLICE END   ===============<br>================  SLICE S2 AFTER =================<br>Content               : [2 4 6 <strong><em>100</em></strong>] // <strong>CHANGED</strong><br>First Element Address : 0x452000<br>First Element Value   : 2<br>Length                : 4<br>Capacity              : 6<br>===============  SLICE END   ===============<br>================  ARRAY START =================<br>[2 4 6 100 10 12]<br>position: 0, value: 2, address: 0x452000<br>position: 1, value: 4, address: 0x452004<br>position: 2, value: 6, address: 0x452008<br><strong><em>position: 3, value: 100, address: 0x45200c </em></strong>// <strong>CHANGED</strong><br>position: 4, value: 10, address: 0x452010<br>position: 5, value: 12, address: 0x452014<br>================  ARRAY END =================</pre><p>Therefore the answer to Q2 is, append will change the underneath array.</p><h4>Q3: What happens when we append over the capacity of a slice?</h4><pre>//SETUP<br>arr := [5]int{2, 3, 4, 5, 6}</pre><pre>s1 := arr[:4]<br>s2 := arr[:]</pre><pre>printArray(arr[:])<br>printSlice(&quot;S1 BEFORE&quot;, s1)<br>printSlice(&quot;S2 BEFORE&quot;, s2)<br>================  ARRAY START =================<br>[2 3 4 5 6]<br><strong><em>position: 0, value: 2, address: 0x454000 &lt;---------------+</em></strong><br>position: 1, value: 3, address: 0x454004                 |<br>position: 2, value: 4, address: 0x454008                 |<br>position: 3, value: 5, address: 0x45400c                 |<br>position: 4, value: 6, address: 0x454010                 |<br>================  ARRAY END ================             |<br>================  SLICE S1 =================             |<br>Content               : [2 3 4 5]                        |<br><strong><em>First Element Address : 0x454000        &lt;----------------+</em></strong><br>First Element Value   : 2                                |<br>Length                : 4                                |<br>Capacity              : 5                                |<br>===============  SLICE END   ===============             |<br>================  SLICE S2 =================             |<br>Content               : [2 3 4 5 6]                      |<br><strong><em>First Element Address : 0x454000        &lt;----------------+</em></strong><br>First Element Value   : 2<br>Length                : 5<br>Capacity              : 5<br>===============  SLICE END   ===============</pre><p>Notice two slice share the same first element, thus we know they share the same array underneath.</p><p>Now let us try to append more element than the capacity is able to handle</p><h4>Q3 Part1:</h4><p>append to s2 but assign the value to s3</p><p>s3 = append(s2, 2, 3)</p><pre>printSlice(&quot;S1 AFTER&quot;, s1)<br>================  SLICE S1 AFTER =================<br>Content               : [2 3 4 5]<br><strong><em>First Element Address : 0x454000</em></strong><br>First Element Value   : 2<br>Length                : 4<br>Capacity              : 5<br>===============  SLICE END   ===============</pre><pre>printSlice(&quot;S2 AFTER&quot;, s2)<br>================  SLICE S2 AFTER =================<br>Content               : [2 3 4 5 6]<br><strong><em>First Element Address : 0x454000</em></strong><br>First Element Value   : 2<br>Length                : 5<br>Capacity              : 5<br>===============  SLICE END   ===============</pre><pre>printSlice(&quot;S3&quot;, s3)<br>================  SLICE S3 =================<br>Content               : [2 3 4 5 6 2 3]<br><strong><em>First Element Address : 0x44c060     // NOT USING THEORIGINAL ARRAY </em></strong><br>First Element Value   : 2<br>Length                : 7<br>Capacity              : 12<br>===============  SLICE END   ===============</pre><p>As you can see s3 is using a different array from s1 and s2</p><p>Q3Part2:</p><p>What happens when we assign the value to s2?</p><pre>arr := [5]int{2, 3, 4, 5, 6}<br>s1 := arr[:4]<br>s2 := arr[:]<br>-----------------------------BEFORE--------------------------------<br>================  ARRAY START =================<br>[2 3 4 5 6]<br><strong><em>position: 0, value: 2, address: 0x454000</em></strong><br>position: 1, value: 3, address: 0x454004<br>position: 2, value: 4, address: 0x454008<br>position: 3, value: 5, address: 0x45400c<br>position: 4, value: 6, address: 0x454010<br>================  ARRAY END =================<br>================  SLICE S1 =================<br>Content               : [2 3 4 5]<br><strong><em>First Element Address : 0x454000</em></strong><br>First Element Value   : 2<br>Length                : 4<br>Capacity              : 5<br>===============  SLICE END   ===============<br>================  SLICE S2 =================<br>Content               : [2 3 4 5 6]<br><strong><em>First Element Address : 0x454000</em></strong><br>First Element Value   : 2<br>Length                : 5<br>Capacity              : 5<br>===============  SLICE END   ===============<br>----------------------------BEFORE----------------------------------</pre><pre>s2 = append(s2, 2,3)<br>------------------------------AFTER---------------------------------<br>================  SLICE S1 AFTER =================<br>Content               : [2 3 4 5]<br><strong><em>First Element Address : 0x454000</em></strong><br>First Element Value   : 2<br>Length                : 4<br>Capacity              : 5<br>===============  SLICE END   ===============<br>================  SLICE S2 AFTER =================<br>Content               : [2 3 4 5 6 2 3]<br><strong><em>First Element Address : 0x44c060    // NOT USING THE ORIGINAL ARRAY</em></strong><br>First Element Value   : 2<br>Length                : 7<br>Capacity              : 12<br>===============  SLICE END   ===============<br>------------------------------END-----------------------------------</pre><p>as you can see s2’s array changed</p><p>So the answer is: when appending if the variable we are trying to assign to has less capacity, the array underneath will be replaced.</p><p><strong>Q4: Does copied slice share the same array?</strong></p><pre>func q4() {<br>  arr := [3]int{1, 2, 3}</pre><pre>s1 := arr[:]<br>  s2 := make([]int, len(s1))<br>  copy(s2, s1)</pre><pre>printSlice(&quot;S1&quot;, s1)<br>  printSlice(&quot;S2&quot;, s2)<br>}<br>================  ARRAY START =================<br>[1 2 3]<br><strong><em>position: 0, value: 1, address: 0x416020</em></strong><br>position: 1, value: 2, address: 0x416024<br>position: 2, value: 3, address: 0x416028<br>================  ARRAY END =================<br>================  SLICE S1 =================<br>Content               : [1 2 3]<br><strong><em>First Element Address : 0x416020</em></strong><br>First Element Value   : 1<br>Length                : 3<br>Capacity              : 3<br>===============  SLICE END   ===============<br>================  SLICE S2 =================<br>Content               : [1 2 3]<br><strong><em>First Element Address : 0x416050     //NOT IN ORIGINAL ARRAY!</em></strong><br>First Element Value   : 1<br>Length                : 3<br>Capacity              : 3<br>===============  SLICE END   ===============</pre><p>Since the first element for s2 is not in the initial array, we know it’s using another array underneath.</p><p>Link for the golang playground:</p><p><a href="https://play.golang.org/p/3QzfxFT0Kzp">The Go Playground</a></p><p>References:</p><ul><li><a href="https://stackoverflow.com/questions/36706843/how-to-get-the-underlying-array-of-a-slice-in-go">How to get the underlying array of a slice in Go?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4557514eecef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GoLang Customized JSON Serialization in Web API]]></title>
            <link>https://medium.com/@langhxs/golang-customized-json-serialization-in-web-api-ae2d106e0041?source=rss-fa4435f59620------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae2d106e0041</guid>
            <category><![CDATA[echo]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Kexin Lu]]></dc:creator>
            <pubDate>Tue, 10 Jul 2018 19:34:06 GMT</pubDate>
            <atom:updated>2019-01-30T16:30:59.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IsR6vrUo7ICW-YNp" /><figcaption>Photo by <a href="https://unsplash.com/@dominik_photography?utm_source=medium&amp;utm_medium=referral">Dominik Vanyi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the world of web API development, it is quite often that we have to deal with JSON representation of Data. Put this in the context of GoLang, you are looking at marshaling and unmarshalling of structs. In this article, we are going to walk through a simple CRUD API example with a typical setup for Enum and finally custom JSON serialization.</p><p>We are going to use a minimalist framework Echo for the API so that the skills you acquired in this article can be applied to write a small API.</p><pre>go get github.com/labstack/echo</pre><p>This API will handle the CRUD of workers. Worker struct will have Name(string), Age(int), Type(WorkerType) and OnboardDate(time.Time). We will use int and iota for WorkerType but the JSON representation of the struct will have a string field ‘worker-type’.</p><h3>Setting Up Basic CRUD API</h3><p>This CRUD example is a CC of Echo’s documentation, you can find it here.</p><p><a href="https://echo.labstack.com/cookbook/crud">https://echo.labstack.com/cookbook/crud</a></p><ol><li>Imports</li></ol><pre><strong>package </strong>main</pre><pre><strong>import </strong>(<br>   &quot;net/http&quot;<br>   &quot;strconv&quot;</pre><pre>   &quot;github.com/labstack/echo&quot;<br>)</pre><p>“net/http” package is used for HTTP status</p><p>“strconv” is used for parsing string to int</p><p>“echo” is the framework</p><p>2. Entity and In-memory Repository(map[int]*Worker)</p><pre><strong>type </strong>Worker <strong>struct </strong>{<br>   ID   int    `json:&quot;id&quot;`<br>   Name string `json:&quot;name&quot;`<br>   Age  int    `json:&quot;age&quot;`<br>}</pre><pre><strong>var </strong>(<br>   Workers = <strong>map</strong>[int]*Worker{}<br>   seq   = 1<br>)</pre><p>3. CRUD</p><pre><strong>func </strong>createWorker(c echo.Context) error {<br>   u := &amp;Worker{<br>      ID: seq,<br>   }<br>   <strong>if </strong>err := c.Bind(u); err != nil {<br>      <strong>return </strong>err<br>   }<br>   Workers[u.ID] = u<br>   seq++<br>   <strong>return </strong>c.JSON(http.<em>StatusCreated</em>, u)<br>}</pre><pre><strong>func </strong>getWorker(c echo.Context) error {<br>   id, _ := strconv.Atoi(c.Param(&quot;id&quot;))<br>   <strong>return </strong>c.JSON(http.<em>StatusOK</em>, Workers[id])<br>}</pre><pre><strong>func </strong>getWorkers(c echo.Context) error {<br>   <strong>return </strong>c.JSON(http.<em>StatusOK</em>, Workers)<br>}</pre><pre><strong>func </strong>updateWorker(c echo.Context) error {<br>   u := new(Worker)<br>   <strong>if </strong>err := c.Bind(u); err != nil {<br>      <strong>return </strong>err<br>   }<br>   id, _ := strconv.Atoi(c.Param(&quot;id&quot;))<br>   Workers[id].Name = u.Name<br>   <strong>return </strong>c.JSON(http.<em>StatusOK</em>, Workers[id])<br>}</pre><pre><strong>func </strong>deleteWorker(c echo.Context) error {<br>   id, _ := strconv.Atoi(c.Param(&quot;id&quot;))<br>   delete(Workers, id)<br>   <strong>return </strong>c.NoContent(http.<em>StatusNoContent</em>)<br>}</pre><p>4. Main</p><pre><strong>func </strong>main() {<br>   e := echo.New()</pre><pre>   // Routes<br>   e.POST(&quot;/workers&quot;, createWorker)<br>   e.GET(&quot;/workers/:id&quot;, getWorker)<br>   e.GET(&quot;/workers&quot;, getWorkers)<br>   e.PUT(&quot;/workers/:id&quot;, updateWorker)<br>   e.DELETE(&quot;/workers/:id&quot;, deleteWorker)</pre><pre>   // Start server<br>   e.Logger.Fatal(e.Start(&quot;:8080&quot;))<br>}</pre><p>5. Test it out</p><pre>go run main.go</pre><p>Post a Worker</p><pre>curl -X POST \<br>  <a href="http://localhost:8080/workers">http://localhost:8080/workers</a> \<br>  -H &#39;content-type: application/json&#39; \<br>  -d &#39;{<br>     &quot;name&quot;: &quot;sunny&quot;,<br>     &quot;age&quot;: 50<br>   }&#39;</pre><p>Result</p><pre>{<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;sunny&quot;,<br>    &quot;age&quot;: 50<br>}</pre><p>GetWorkers</p><pre>curl -X GET \<br>  <a href="http://localhost:8080/workers">http://localhost:8080/workers</a> \<br>  -H &#39;content-type: application/json&#39; \<br>  -d &#39;{<br>    &quot;name&quot;: &quot;sunny&quot;,<br>    &quot;age&quot;: 50<br>  }&#39;</pre><p>Result</p><pre>{<br>    &quot;1&quot;: {<br>        &quot;id&quot;: 1,<br>        &quot;name&quot;: &quot;sunny&quot;,<br>        &quot;age&quot;: 50<br>    }<br>}</pre><h3>Adding Worker Type Enum</h3><ul><li>A very good article by Inanc Gumus <a href="https://blog.learngoprogramming.com/golang-const-type-enums-iota-bc4befd096d3">https://blog.learngoprogramming.com/golang-const-type-enums-iota-bc4befd096d3</a></li><li>Another good example for Enum in GoLang is time. Weekday</li></ul><ol><li>Setup WorkerType as int and iota</li></ol><pre><strong>type </strong>WorkerType int</pre><pre><strong>const </strong>(<br>   <em>Unknown </em>= <em>iota<br>   IronWorker<br>   MechanicalWorker<br>   OilWorker<br></em>)</pre><p>2. Adding WorkerType to Worker struct</p><pre><strong>type </strong>Worker <strong>struct </strong>{<br>   ID   int        `json:&quot;id&quot;`<br>   Name string     `json:&quot;name&quot;`<br>   Age  int        `json:&quot;age&quot;`<br>   Type WorkerType `json:&quot;worker_type&quot;`<br>}</pre><p>Now our request body becomes</p><pre>{<br>    &quot;name&quot;: &quot;sunny&quot;,<br>    &quot;age&quot;: 50,<br>    &quot;worker_type&quot;: 1<br>}</pre><p>And the response becomes</p><pre>{<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;sunny&quot;,<br>    &quot;age&quot;: 50,<br>    &quot;worker_type&quot;: 1<br>}</pre><p>This fulfills our requirement of using enum; however, the number 1 in the above JSON doesn’t provide much information about the actual worker type to the reader, and you have to keep API and UI to agree upon the number to use for each worker type. We can do better with a trick. In the next section, we are going to make our API accepting string type for worker_type, but once the data is unmarshalled, it’s worker_type will be converted to our enum type.</p><h3>Customize JSON serialization for Worker</h3><p>1. Echo’s defaultBinder actually utilizes two methods from Unmarshaler and Marshaler interface, thus json.marshal and json.unmarshal will give you the same result.</p><ul><li>MarshalJSON</li><li>UnmarshalJSON</li></ul><p>2. Setup String Method for WorkerType</p><pre><strong>func</strong>(wt WorkerType) String() string {<br>   names := [4]string{<br>      &quot;unknown&quot;,<br>      &quot;iron_worker&quot;,<br>      &quot;mechanical_worker&quot;,<br>      &quot;oil_worker&quot;,<br>   }</pre><pre>   <strong>if </strong>wt &lt; <em>Unknown </em>|| wt &gt; <em>OilWorker </em>{<br>      <strong>return </strong>&quot;unknown&quot;<br>   }</pre><pre>   <strong>return </strong>names[wt]<br>}</pre><p>3. Setup ParseFrom Method for WorkerType</p><pre><strong>func</strong>(wt *WorkerType) ParseFrom(src string) {<br>   nameWorkerTypeMap := <strong>map</strong>[string]WorkerType{<br>      &quot;unknown&quot;: <em>Unknown</em>,<br>      &quot;iron_worker&quot;: <em>IronWorker</em>,<br>      &quot;mechanical_worker&quot;: <em>MechanicalWorker</em>,<br>      &quot;oil_worker&quot;: <em>OilWorker</em>,<br>   }<br>   <strong>if </strong>val, exist := nameWorkerTypeMap[src]; exist {<br>      *wt = val<br>      <strong>return<br>   </strong>}</pre><pre>   *wt = <em>Unknown<br></em>}</pre><p>4. Using an auxiliary struct to change the JSON serialization</p><p>This method is explained in great detail by this article: <a href="http://choly.ca/post/go-json-marshalling/">http://choly.ca/post/go-json-marshalling/</a></p><pre><strong>type </strong>Alias Worker<br><strong>type </strong>AuxWorker <strong>struct </strong>{<br>   Type      string     `json:&quot;worker_type&quot;`<br>   *Alias<br>}</pre><pre><strong>func </strong>(m Worker) MarshalJSON() ([]byte, error) {<br>   <strong>return </strong>json.Marshal(<br>      &amp;AuxWorker{<br>         Type: m.Type.String(),<br>         Alias: (*Alias)(&amp;m),<br>      },<br>   )<br>}</pre><p>The GET method’s response now becomes</p><pre>{<br>    &quot;worker_type&quot;: &quot;iron_worker&quot;,<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;sunny&quot;,<br>    &quot;age&quot;: 50<br>}</pre><p>Unmarshall</p><pre><strong>func </strong>(m *Worker) UnmarshalJSON(data []byte) error {<br>   aux := AuxWorker{ Alias: (*Alias)(m)}<br>   <strong>if </strong>err := json.Unmarshal(data, &amp;aux); err != nil {<br>      <strong>return </strong>err<br>   }<br>   t := new(WorkerType)<br>   t.ParseFrom(aux.Type)<br>   m.Type = *t<br>   <strong>return </strong>nil<br>}</pre><p>And now you are able to send a POST request with the body shown below</p><pre>{<br>   &quot;name&quot;: &quot;tony&quot;,<br>   &quot;age&quot;: 20,<br>   &quot;worker_type&quot;: &quot;iron_worker&quot;<br>}</pre><h3>Finally, marshal and unmarshal time.Time</h3><p>By applying the same technique. Here’s our final draft where the date in JSON will show up in the form ****-**-** while keeping its time.Time type.</p><pre><strong>package </strong>main</pre><pre><strong>import </strong>(<br>   &quot;net/http&quot;<br>   &quot;strconv&quot;</pre><pre>   &quot;github.com/labstack/echo&quot;<br>   &quot;encoding/json&quot;<br>   &quot;fmt&quot;<br>   &quot;time&quot;<br>)</pre><pre><strong>type </strong>WorkerType int</pre><pre><strong>const </strong>(<br>   <em>Unknown </em>= <em>iota<br>   IronWorker<br>   MechanicalWorker<br>   OilWorker<br></em>)</pre><pre><strong>func</strong>(wt WorkerType) String() string {<br>   names := [4]string{<br>      &quot;unknown&quot;,<br>      &quot;iron_worker&quot;,<br>      &quot;mechanical_worker&quot;,<br>      &quot;oil_worker&quot;,<br>   }</pre><pre>   <strong>if </strong>wt &lt; <em>Unknown </em>|| wt &gt; <em>OilWorker </em>{<br>      <strong>return </strong>&quot;unknown&quot;<br>   }</pre><pre>   <strong>return </strong>names[wt]<br>}</pre><pre><strong>func</strong>(wt *WorkerType) ParseFrom(src string) {<br>   nameWorkerTypeMap := <strong>map</strong>[string]WorkerType{<br>      &quot;unknown&quot;: <em>Unknown</em>,<br>      &quot;iron_worker&quot;: <em>IronWorker</em>,<br>      &quot;mechanical_worker&quot;: <em>MechanicalWorker</em>,<br>      &quot;oil_worker&quot;: <em>OilWorker</em>,<br>   }<br>   <strong>if </strong>val, exist := nameWorkerTypeMap[src]; exist {<br>      *wt = val<br>      <strong>return<br>   </strong>}</pre><pre>   *wt = <em>Unknown<br></em>}</pre><pre><strong>type </strong>Worker <strong>struct </strong>{<br>   ID   int              `json:&quot;id&quot;`<br>   Name string           `json:&quot;name&quot;`<br>   Age  int              `json:&quot;age&quot;`<br>   Type WorkerType       `json:&quot;worker_type&quot;`<br>   OnBoardDate time.Time `json:&quot;-&quot;`<br>}</pre><pre><strong>type </strong>Alias Worker<br><strong>type </strong>AuxWorker <strong>struct </strong>{<br>   Type        string     `json:&quot;worker_type&quot;`<br>   OnBoardDate string     `json:&quot;on_board_date&quot;`<br>   *Alias<br>}</pre><pre><strong>func </strong>(m *Worker) MarshalJSON() ([]byte, error) {<br>   <strong>return </strong>json.Marshal(<br>      &amp;AuxWorker{<br>         Type: m.Type.String(),<br>         OnBoardDate: string([]rune(m.OnBoardDate.String())[0:10]),<br>         Alias: (*Alias)(m),<br>      },<br>   )<br>}</pre><pre><strong>func </strong>(m *Worker) UnmarshalJSON(data []byte) error {<br>   aux := AuxWorker{ Alias: (*Alias)(m)}<br>   <strong>if </strong>err := json.Unmarshal(data, &amp;aux); err != nil {<br>      <strong>return </strong>err<br>   }<br>   // WorkerType<br>   t := new(WorkerType)<br>   t.ParseFrom(aux.Type)<br>   m.Type = *t</pre><pre>   // OnBoardDate<br>   layout := &quot;2006-01-02&quot;<br>   <strong>if </strong>t, err := time.Parse(layout, aux.OnBoardDate); err != nil {<br>      <strong>return </strong>err<br>   } <strong>else </strong>{<br>      m.OnBoardDate = t<br>   }</pre><pre>   <strong>return </strong>nil<br>}</pre><pre><strong>var </strong>(<br>   Workers = <strong>map</strong>[int]*Worker{}<br>   seq   = 1<br>)</pre><pre><strong>func </strong>createWorker(c echo.Context) error {<br>   u := &amp;Worker{<br>      ID: seq,<br>   }<br>   <strong>if </strong>err := c.Bind(u); err != nil {<br>      <strong>return </strong>err<br>   }<br>   Workers[u.ID] = u<br>   seq++<br>   <strong>return </strong>c.JSON(http.<em>StatusCreated</em>, u)<br>}</pre><pre><strong>func </strong>getWorker(c echo.Context) error {<br>   id, _ := strconv.Atoi(c.Param(&quot;id&quot;))<br>   <strong>return </strong>c.JSON(http.<em>StatusOK</em>, Workers[id])<br>}</pre><pre><strong>func </strong>getWorkers(c echo.Context) error {<br>   fmt.Println(Workers[1])<br>   <strong>return </strong>c.JSON(http.<em>StatusOK</em>, Workers)<br>}</pre><pre><strong>func </strong>updateWorker(c echo.Context) error {<br>   u := new(Worker)<br>   <strong>if </strong>err := c.Bind(u); err != nil {<br>      <strong>return </strong>err<br>   }<br>   id, _ := strconv.Atoi(c.Param(&quot;id&quot;))<br>   Workers[id].Name = u.Name<br>   <strong>return </strong>c.JSON(http.<em>StatusOK</em>, Workers[id])<br>}</pre><pre><strong>func </strong>deleteWorker(c echo.Context) error {<br>   id, _ := strconv.Atoi(c.Param(&quot;id&quot;))<br>   delete(Workers, id)<br>   <strong>return </strong>c.NoContent(http.<em>StatusNoContent</em>)<br>}</pre><pre><strong>func </strong>main() {<br>   e := echo.New()</pre><pre>   // Routes<br>   e.POST(&quot;/workers&quot;, createWorker)<br>   e.GET(&quot;/workers/:id&quot;, getWorker)<br>   e.GET(&quot;/workers&quot;, getWorkers)<br>   e.PUT(&quot;/workers/:id&quot;, updateWorker)<br>   e.DELETE(&quot;/workers/:id&quot;, deleteWorker)</pre><pre>   // Start server<br>   e.Logger.Fatal(e.Start(&quot;:8080&quot;))<br>}</pre><h4>GET RESPONSE</h4><pre>{<br>    &quot;1&quot;: {<br>        &quot;worker_type&quot;: &quot;iron_worker&quot;,<br>        &quot;on_board_date&quot;: &quot;2016-01-05&quot;,<br>        &quot;id&quot;: 1,<br>        &quot;name&quot;: &quot;tony&quot;,<br>        &quot;age&quot;: 20<br>    }<br>}</pre><h4>POST BODY</h4><pre>{<br>   &quot;name&quot;: &quot;tony&quot;,<br>   &quot;age&quot;: 20,<br>   &quot;worker_type&quot;: &quot;iron_worker&quot;,<br>   &quot;on_board_date&quot;: &quot;2016-01-05&quot;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae2d106e0041" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>