<?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 Nguyễn Tường on Medium]]></title>
        <description><![CDATA[Stories by Nguyễn Tường on Medium]]></description>
        <link>https://medium.com/@nttuong58?source=rss-77ffddabcb9a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1GJhoRuMAVdNZ-RhyW4VJw.png</url>
            <title>Stories by Nguyễn Tường on Medium</title>
            <link>https://medium.com/@nttuong58?source=rss-77ffddabcb9a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:57:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nttuong58/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[Elasticsearch in a nutshell.]]></title>
            <link>https://medium.com/@nttuong58/elasticsearch-in-a-nutshell-86506438a29e?source=rss-77ffddabcb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/86506438a29e</guid>
            <dc:creator><![CDATA[Nguyễn Tường]]></dc:creator>
            <pubDate>Fri, 13 May 2022 09:53:01 GMT</pubDate>
            <atom:updated>2022-05-15T08:56:35.588Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will quickly introduce what ElasticSearch is and how useful it will be in your projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uz8mVZvSYSUN8igF52I1uw.png" /></figure><h3><strong>What is Elasticsearch ?</strong></h3><p>According to its official documentation, Elasticsearch is a distributed RESTful search and analytics engine designed to meet a countless number of use cases.</p><p>It is built on top of Apache Lucene and written in Java. It was formerly a scalable version of Luence open-source search framework and added the ability to horizontally scale Luence indices. Elasticsearch allows you to store, search data at blazingly fast speed by using index constructed based on documents. At its core, you can think of Elasticsearch as a server that can process JSON requests and give you back JSON data.</p><h3><strong>How ElasticSearch works</strong></h3><p>Some logical concepts:</p><p><strong>Documents:</strong> documents are the basic unit of information that are stored in JSON format and indexed in ElasticSearch. Documents are similar to rows in relational databases because both of the kinds represent some entity in real life.</p><p><strong>Indices: </strong>indices are collections of documents that have some mutual characteristics. Indices in Elasticsearch are similar to relation database ‘s schemas. Documents in an index are logically related.</p><p><strong>Inverted indices: </strong>inverted indices are real name of indices, which is the mechanism of how search engines work. Typically, its internal implementation is like that of HashMap.</p><p><strong>Clusters: </strong>a cluster is a group of one or more node instances that are connected together. The real power of an Elasticsearch cluster lies in the distribution of tasks, searching, and indexing, across all nodes in the cluster.</p><p><strong>Node: </strong>node is a single server that an instance of Elasticsearch runs on. A node stores data and contribute to searching ability of a cluster. There are 3 main types of node: <em>master node, data node, client node.</em></p><p><strong>Shards: </strong>Elasticsearch can divide the index into multiple pieces called <em>shards </em>or each index is composed of many many shards. Each shard is a fully functional and “independant” index that can be hosted on any node within a cluster.</p><p><strong>Replicas: </strong>Elasticsearch allows us to make one or more copies of index’s shards call <em>replica shards</em> or just <em>replicas. </em>Replicas provide redundant copies of your data to protect against hardware failure and increase capacity to serve read requests like searching or retrieving documents.</p><h3>The ELK Stack</h3><p><strong>Kibana:</strong> Kibana is a free and open user interface that lets you visualize your Elasticsearch data and navigate the Elastic Stack. It lets you visualize your Elasticsearch data and navigate the Elastic Stack. You can select the way you give shape to your data by starting with one question to find out where the interactive visualization will lead you.</p><p><strong>Logstash: </strong>Logstash is used to aggregate and process data and send it to Elasticsearch. It is an open-source, server-side data processing pipeline that ingests data from a multitude of sources simultaneously, transforms it, and then sends it to collect. It also transforms and prepares data regardless of format by identifying named fields to build structure, and transform them to converge on a common format.</p><p><strong>Beats: </strong>Beats is a collection of lightweight, single-purpose data shipping agents used to send data from hundreds or thousands of machines and systems to Logstash or Elasticsearch. Beats are great for gathering data as they can sit on your servers, with your containers, or deploy as functions then centralize data in Elasticsearch.</p><h3><strong>What is Elasticsearch used for ?</strong></h3><p><strong>Application search</strong> — — For applications that rely heavily on a search platform for the access, retrieval, and reporting of data.</p><p><strong>Website search</strong> — — Websites which store a lot of content find Elasticsearch a very useful tool for effective and accurate searches. It’s no surprise that Elasticsearch is steadily gaining ground in the site search domain sphere.</p><p><strong>Logging and log analytics</strong> — — As we’ve discussed, Elasticsearch is commonly used for ingesting and analyzing log data in near-real-time and in a scalable manner. It also provides important operational insights on log metrics to drive actions.</p><p><strong>Infrastructure metrics and container monitoring</strong> — — Many companies use the ELK stack to analyze various metrics. This may involve gathering data across several performance parameters that vary by use case.</p><p>Some big companies that use Elasticsearch: Netflix, Walmart, Ebay</p><h3>References</h3><ul><li><a href="https://www.knowi.com/blog/what-is-elastic-search/">https://www.knowi.com/blog/what-is-elastic-search/</a></li><li><a href="https://logz.io/blog/10-elasticsearch-concepts/">https://logz.io/blog/10-elasticsearch-concepts/</a></li><li><a href="https://www.elastic.co/fr/kibana/">https://www.elastic.co/fr/kibana/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86506438a29e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HAProxy in Go]]></title>
            <link>https://medium.com/@nttuong58/haproxy-in-go-2fb0b60a610d?source=rss-77ffddabcb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fb0b60a610d</guid>
            <dc:creator><![CDATA[Nguyễn Tường]]></dc:creator>
            <pubDate>Sun, 08 May 2022 03:28:00 GMT</pubDate>
            <atom:updated>2022-05-08T03:28:00.389Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my very first implementation of how to use HAProxy for Go web app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fb0b60a610d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is DNS ?]]></title>
            <link>https://medium.com/@nttuong58/what-is-dns-50c250e074e2?source=rss-77ffddabcb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/50c250e074e2</guid>
            <dc:creator><![CDATA[Nguyễn Tường]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 10:33:44 GMT</pubDate>
            <atom:updated>2022-04-17T10:33:44.367Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is DNS ?</h3><p><em>Domain Name System</em> is the phone book of Internet. Human accesses information online through domain names like <a href="http://www.google.com/">www.google.com</a> or <a href="http://www.facebook.com./">www.facebook.com.</a> Web browsers interact through IP (Internet Protocol) addresses. DNS translates domain names to IP addresses.</p><p>Devices which connects to internet has unique IP addresses, which other machines use to identify. DNS free people from memorizing long numeric IP Address such as IP V4 192.168.1.255 to simple human-readable domain name like youtube.com.</p><p>You can think of DNS as a phonebook on your phone where domain name is like your contact name and IP address is contact number.</p><p>In conclusion, DNS is important because it helps the clients find correct site to connect and without it we can not access any website at all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50c250e074e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go programming language]]></title>
            <link>https://medium.com/@nttuong58/go-programming-language-71dd6e75b5b8?source=rss-77ffddabcb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/71dd6e75b5b8</guid>
            <dc:creator><![CDATA[Nguyễn Tường]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 10:32:22 GMT</pubDate>
            <atom:updated>2022-04-17T10:32:22.528Z</atom:updated>
            <content:encoded><![CDATA[<p>Go (also known as <em>Golang</em>) is a general purpose, multi-paradigm programming language created by three engineers at Google. Go was publicly announced in 2009 and version 1.0 was released in 2012, from then on, it was maintained and released by open-source community.</p><p>Go is created to make programming compilation process faster. Moreover, it aims to be a static, high performance, easy-to-learn, easy-to-adapt language. Go’s icon is a gopher as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*zQyOr1QQ6Xsl2PwC.png" /></figure><p><em>Go ‘s icon as of 2022, credit: internet</em></p><p>Nowadays, Go is quite popular among developers, especially with DevOps community. According to Stack Overflow Developer Survey 2021, Go ranks 9th in list of highest paying programming language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/0*RxnizOtF0ax-QWqm.png" /></figure><p><em>Top highest paying programming language as of 2021, credit: Stack Overflow</em></p><p>Here are some famous projects that are written in Go:</p><ul><li>Docker</li><li>Kubernetes</li><li>CockroachDB</li><li>InfluxDB</li></ul><p>Companies that use Go in production:</p><ul><li>Google</li><li>Uber</li><li>Dropbox</li><li>Twitch</li></ul><p>Go has a rich set of standard libraries and more concise syntax than other programming language, making it ideal to handle large code base easier. Here is idiomatic Hello World program written in Go.</p><p>package main</p><p>import &quot;fmt&quot;<br>func main() {</p><p>fmt.Println(&quot;Hello World&quot;)</p><p>}</p><p>You can build a HTTP server without using any 3rd party libraries.</p><p>package main</p><p>import (</p><p>&quot;log&quot;</p><p>&quot;net/http&quot;</p><p>)</p><p>func main() {</p><p>mux := http.NewServeMux()</p><p>mux.HandleFunc(&quot;/&quot;, func(w http.ResponseWriter, r *http.Request) {</p><p>w.Write([]byte(&quot;Hello World\n&quot;))</p><p>})<br>err := http.ListenAndServe(&quot;:5000&quot;, mux)</p><p>log.Fatalln(err)</p><p>}</p><p>Save this snippet to a main.go file and store somewhere on your machine. After that, navigate to the folder containing the file, open a terminal and run:</p><p>$ go run main.go</p><p>Open another terminal and run</p><p>$ curl localhost:5000</p><p>Then you should see the message Hello World sent back.</p><p>All in all,</p><p>Pros of Go:</p><ul><li>Easy to learn, static language</li><li>Blazingly fast compiler</li><li>Concise syntax</li><li>High performance</li></ul><p>Cons of Go:</p><ul><li>Not a system language</li><li>Still need garbage collector</li></ul><h3>References</h3><p><a href="https://vi.wikipedia.org/wiki/Go_(ng%C3%B4n_ng%E1%BB%AF_l%E1%BA%ADp_tr%C3%ACnh)">https://vi.wikipedia.org/wiki/Go_(ng%C3%B4n_ng%E1%BB%AF_l%E1%BA%ADp_tr%C3%ACnh)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71dd6e75b5b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Redis in 5 minutes]]></title>
            <link>https://medium.com/@nttuong58/learn-redis-in-5-minutes-3b776d7648b?source=rss-77ffddabcb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b776d7648b</guid>
            <dc:creator><![CDATA[Nguyễn Tường]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 10:29:41 GMT</pubDate>
            <atom:updated>2022-04-17T10:29:41.119Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s learn some basics of how the world’s most popular in-memory database works</p><p>Redis stands for REmote DIctionary Server is an open-source, key-value in-memory database. Data in Redis is always loaded in RAM, making it so fast to access any piece of data within a tiny amount of time (usually millisecond). For this reason, it is usually used as cache-server.</p><h3>Install Redis</h3><p>Install Redis on Linux:</p><p>sudo snap install redis</p><p>Install redis on Mac:</p><p>brew install redis</p><h3>Basic operations</h3><p>When you have Redis installed installed on your machine, you can check if it is running by typing:</p><p>sudo systemctl status redis</p><p>If it is running then we can go to next step.</p><p>Run this command:</p><p>redis-cli</p><p>Now you should see this:</p><p>127.0.0.1:6379&gt;</p><p>If you don’t, then try to figure out what went wrong</p><p>You can use SET to set a key to a value. For example:</p><p>127.0.0.1:6379&gt; SET gopher <a href="http://www.rust-lang.org/">www.rust-lang.org</a></p><p>OK</p><p>And GET to retrieve the value of a key</p><p>127.0.0.1:6379&gt; GET gopher</p><p>“www.rust-lang.org”</p><p>Also, you can use MGET or MSET to reduce traffic for the database with any number of key-value pairs.</p><p>Use MSET to set a number of key-value pair</p><p>127.0.0.1:6379&gt; MSET gog www.google.com red <a href="http://www.reddit.com/">www.reddit.com</a></p><p>OK</p><p>Retriving values of those keys using MGET</p><p>127.0.0.1:6379&gt; MGET gog red</p><ol><li>“www.google.com”</li><li>“www.reddit.com”</li></ol><h3>Transactions</h3><p>Like some relational databases such as PostgreSQL, let’s walk through an example of how to begin and finish a transaction in Redis.</p><p>redis 127.0.0.1:6379&gt; MULTI</p><p>OK</p><p>redis 127.0.0.1:6379&gt; SET prag <a href="http://pragprog.com/">http://pragprog.com</a></p><p>QUEUED</p><p>redis 127.0.0.1:6379&gt; SET count 2</p><p>QUEUED</p><p>redis 127.0.0.1:6379&gt; INCR count</p><p>QUEUED</p><p>redis 127.0.0.1:6379&gt; EXEC</p><p>1) OK</p><p>2) (integer) 3</p><p>When using MULTI, the commands aren’t actually executed when we define them (similar to PostgreSQL). Instead, they are queued and then executed in sequence. Similar to ROLLBACK in SQL, you can stop a transaction with the DISCARD command, which will clear the transaction queue.</p><h3>Complex data types</h3><h4>Hashes:</h4><p>Hashes are like nested objects that can take any number of key-value pairs.</p><p>We can set keys and values of hash using regular MSET then retrieve them using regular MGET.</p><p>redis 127.0.0,1:6379&gt; MSET user:luc:name “Luc” user:luc:password s3cret</p><p>OK</p><p>redis 127.0.0.1&quot;:6379&gt; MGET user:luc:name user:luc:password</p><p>1) “Luc”</p><p>2) “s3cret”</p><p>Or using hash-specific functions:</p><p>redis 127.0.0.1:6379&gt; HMSET user:luc name Luc user:luc password s3cret</p><p>OK</p><p>Again retrieve them with HMGET:</p><p>redis 127.0.0.1:6379&gt; HMGET user:luc name password</p><p>1) “Luc”</p><p>2) “s3cret”</p><h4>Lists:</h4><p>Lists are used to store a number of items that are adjacent to each other (can have certain offset) in memory and have same data type. List can act both as stack or queue. Use RPUSH to add one more item at the end of a list,</p><p>redis 127.0.0,1:6379&gt; RPUSH mylist 7wks gog prag</p><p>( integer ) 3</p><p>Use LRANGE to retrive some or all items of a list. Items in list are have zero-based index.</p><p>redis 127.0.0.1:6379&gt; LRANGE mylist 0 -1</p><p>1) “7wks”</p><p>2) “gog”</p><p>3) “prag”</p><h4>Sets</h4><h4>References:</h4><ol><li>Seven Databases In Seven Weeks, Chapter 8</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b776d7648b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting to Redis in Go]]></title>
            <link>https://medium.com/@nttuong58/connecting-to-redis-in-go-7a4159f82110?source=rss-77ffddabcb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a4159f82110</guid>
            <dc:creator><![CDATA[Nguyễn Tường]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 10:27:19 GMT</pubDate>
            <atom:updated>2022-04-17T10:27:19.818Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous <a href="https://gopher5889.substack.com/p/learn-redis-database-in-5-minutes?s=w">post</a>, we have learned very very basic features in Redis. Let’s go through an example to see how use Redis in Go. For the Redis client in this example we will use <a href="http://github.com/go-redis/redis">github.com/go-redis/redis</a></p><h4>First we need to check if Redis is up and running on our local machine. Type following command on terminal:</h4><p>$ sudo systemctl status redis</p><p>● redis-server.service - Advanced key-value store</p><p>Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)</p><p>Active: active (running) since Wed 2022-03-30 05:53:06 +07; 4h 40min ago</p><p>Docs: <a href="http://redis.io/documentation,">http://redis.io/documentation,</a></p><p>man:redis-server(1)</p><p>Main PID: 813 (redis-server)</p><p>Tasks: 4 (limit: 14122)</p><p>Memory: 4.8M</p><p>CGroup: /system.slice/redis-server.service</p><p>└─813 /usr/bin/redis-server 127.0.0.1:6379</p><p>Thg 3 30 05:53:06 gopc systemd[1]: Starting Advanced key-value store...</p><p>Thg 3 30 05:53:06 gopc systemd[1]: redis-server.service: Can&#39;t open PID file /run/redis/redis-server.pid (yet?) after start: Operation not permitted</p><p>Thg 3 30 05:53:06 gopc systemd[1]: Started Advanced key-value store.</p><h4>If the we get a result same as above, we are ready to go to next step.</h4><p>Here is a sample Go snippet describing how to connect to local Redis:</p><p>rdb := redis.NewClient(&amp;redis.Options{</p><p>Addr: &quot;localhost:6379&quot;,</p><p>Password: &quot;&quot;,</p><p>DB: 0,</p><p>})</p><p>ctx := context.Background()<br> err := rdb.Set(ctx, &quot;7wks&quot;, &quot;http://www.sevenweeks.org/&quot;, 0).Err()</p><p>if err != nil {</p><p>panic(err)</p><p>}<br> val, err := rdb.Get(ctx, &quot;7wks&quot;).Result()</p><p>if err != nil {</p><p>panic(err)</p><p>}</p><p>fmt.Println(val)</p><p>Save the above snippet to file such as main.go, open a terminal and run:</p><p>$ go run main.go</p><p><a href="http://www.sevenweeks.org/">http://www.sevenweeks.org/</a></p><p>We have successfully add new key 7wks with value <a href="http://www.sevenweeks.org/">http://www.sevenweeks.org/</a></p><p>Set and get multiple key at once:</p><p>_, err := rdb.MSet(ctx, &quot;gog&quot;, &quot;http://google.com&quot;, &quot;ms&quot;, &quot;http://microsoft.com&quot;).Result()</p><p>if err != nil {</p><p>panic(err)</p><p>}</p><p>sliceCMD := rdb.MGet(ctx, &quot;gog&quot;, &quot;ms&quot;)</p><p>if sliceCMD.Err() != nil {</p><p>panic(sliceCMD.Err())</p><p>}</p><p>fmt.Println(sliceCMD.Val()...)</p><p>rdb.Set(ctx, &quot;count&quot;, 2, 0).Err()</p><p>Again save this and run:</p><p>$ go run main.go</p><p>http://google.com <a href="http://microsoft.com/">http://microsoft.com</a></p><h3>References:</h3><ol><li><a href="https://github.com/go-redis/redis">https://github.com/go-redis/redis</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a4159f82110" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL basics]]></title>
            <link>https://medium.com/@nttuong58/postgresql-basics-bc4ef499a914?source=rss-77ffddabcb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc4ef499a914</guid>
            <dc:creator><![CDATA[Nguyễn Tường]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 10:25:31 GMT</pubDate>
            <atom:updated>2022-04-17T10:25:31.364Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>According the official ‘s docs, PostgreSQL is the most advanced open-source database and its belongs to relational database category. But since version 9.3, it had been added support for NoSQL too. PostgreSQL also supports advanced data types and performance tuning features, which are only available in enterprise-class DBMS. PostgreSQL is now maintained by an active open-source community, which makes tremendous amount of effort to make it a reliable DBMS.</p><h3>How to install</h3><p>Depending on what platform you are in, go to the PostgreSQL ‘s official website and follow the installation steps.</p><h3>Advantages and disadvantages</h3><p><strong>Advantages:</strong></p><ul><li>Easy to use and set up</li><li>Open source</li><li>Support geographic objects</li><li>Can run dynamic websites and web apps as a LAMP stack option</li></ul><p><strong>Disadvantages:</strong></p><ul><li>There is a vast amount of competitors of PostgreSQL out there</li><li>PostgreSQL is not backed by a tech giant like in case of MS SQL</li><li>Many open-source apps support MySQL, but don’t support PostgreSQL</li><li>When it comes to performance, it is slower than MySQL</li></ul><h3>Applications of PostgreSQL</h3><ul><li>Financial industry</li><li>Government GIS data</li><li>Manufacturing</li><li>Scientific data</li></ul><h3>Set up PostgreSQL for first use</h3><p>By default, after a fresh installation of PostgreSQL on your machine, a super user named <em>postgres</em> will be created. Again, by default, PostgreSQL uses an authentication scheme called <em>peer authentication</em> for local machine. Peer authentication means that if the current operating system user’s username matches a valid PostgreSQL role name, they can log in into PostgreSQL without further authentication and there is no password needed.</p><p>You can check status of PostgreSQL by typing this command in terminal:</p><p>$ sudo systemctl status postgresql</p><p>If it is running, then go to next steps.</p><p>$ sudo su - postgres</p><p>$ psql</p><p>The terminal will transfer to PostgreSQL command prompt under <em>postgres</em> user</p><p>postgres=#</p><p>Use this command to change password of user postgres:</p><p>postgres=# ALTER USER postgres WITH PASSWORD ‘yourpassword’;</p><p>Then use sudo systemctl restart postgresql for the change to take effect.</p><h3>Connect to PostgreSQL in Go</h3><p>To connect to PostgreSQL in Go, we first need to install a database driver. The driver acts as a middle man to communicate between Go and PostgreSQL. There are many PostgreSQL for Go but in this example we will stick with github.com/lib/pq.</p><p>Data source name ( or connection string ) of PostgreSQL for local connection:</p><p>postgres://username:password@database@hostname/database</p><p>Code to connect to PostgreSQL in Go:</p><p>func openDB(dsn string) (*sql.DB, error) {</p><p>db, err := sql.Open(&quot;postgres&quot;, dsn)</p><p>if err != nil {</p><p>return nil, err</p><p>}</p><p>ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)</p><p>defer cancel()<br> err = db.PingContext(ctx)</p><p>if err != nil {</p><p>return nil, err</p><p>}<br> return db, nil</p><p>}</p><h3>Basic CRUD</h3><p>Suppose we have the following relation in database:</p><p>CREATE TABLE IF NOT EXISTS movies (</p><p>id bigserial PRIMARY KEY,</p><p>created_at timestamp(0) with time zone NOT NULL DEFAULT now(),</p><p>title text NOT NULL,</p><p>year integer NOT NULL,</p><p>runtime integer NOT NULL,</p><p>genres text[] NOT NULL,</p><p>version integer NOT NULL DEFAULT 1</p><p>);</p><p>and following Go struct:</p><p>type Movie struct {</p><p>ID int64 `json:&quot;id&quot;`</p><p>CreatedAt time.Time `json:&quot;-&quot;`</p><p>Title string `json:&quot;title&quot;`</p><p>Year int32 `json:&quot;year,omitempty&quot;`</p><p>Runtime Runtime `json:&quot;runtime,omitempty,string&quot;`</p><p>Genres []string `json:&quot;genres,omitempty&quot;`</p><p>Version int32 `json:&quot;version,omitempty&quot;`</p><p>}</p><p>Insert one new record to table Movie:</p><p>func (m MovieModel) Insert(movie *Movie) error {</p><p>query := `</p><p>INSERT INTO movies (title, year, runtime, genres)</p><p>VALUES ($1, $2, $3, $4)</p><p>RETURNING id, created_at, version</p><p>`</p><p>args := []interface{}{movie.Title, movie.Year, movie.Runtime, pq.Array(movie.Genres)}</p><p>return m.DB.QueryRow(query, args...).Scan(&amp;movie.ID, &amp;movie.CreatedAt, &amp;movie.Version)</p><p>}</p><p>Get movie by ID:</p><p>func (m MovieModel) Get(id int64) (*Movie, error) {</p><p>if id &lt; 1 {</p><p>return nil, ErrRecordNotFound</p><p>}</p><p>query := `</p><p>SELECT id, created_at, title, year, runtime, genres, version</p><p>FROM movies</p><p>WHERE id = $1</p><p>`</p><p>var movie Movie<br> err := m.DB.QueryRow(query, id).Scan(</p><p>&amp;movie.ID,</p><p>&amp;movie.CreatedAt,</p><p>&amp;movie.Title,</p><p>&amp;movie.Year,</p><p>&amp;movie.Runtime,</p><p>pq.Array(&amp;movie.Genres),</p><p>&amp;movie.Version,</p><p>)<br> if err != nil {</p><p>switch {</p><p>case errors.Is(err, sql.ErrNoRows):</p><p>return nil, ErrRecordNotFound</p><p>default:</p><p>return nil, err</p><p>}</p><p>}</p><p>return &amp;movie, nil</p><p>}</p><p>Update one movie by ID:</p><p>func (m MovieModel) Update(movie *Movie) error {</p><p>query := `</p><p>UPDATE movies</p><p>SET title = $1, year = $2, runtime = $3, genres = $4, version = version + 1</p><p>WHERE id = $5</p><p>RETURNING version</p><p>`</p><p>args := []interface{}{</p><p>movie.Title,</p><p>movie.Year,</p><p>movie.Runtime,</p><p>pq.Array(movie.Genres),</p><p>movie.ID,</p><p>}</p><p>return m.DB.QueryRow(query, args...).Scan(&amp;movie.Version)}</p><p>Delete one movie by ID:</p><p>func (m MovieModel) Delete(id int64) error {</p><p>if id &lt; 1 {</p><p>return ErrRecordNotFound</p><p>}</p><p>query := ` DELETE FROM movies WHERE id = $1 `<br> result, err := m.DB.Exec(query, id) if err != nil { return err }<br> rowsAffected, err := result.RowsAffected() if err != nil { return err }<br> if rowsAffected == 0 { return ErrRecordNotFound }<br> return nil}</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc4ef499a914" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing simple RESTful API with Go and Gin]]></title>
            <link>https://medium.com/@nttuong58/writing-simple-restful-api-with-go-and-gin-64be2c24e1aa?source=rss-77ffddabcb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/64be2c24e1aa</guid>
            <dc:creator><![CDATA[Nguyễn Tường]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 10:23:05 GMT</pubDate>
            <atom:updated>2022-04-17T10:23:05.974Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will demonstrate how to build a simple RESTful API in Go and Gin</p><p><strong>Table of contents:</strong></p><ol><li>Prerequisites</li><li>Design API endpoints</li><li>Design API endpoints</li><li>Design database models</li><li>Create folder for your project</li><li>Put them all together</li></ol><h3>1. Prerequisites</h3><ul><li><em>Go</em> version 1.12 or later installed on your machine</li><li>A code editor ( I prefer <em>Visual Studio Code</em> because its popularity among developers and it has many useful extensions)</li><li><em>curl</em> command already installed on your machine</li></ul><h3>2. Design API endpoints</h3><p>The application will have following endpoints:</p><p>/movies</p><ul><li>GET — fetch all movies</li><li>POST — create a movie</li></ul><p>/movies/:id</p><ul><li>GET — fetch a specific movie based on its ID</li><li>PUT — update a movie</li><li>DELETE — delete a movie</li></ul><p>Next, let’s create a folder for the application.</p><h3>3. Create a folder for the application</h3><p>If you are on Mac or Linux:</p><p>cd</p><p>mkdir your-project-name</p><p>If you are on Windows:</p><p>C:\Users\your_user_name&gt; mkdir your_project_name</p><h3>4. Design database model</h3><p>Our application logic will revolve around this one and only database model named <em>Movie</em></p><p>type Movie struct {</p><p>ID int `json:&quot;id&quot;`</p><p>Name string `json:&quot;name&quot;`</p><p>Year int `json:&quot;year&quot;`</p><p>Genres []string `json:&quot;genres&quot;`</p><p>Directors []string `json:&quot;directors&quot;`</p><p>Rating float64 `json:&quot;rating&quot;`</p><p>}</p><h3>5. Define the application‘s handlers</h3><ul><li>Get all movies handler</li><li>func GetAllMovies(ctx *gin.Context) {</li><li>ctx.IndentedJSON(http.StatusOK, movies)</li><li>}</li><li>Get one movie by id handler</li><li>func GetMovie(ctx *gin.Context) {</li><li>id := ctx.Param(&quot;id&quot;)</li><li>if id == &quot;&quot; {</li><li>return</li><li>}</li><li>for _, movie := range movies {</li><li>if id == movie.ID {</li><li>ctx.IndentedJSON(http.StatusOK, movie)</li><li>return</li><li>}</li><li>}</li><li>ctx.JSON(http.StatusOK, gin.H{&quot;error&quot;: fmt.Sprintf(&quot;movie with ID %s not found&quot;, id)})</li><li>}</li><li>Add new movie handler</li><li>func AddMovie(ctx *gin.Context) {</li><li>var m Movie</li><li>err := ctx.ShouldBindJSON(&amp;m)</li><li>if err != nil {</li><li>ctx.Writer.WriteHeader(http.StatusBadRequest)</li><li>ctx.Writer.Write([]byte(&quot;missing info or malformed request&quot;))</li><li>return</li><li>}</li><li>movies = append(movies, m)</li><li>}</li><li>Delete movie handler</li><li>func DeleteMovie(ctx *gin.Context) {</li><li>id := ctx.Param(&quot;id&quot;)</li><li>if id == &quot;&quot; {</li><li>ctx.AbortWithStatusJSON(http.StatusNotFound,</li><li>gin.H{</li><li>&quot;message&quot;: fmt.Sprintf(&quot;movie ID: %s not found&quot;, id)})</li><li>return</li><li>}</li><li>for i, movie := range movies {</li><li>if id == movie.ID {</li><li>movies = append(movies[:i], movies[i+1:]...) return</li><li>}</li><li>}</li><li>}</li><li>Update movie handler</li><li>func UpdateMovie(ctx *gin.Context) {</li><li>var m Movie</li><li>err := ctx.ShouldBindJSON(&amp;m)</li><li>if err != nil {</li><li>ctx.AbortWithStatusJSON(</li><li>http.StatusBadRequest,</li><li>gin.H {</li><li>&quot;message&quot;: &quot;json malformed&quot;,</li><li>})</li><li>return</li><li>}</li><li>for _, movie := range movies {</li><li>if m.ID == movie.ID {</li><li>movie.Name = m.Name</li><li>movie.Year = m.Year</li><li>movie.Genres = m.Genres</li><li>movie.Directors = m.Directors</li><li>movie.Rating = m.Rating</li><li>return</li><li>}</li><li>}</li><li>}</li></ul><h3>6. Put it all together</h3><p>Put all the code we have written so far together</p><p><a href="https://yamcode.com/untitled-59798">main.go</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64be2c24e1aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a DNS server in Go]]></title>
            <link>https://medium.com/@nttuong58/writing-a-dns-server-in-go-cc8f1ab6edc8?source=rss-77ffddabcb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc8f1ab6edc8</guid>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[Nguyễn Tường]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 10:19:25 GMT</pubDate>
            <atom:updated>2022-04-17T10:19:25.980Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple DNS server written in Go. It uses package github.com/miekg/dns. The following DNS knows how to answer A queries and it only knows IP address of two domains.</p><p>package main</p><p>import (</p><p>&quot;net&quot;</p><p>&quot;strconv&quot;</p><p>&quot;log&quot;</p><p>&quot;github.com/miekg/dns&quot;</p><p>)</p><p>var domainsToAddresses = map[string]string{</p><p>&quot;google.com.&quot;: &quot;1.2.3.4&quot;,</p><p>&quot;jameshfisher.com.&quot;: &quot;104.198.14.52&quot;,</p><p>}</p><p>type handler struct{}</p><p>func (this *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {</p><p>msg := dns.Msg{}</p><p>msg.SetReply(r)</p><p>switch r.Question[0].Qtype {</p><p>case dns.TypeA:</p><p>msg.Authoritative = true</p><p>domain := msg.Question[0].Name</p><p>address, ok := domainsToAddresses[domain]</p><p>if ok {</p><p>msg.Answer = append(msg.Answer, &amp;dns.A{ Hdr: dns.RR_Header{ Name: domain, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60 },</p><p>A: net.ParseIP(address),</p><p>})</p><p>}</p><p>}</p><p>w.WriteMsg(&amp;msg)</p><p>}</p><p>func main() {</p><p>srv := &amp;dns.Server{Addr: &quot;:&quot; + strconv.Itoa(8000), Net: &quot;udp&quot;}</p><p>srv.Handler = &amp;handler{}</p><p>if err := srv.ListenAndServe(); err != nil {</p><p>log.Fatalf(&quot;Failed to set udp listener %s\n&quot;, err.Error())</p><p>}</p><p>}</p><p>$ dig @127.0.0.1 -p 8000 google.com</p><p>; &lt;&lt;&gt;&gt; DiG 9.16.1-Ubuntu &lt;&lt;&gt;&gt; @127.0.0.1 -p 8000 google.com</p><p>; (1 server found)</p><p>;; global options: +cmd</p><p>;; Got answer:</p><p>;; -&gt;&gt;HEADER&lt;&lt;- opcode: QUERY, status: NOERROR, id: 64611</p><p>;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0</p><p>;; WARNING: recursion requested but not available</p><p>;; QUESTION SECTION:</p><p>;google.com. IN A</p><p>;; ANSWER SECTION:</p><p>google.com. 60 IN A 1.2.3.4</p><p>;; Query time: 0 msec</p><p>;; SERVER: 127.0.0.1#8000(127.0.0.1)</p><p>;; WHEN: T3 Thg 3 29 16:11:54 +07 2022</p><p>;; MSG SIZE rcvd: 54</p><p>$ dig @127.0.0.1 -p 8000 jameshfisher.com</p><p>; &lt;&lt;&gt;&gt; DiG 9.16.1-Ubuntu &lt;&lt;&gt;&gt; @127.0.0.1 -p 8000 jameshfisher.com</p><p>; (1 server found)</p><p>;; global options: +cmd</p><p>;; Got answer:</p><p>;; -&gt;&gt;HEADER&lt;&lt;- opcode: QUERY, status: NOERROR, id: 10325</p><p>;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0</p><p>;; WARNING: recursion requested but not available</p><p>;; QUESTION SECTION:</p><p>;jameshfisher.com. IN A</p><p>;; ANSWER SECTION:</p><p>jameshfisher.com. 60 IN A 104.198.14.52</p><p>;; Query time: 0 msec</p><p>;; SERVER: 127.0.0.1#8000(127.0.0.1)</p><p>;; WHEN: T3 Thg 3 29 16:13:33 +07 2022</p><p>;; MSG SIZE rcvd: 66</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc8f1ab6edc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connect to Redis in Go]]></title>
            <link>https://medium.com/@nttuong58/connect-to-redis-in-go-d9b2f95a61c4?source=rss-77ffddabcb9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9b2f95a61c4</guid>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Nguyễn Tường]]></dc:creator>
            <pubDate>Thu, 07 Apr 2022 08:54:43 GMT</pubDate>
            <atom:updated>2022-04-07T08:54:43.891Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous <a href="https://gopher5889.substack.com/p/learn-redis-database-in-5-minutes?s=w">post</a>, we have learned very very basic features in Redis. Let’s go through an example to see how use Redis in Go. For the Redis client in this example we will use <a href="http://github.com/go-redis/redis">github.com/go-redis/redis</a></p><p>First we need to check if Redis is up and running on our local machine. Type following command on terminal:</p><h4>First we need to check if Redis is up and running on our local machine. Type following command on terminal:</h4><p>$ sudo systemctl status redis</p><p>● redis-server.service - Advanced key-value store</p><p>Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)</p><p>Active: active (running) since Wed 2022-03-30 05:53:06 +07; 4h 40min ago</p><p>Docs: <a href="http://redis.io/documentation,">http://redis.io/documentation,</a></p><p>man:redis-server(1)</p><p>Main PID: 813 (redis-server)</p><p>Tasks: 4 (limit: 14122)</p><p>Memory: 4.8M</p><p>CGroup: /system.slice/redis-server.service</p><p>└─813 /usr/bin/redis-server 127.0.0.1:6379</p><p>Thg 3 30 05:53:06 gopc systemd[1]: Starting Advanced key-value store...</p><p>Thg 3 30 05:53:06 gopc systemd[1]: redis-server.service: Can&#39;t open PID file /run/redis/redis-server.pid (yet?) after start: Operation not permitted</p><p>Thg 3 30 05:53:06 gopc systemd[1]: Started Advanced key-value store.</p><h4>If the we get a result same as above, we are ready to go to next step.</h4><p>Here is a sample Go snippet describing how to connect to local Redis:</p><p>rdb := redis.NewClient(&amp;redis.Options{</p><p>Addr: &quot;localhost:6379&quot;,</p><p>Password: &quot;&quot;,</p><p>DB: 0,</p><p>})</p><p>ctx := context.Background()<br>err := rdb.Set(ctx, &quot;7wks&quot;, &quot;http://www.sevenweeks.org/&quot;, 0).Err()</p><p>if err != nil {</p><p>panic(err)</p><p>}<br>val, err := rdb.Get(ctx, &quot;7wks&quot;).Result()</p><p>if err != nil {</p><p>panic(err)</p><p>}</p><p>fmt.Println(val)</p><p>Save the above snippet to file such as main.go, open a terminal and run:</p><p>$ go run main.go</p><p><a href="http://www.sevenweeks.org/">http://www.sevenweeks.org/</a></p><p>We have successfully add new key 7wks with value <a href="http://www.sevenweeks.org/">http://www.sevenweeks.org/</a></p><p>Set and get multiple key at once:</p><p>_, err := rdb.MSet(ctx, &quot;gog&quot;, &quot;http://google.com&quot;, &quot;ms&quot;, &quot;http://microsoft.com&quot;).Result()</p><p>if err != nil {</p><p>panic(err)</p><p>}</p><p>sliceCMD := rdb.MGet(ctx, &quot;gog&quot;, &quot;ms&quot;)</p><p>if sliceCMD.Err() != nil {</p><p>panic(sliceCMD.Err())</p><p>}</p><p>fmt.Println(sliceCMD.Val()...)</p><p>rdb.Set(ctx, &quot;count&quot;, 2, 0).Err()</p><p>Again save this and run:</p><p>$ go run main.go</p><p>http://google.com <a href="http://microsoft.com/">http://microsoft.com</a></p><h3>References:</h3><ol><li><a href="https://github.com/go-redis/redis">https://github.com/go-redis/redis</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9b2f95a61c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>