<?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 Nathan Tsao on Medium]]></title>
        <description><![CDATA[Stories by Nathan Tsao on Medium]]></description>
        <link>https://medium.com/@wofltsao?source=rss-499182c4abe3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PEuF7fJjU2yIzfoR14rBcw.jpeg</url>
            <title>Stories by Nathan Tsao on Medium</title>
            <link>https://medium.com/@wofltsao?source=rss-499182c4abe3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:14:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wofltsao/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[How To Serve a Single-Page Application Using Go]]></title>
            <link>https://medium.com/better-programming/how-to-serve-a-single-page-application-using-go-4b9a38d92987?source=rss-499182c4abe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b9a38d92987</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Nathan Tsao]]></dc:creator>
            <pubDate>Fri, 20 May 2022 14:00:25 GMT</pubDate>
            <atom:updated>2022-05-20T14:00:25.094Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide to building a Vue SPA with Go’s standard HTTP server</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vXPmgD5i1V9mHD6Q" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Full source code can be found </em><a href="https://github.com/wolftsao/go_spa_example"><em>here</em></a><em>.</em></p><h4>Prerequisites</h4><ol><li>npm</li><li>Vue CLI</li><li>Go compile (1.16+ for embedding in this example, recommend 1.18+)</li><li>(Optional) Docker</li></ol><h3>Setup Our Project</h3><p>The very first thing is to set up our project. Let’s say our project name is go_spa_example. Here’s the code to do that:</p><pre>mkdir go_spa_example<br>cd go_spa_example</pre><pre># create Go module, I am using my Github here<br>go mod init github.com/wolftsao/go_spa_example</pre><p>Then initialize our Vue frontend:</p><pre># To make it simple, I just name the Vue project ui<br># flag -n means no git</pre><pre>vue create -n ui</pre><p>Now, Vue CLI will ask you about the project options. The Vue Router (since we are building SPA) is the most important thing, so choose “Manually select features.” Here are my configurations:</p><figure><img alt="preset: manually select features features needed: babel, router, linter Vue.js version: 3.x history mode: yes linter/formatter: basic additional lint features: lint on save prefer placing: in dedicated config files save as preset: n" src="https://cdn-images-1.medium.com/max/1024/1*MGvBKxlnQl45HdG_-gwTsw.png" /></figure><p>Our project setup is done. Let’s handle the frontend first.</p><h3>Vue Frontend Setup</h3><p>We are not going to create fancy frontend things here, just have a workable example with default Vue template pages that will contain the following pages:</p><ul><li>Index page with path &quot;/&quot;</li><li>About page with path &quot;/about&quot;</li><li>Everything else will show the Not Found page</li></ul><p>We need to do the following to complete this:</p><ol><li>Change the location of frontend build artifacts</li><li>Add a Not Found page</li><li>Setup alias for index page and catch all routes for the Not Found page</li></ol><h4>Change frontend artifacts location</h4><p>If we build the frontend now, the output artifacts will be in ui/dist, like this:</p><pre>ui/dist<br>├── css<br>├── favicon.ico<br>├── index.html<br>└── js</pre><p>The dist is now the root folder to serve the frontend, and it has each type of static files, e.g., js, CSS, etc., under its own folder.</p><p>But this common layout is a little bit complicated to handle with Go’s standard HTTP library (I will explain more about this later).</p><p>Let’s aggregate all the static files into a centralized location.</p><p>Open ui/vue.config.js then add the attribute assetsDir with the value static like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e782d95b7a9edf820c3f0f7f2dc554d1/href">https://medium.com/media/e782d95b7a9edf820c3f0f7f2dc554d1/href</a></iframe><p>The structure of artifacts now will be:</p><pre>ui/dist<br>├── favicon.ico<br>├── index.html<br>└── static<br>    ├── css<br>    └── js</pre><p>All static files are under the static folder.</p><p>Based on this configuration, the URL for our index page will be:<br>http://&lt;domain&gt;:&lt;port&gt;/</p><p>And CSS file will look like this:<br>http://&lt;domain&gt;:&lt;port&gt;/static/css/app.9bdcf330.css</p><h4>Create Not Found page</h4><p>Create file ui/src/views/NotFound.vue with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fa18cb49cf69a84612317dae6f1b593/href">https://medium.com/media/7fa18cb49cf69a84612317dae6f1b593/href</a></iframe><p>Now, we have a <a href="https://vuejs.org/guide/scaling-up/sfc.html">single file component (SFC)</a> with a template only.</p><h4>Add Index page alias and the catch all route</h4><p>Finally, open up ui/src/router/index.js, then:</p><ol><li>Add an alias alias: [&#39;/index.htm&#39;], to index page route (line 7 below).<br>By default, Vue treat &quot;/&quot; and &quot;/index.html&quot; differently, so let’s make it more natural by adding this alias.</li><li>Add a catch all route at the end of routes array (line 20 below).</li></ol><p>Here’s the code to do that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8456ce981ab2a9ff9df7ef0977d4322/href">https://medium.com/media/c8456ce981ab2a9ff9df7ef0977d4322/href</a></iframe><p>Excellent! We have completed our Vue frontend. Let’s embrace the most exciting part — the Go HTTP server.</p><h3>Create Go HTTP Backend Server</h3><p>This will be the main part of this story. However, to make things as simple as possible, I will define everything in a single main.go file.</p><p>Basically, what we need here is:</p><ul><li>A Go embedding package</li><li>Go HTTP server</li><li>Mux/router</li><li>HTTP file server to serve frontend static files</li></ul><p>I will also talk about some errors when serving SPA from Go.</p><h4>Embedding our frontend artifacts</h4><p>We don’t really need to embed our frontend file, but <a href="https://pkg.go.dev/embed">embed</a> has its own potential usage, so I use it here as a practice.</p><p>(My project source code also has another branch, noembed, which uses a normal filesystem to serve the frontend. You can check it out <a href="https://github.com/wolftsao/go_spa_example/tree/noembed">here</a>)</p><p>The advantage of using embed is that we can run our SPA anywhere without worrying about the location of frontend artifacts. However, we need to rebuild our program every time there’s a frontend change.</p><p>OK. Let’s create the Go embed package file, ui/ui.go:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85322079f9d26df3a16f79420d4c1bf9/href">https://medium.com/media/85322079f9d26df3a16f79420d4c1bf9/href</a></iframe><p>Make sure the file, ui.go, is under the ui folder, not the project root. It lives with the other frontend files.</p><p><strong><em>Note</em></strong><em>: We can put </em><em>ui.go in the project root and change package to main in this example. But in a bigger project, we usually separate files into different packages, with each package serving its own purpose. The only purpose for </em><em>ui.go is to serve frontend artifacts. So, I decided to put it in the </em><em>ui folder, but it’s just my opinion.</em></p><p>This package declares a variable StaticFiles that serves as the embedding filesystem.</p><p>Also, pay attention to the Go directive //go:embed all:dist , which means embedding all files in the dist folder and subfolders.</p><p>In Go version earlier than 1.18, there’s a big limitation in the embed, which cannot embed files prefixed with &quot;.&quot; or &quot;_&quot;. And some frontend bundle tools generate artifacts with that pattern.</p><p>Note: This <a href="https://github.com/golang/go/issues/43854">issue</a> has been fixed in Go 1.18 with the special term all: in the embed directive. But since Vue CLI didn’t generate artifacts with &quot;.&quot; or &quot;_&quot; prefix, we don’t have to worry about this (if you are using an earlier Go version, please change the directive to //go:embed dist/*, since all: is a 1.18 feature.</p><p>So, if you like to try other frontend libraries/frameworks, or if you are using an earlier Go version, you need to pay more attention to these.</p><h4>A simple Go HTTP server</h4><p>Now, create the file main.go in the project root folder to serve our HTTP server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a70a29fc622f280481bb8e48da3166a/href">https://medium.com/media/3a70a29fc622f280481bb8e48da3166a/href</a></iframe><p><em>You might need to adjust the import path for the ui package.</em></p><p>It’s just a normal Go HTTP server (and I hardcoded the server port to 8888).</p><p>Again, to make the example as simple as possible, I put every route/handler in one function called router. Let’s talk about this.</p><h4>Our mux/router</h4><p>The router function will handle three kinds of routes:</p><ol><li>Frontend index page (&quot;/&quot; or index.html)</li><li>Frontend static files (e.g., JavaScript, CSS, etc.)</li><li>APIs</li></ol><p>Define the router function under main function like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb9246da459a3cdb081abe14653b36fe/href">https://medium.com/media/eb9246da459a3cdb081abe14653b36fe/href</a></iframe><ul><li>On line 5, we handle the index page with the function indexHandler (I will work on this later)</li><li>On lines 8 to 10, we define a http.FileServer by creating a subfolder of our embedded filesystem. With that, we can search files starting with &quot;static&quot; instead of &quot;dist&quot; (By default, http.FileServer enables directory listings; you can check <a href="https://www.alexedwards.net/blog/disable-http-fileserver-directory-listings">this great article</a> to disable that behavior)</li><li>Line 13 is just a dummy API (anonymous function) for demo</li></ul><p>Right now, you might wonder why we separate index handler (&quot;/&quot;) from the static file server (&quot;/static/&quot;). Isn’t index.html just another file?</p><p>Suppose we only have the &quot;/&quot; route, which serves our file server if we go down the easiest path. We can complete this by doing the following:</p><ul><li>Build and run the program</li><li>Type http://localhost:8888 in the address bar, and the index page will show correctly</li><li>Click the About link to show the right page with the correct URL (http://localhost:8888/about)</li></ul><p>Everything looks good until you type http://localhost:8888/about directly in the address bar, then hit enter. Boom! Empty page with 404 page not found.</p><p>What’s going on?</p><p>Well, the problem is twofold.</p><p>First, Go searches the filesystem by URL path. For the case of http://localhost:8888/about. This is telling Go to search the about file in the file server. Since we don’t have such a file, the Go HTTP server returns a default 404 message.</p><p>Second, the about page only exists in the frontend. JavaScript did the frontend routing magic for us. Technically, JavaScript/CSS code does exist in backend, so we need a file server to serve these files.</p><p>The frontend also needs an entry point to start the SPA, much like Go’s main function. When the browser accesses the index page (&quot;/&quot;, the entry point), it knows how to fetch other static files, start the Vue engine, and then Vue can route and render those pages for us.</p><p>That’s why we need to handle index route &quot;/&quot; specifically.</p><p>There’s one final thing about Go’s HTTP route. Earlier, when we worked on Vue, we set assetsDir: &#39;static&#39; in the vue.config.js, which is geared toward Go’s routing pattern rule. (If you are not familiar with Go’s routing rule, I highly recommend you to read <a href="https://lets-go.alexedwards.net/sample/02.03-routing-requests.html">this</a>. One of the greatest Go books I’ve ever read!)</p><p>For Go, everything else not matched by other handlers will fallback to index route /. This is the effect we want, so we set it to our index page. When the user types an arbitrary URL in the address bar, it always falls back to index.html, then Vue can do the frontend routing correctly.</p><p>Since &quot;/&quot; index route has been used by indexHandler, we need to use another pattern for the file server. But if we are not setting assetsDir: &#39;static&#39;, we need to handle each static file type individually like this:</p><pre>mux.Handle(&quot;/css/&quot;, httpFS)<br>mux.Handle(&quot;/js/&quot;, httpFS)</pre><p>We have spent quite a huge page explaining these errors in Go. Let’s move on to our final piece of code, indexHandler.</p><h4>Index page handler</h4><p>Define indexHandler under router like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37bbadeed557a12a964ea963d457dd8b/href">https://medium.com/media/37bbadeed557a12a964ea963d457dd8b/href</a></iframe><p>The code reads specific embedded files and then writes them to the HTTP response.</p><p>But it looks quite confusing because we also handle the favicon here.</p><p>Honestly speaking, I’m not quite familiar with the frontend. I didn’t find an easy way to change the location of the favicon file. The default location in Vue is under the root &quot;/favicon.ico&quot;, so I handled it here directly. (We can handle it with a dedicated handler like mux.Handle(&quot;/favicon.ico&quot;, faviconHandler))</p><p>Now we have completed our Go SPA. Time to roll!</p><h3>Build and Run Our Spa</h3><p>Build our frontend first, so there’s artifacts for Go to embed. Here&#39;s code:</p><pre>cd ui<br>npm run build</pre><p>Run our Go HTTP server:</p><pre>cd ..<br>go run main.go</pre><p>Let’s make some tests. Open <a href="http://localhost:8888/">http://localhost:8888</a> (we hardcoded the port to 8888), and your browser should show default to the Vue home page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWs7KJQ2-w1PBAc-PCcBtg.png" /><figcaption>Vue default home page</figcaption></figure><p>Click the top “About” link and change the about page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*HNHtSz2yssZL1Wyb1i1CPg.png" /><figcaption>Vue default about page</figcaption></figure><p>Type <a href="http://localhost:8888/about">http://localhost:8888/about</a> in the address bar, then hit enter. It should show the same about page.</p><p>Type an arbitrary URL like <a href="http://localhost:8888/login">http://localhost:8888/login</a> to show the not found page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*NrJnTmELU2PClBsonXzvJQ.png" /><figcaption>Vue not found page</figcaption></figure><p>Awesome! Everything looks great. Let’s use CURL to test our dummy API using this command:</p><pre>curl -i &quot;http://localhost:8888/api/v1/greeting&quot;</pre><p>Output:</p><pre>HTTP/1.1 200 OK<br>Date: Fri, 20 May 2022 02:47:58 GMT<br>Content-Length: 13<br>Content-Type: text/plain; charset=utf-8</pre><pre>Hello, there!</pre><p>Good, let’s test more. How about a nonexistent API, which could happen if a user typed the wrong address.</p><pre>curl -i &quot;http://localhost:8888/api/v1/greting&quot;</pre><p>Output:</p><pre>HTTP/1.1 200 OK<br>Date: Fri, 20 May 2022 02:53:18 GMT<br>Content-Length: 611<br>Content-Type: text/html; charset=utf-8</pre><pre>&lt;!doctype html&gt;&lt;html lang=&quot;&quot;&gt;&lt;head&gt;&lt;meta charset=&quot;utf-8&quot;&gt;&lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width,initial-scale=1&quot;&gt;&lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot;&gt;&lt;title&gt;ui&lt;/title&gt;&lt;script defer=&quot;defer&quot; src=&quot;/static/js/chunk-vendors.ea2100d5.js&quot;&gt;&lt;/script&gt;&lt;script defer=&quot;defer&quot; src=&quot;/static/js/app.fc9d9338.js&quot;&gt;&lt;/script&gt;&lt;link href=&quot;/static/css/app.9bdcf330.css&quot; rel=&quot;stylesheet&quot;&gt;&lt;/head&gt;&lt;body&gt;&lt;noscript&gt;&lt;strong&gt;We&#39;re sorry but ui doesn&#39;t work properly without JavaScript enabled. Please enable it to continue.&lt;/strong&gt;&lt;/noscript&gt;&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre><p>Oops… How come the nonexistent API call worked?</p><p>If you look closely, the response body is actually index.html of our frontend.</p><p>The problem is, we don’t have any route that matches that URL, so it falls back to the index route &quot;/&quot;.</p><p>Let’s add some guard clauses to prevent this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ea25993dc5d558c7bf8417a47015b53/href">https://medium.com/media/0ea25993dc5d558c7bf8417a47015b53/href</a></iframe><ul><li>On line 2, we add a method check to only allow the GET method</li><li>On line 8, if URL.Path is prefixed with /api, we return the not found response</li></ul><p>(Ideally, in a well-organized project, it’s better to put these conditions in things like middleware)</p><p>Let’s rebuild our program and try the nonexistent API again. It should return 404 this time:</p><pre>HTTP/1.1 404 Not Found<br>Content-Type: text/plain; charset=utf-8<br>X-Content-Type-Options: nosniff<br>Date: Fri, 20 May 2022 03:14:42 GMT<br>Content-Length: 19</pre><pre>404 page not found</pre><p>Congrats! We really have come a long way and built our full-fledged single-page application with Go successfully.</p><h3>Additional Information — Docker</h3><p>We can also build our application in Docker.</p><p>Create a dockerfile in our project root with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae3e755c0ad85b6dc5eb16625febae1a/href">https://medium.com/media/ae3e755c0ad85b6dc5eb16625febae1a/href</a></iframe><p>Then:</p><pre># 1. build frontend<br>cd ui<br>npm run build</pre><pre># 2. build docker image<br>cd ..<br>docker build -t go-spa:test .</pre><pre># 3. (optional) remove intermediate images<br>docker image prune -f</pre><pre># 4. run our SPA container<br>docker run --rm -p &quot;8888:8888&quot; go-spa:test</pre><h3>Summary</h3><p>This is a long story, but it&#39;s quite short and simple if you look at the full Go code. We need to understand the mechanisms and limitations of Go’s HTTP server and make some accommodations.</p><p>The principles are:</p><ol><li>understand the structure of frontend build artifacts, find and adjust possible configuration settings, then serve these files in Go correctly.</li><li>understand the pattern-matching rules and quirks of Go’s HTTP handler</li></ol><p>Before I started writing this story, I did spend lots of time figuring out how to make this work. I’m not an experienced programmer, especially in frontend, so please let me know if there are better solutions or if something is incorrect here.</p><p>Thanks a lot for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b9a38d92987" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-serve-a-single-page-application-using-go-4b9a38d92987">How To Serve a Single-Page Application Using Go</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Achieve Dynamic SQL Query With Go]]></title>
            <link>https://medium.com/better-programming/dynamic-sql-query-with-go-8aeedaa02907?source=rss-499182c4abe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aeedaa02907</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Nathan Tsao]]></dc:creator>
            <pubDate>Mon, 16 May 2022 13:53:16 GMT</pubDate>
            <atom:updated>2022-05-17T15:29:27.887Z</atom:updated>
            <content:encoded><![CDATA[<h4>Start by using <a href="https://pkg.go.dev/database/sql#Rows.Columns">Rows.Columns</a> or <a href="https://pkg.go.dev/database/sql#Rows.ColumnTypes">Rows.ColumnTypes</a> to get column information</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LymQJ8BtzG-jbtP6" /><figcaption>Photo by <a href="https://unsplash.com/@sunder_2k25?utm_source=medium&amp;utm_medium=referral">Sunder Muthukumaran</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For most applications, we will know what data we need from the database, then we can define the appropriate data types to take the query result.</p><p>But sometimes we might need the flexibility to take dynamic SQL or unknown column queries at runtime to generate some data. For example, say we are building a reporting, management or GUI tool.</p><p>In this post, I am going to talk about how to do this with Go standard library (<a href="https://pkg.go.dev/database/sql">database/sql</a>) in a simple reporting example.</p><p>The full code example can be found <a href="https://github.com/wolftsao/go_dynamic_sql_example">here</a></p><p>I will skip the obvious Go code and jump right into the important part. Also, to make the code clear to read, I will ignore the error handling.</p><h3>Obtaining column length and column names</h3><p>First, we need to get the column information like column names.</p><p>In this example, I am using <a href="https://www.cockroachlabs.com/">CockroachDB</a> with users table defined below:</p><pre>   column_name  |  data_type  |<br>----------------+-------------+<br>  id            | UUID        |<br>  name          | STRING      |<br>  age           | INT8        |<br>  married       | BOOL        |<br>  location      | JSONB       |<br>  phone_numbers | STRING[]    |<br>  creation_time | TIMESTAMPTZ |</pre><p>Let’s run a full table query:</p><pre>rows, _ := db.Query(&quot;select * from users&quot;)<br>defer rows.Close()</pre><pre>cols, _ := rows.Columns()</pre><p>Variable cols is the column names (slice of string). Assuming we are just printing results to stdout, we can use <a href="https://pkg.go.dev/text/tabwriter">text/tabwriter</a> with ease:</p><pre>w := tabwriter.NewWriter(os.Stdout, 0, 2, 1, &#39; &#39;, 0)<br>defer w.Flush()</pre><pre>sep := []byte(&quot;\t&quot;)<br>newLine := []byte(&quot;\n&quot;)</pre><pre>w.Write([]byte(strings.Join(cols, &quot;\t&quot;) + &quot;\n&quot;))</pre><p>The header part of the report is completed, let’s tackle the result data.</p><h3>Handling unknown row data</h3><p>For dynamic or ad hoc query, since we don’t know the column type, it’s very difficult to determine the variable type we need to use in advance (we can pair switch statement with <a href="https://pkg.go.dev/database/sql#Rows.ColumnTypes">ColumnTypes</a> to achieve this, and for advanced usage like formatting or further processing, we should. But that will be quite tedious).</p><p>In addition, the database column can be NULLABLE . In Go, we need to handle this with special data types like NullString.</p><p>For simple reporting purposes, we need a general data type to accommodate results from database query.</p><p>Fortunately, byte slice []byte works well for this, including JSON/array data. Also, byte slice treat database NULL as empty by default, which alleviates us from additional handling.</p><pre>row := make([][]byte, len(cols))</pre><p>Since the row might contain multiple columns, we need a byte slice.</p><p>Now, there’s a tricky part of Go, the <a href="https://pkg.go.dev/database/sql#Rows.Scan">Rows.Scan</a> is a variadic function with parameter as type any, and the underlying concrete type should be pointers. There’s no problem if we specify each argument like:</p><pre>var id int<br>var name string<br>err := rows.Scan(&amp;id, &amp;name)</pre><p>At this point, we might think we can just change row to []*[]byte then unpack it in Scan call:</p><pre>row := make([]*[]byte, len(cols))<br>err := rows.Scan(row...)</pre><p>Unfortunately, we will get compile-time error saying:</p><pre>cannot use row (variable of type []*[]byte) as []any value in argument to rows.Scan</pre><p>To address this, we have to follow what the compiler had told us. We need a variable of []any type, then each element will be a pointer to each element of row variable:</p><pre>rowPtr := make([]any, len(cols))<br>for i := range row {<br>  rowPtr[i] = &amp;row[i]<br>}</pre><p>That’s quite a lot, now we can print the result.</p><h3>Printing the query result</h3><p>This part should be easy, just loop through the rows, scan and write to stdout:</p><pre>for rows.Next() {<br>  _ := rows.Scan(rowPtr...)</pre><pre>  w.Write(bytes.Join(row, sep))<br>  w.Write(newLine)<br>}</pre><p>We can execute the program now, the result will like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6-63rPl-ul0mpcmK1WqMA.png" /><figcaption>Dynamic query result example</figcaption></figure><p>Below is the full minimum runnable code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f030b8a19535d8fd7a3dda58b490bf3/href">https://medium.com/media/9f030b8a19535d8fd7a3dda58b490bf3/href</a></iframe><p>(Make sure there’s a database and table available to run the program, or check <a href="https://github.com/wolftsao/go_dynamic_sql_example">this</a> for a complete example)</p><h3>Summary</h3><p>To achieve dynamic SQL query in Go, we:</p><ol><li>Used <a href="https://pkg.go.dev/database/sql#Rows.Columns">Rows.Columns</a> or <a href="https://pkg.go.dev/database/sql#Rows.ColumnTypes">Rows.ColumnTypes</a> to get column information</li><li>Used more general data type (byte slice in this case) to store the query result, with an intermediary type ([]any) to match up Rows.Scan call</li><li>Loop through the rows as usually</li></ol><p>Thanks a lot for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aeedaa02907" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/dynamic-sql-query-with-go-8aeedaa02907">How to Achieve Dynamic SQL Query With Go</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>