<?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 Muhammad Wyndham Haryata Permana on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Wyndham Haryata Permana on Medium]]></description>
        <link>https://medium.com/@mwyndham?source=rss-4c11fceb1e91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SOz5iufT06Jr7krvlV0ojQ.jpeg</url>
            <title>Stories by Muhammad Wyndham Haryata Permana on Medium</title>
            <link>https://medium.com/@mwyndham?source=rss-4c11fceb1e91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 18:09:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mwyndham/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[Personal Blog With HTMX + Go Part 3 — Server Rendered Markdown]]></title>
            <link>https://mwyndham.medium.com/personal-blog-with-htmx-go-part-3-server-rendered-markdown-75c80cc5f470?source=rss-4c11fceb1e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/75c80cc5f470</guid>
            <category><![CDATA[htmx]]></category>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <dc:creator><![CDATA[Muhammad Wyndham Haryata Permana]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 05:57:23 GMT</pubDate>
            <atom:updated>2024-03-15T05:58:21.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-_0udPmEY009U99e.gif" /></figure><h3>Personal Blog With HTMX + Go Part 3 — Server Rendered Markdown</h3><p>This article will cover part 3 of the blogging Tutorial. This one is going to be long as we start deep-diving into making some interactive stuff with the help of HTMX. If you need a refresher, you can read the <a href="https://mwyndham.dev/articles/personal-blog-with-htmx-go-part-golang-templating.html">first</a> or the <a href="https://mwyndham.dev/articles/personal-blog-with-htmx-go-part-integrating-tailwindcss.html">previous</a> part.</p><h3>What We’re Going to Do Today</h3><p>This time, we’re about to make a fancy <strong>Markdown to HTML</strong> Renderer but on the server side. Why? First, it will be a good demonstration of making an interactive element using HTMX. Secondly, Why not? It’s kinda cool, isn’t it?</p><h3>Dependencies</h3><p>First, we need to sort out our dependency. We need to add a Markdown parser for Golang.</p><blockquote><em>What? Why not make your own parser?</em></blockquote><p>I know I know, maybe I oversell it a bit. <strong>Technically we can, </strong>but it will be quite an effort, especially for the coverage of a single blog post. But there’s more reason for that.</p><p>HTML Sanitization is one thing, then there are many different flavors of markdown to support. It’s also a bit out of scope because we’re here to highlight how HTMX is useful for creating interactive apps.</p><p>Okay, now we need to add our dependency first. My Markdown parser of choice is <a href="https://github.com/yuin/goldmark">GoldMark</a>. It’s fast and has quite an extensive amount of available extensions you might want. It also handles sanitization quite well for basic stuff.</p><p>Let’s add our dependency to our Go project via:</p><pre>go get github.com/yuin/goldmark</pre><p>Goldmark also brings its extension called <strong>GFM (GitHub Flavored Markdown) </strong>and <strong>Typographer</strong>. We will need these two extensions to increase our markdown parsing capabilities.</p><p>GFM, as the name suggests, adds GitHub style Markdown tags, such as table, strike-through, and linkify. There’s more to it, but you can read it yourself in the formal spec <a href="https://github.github.com/gfm">here</a>.</p><h3>Markdown parsing</h3><p>Next, we need to create a new file called utils/markd/markd_parser.go and set the content as follows:</p><pre>package markd<br>import (<br>   &quot;bytes&quot;<br>   &quot;string&quot;<br>   &quot;github.com/yuin/goldmark&quot;<br>   &quot;github.com/yuin/goldmark/extension&quot;<br>   &quot;github.com/yuin/goldmark/parser&quot;<br>   &quot;github.com/yuin/goldmark/renderer/html&quot;<br>)<br><br>var mdParser goldmark.Markdown<br>func init() {<br>   mdParser = goldmark.New(<br>      goldmark.WithExtensions(<br>         extension.GFM,<br>         extension.Typographer,<br>      ),<br>      goldmark.WithParserOptions(<br>         parser.WithAutoHeadingID(),<br>      ),<br>      goldmark.WithRendererOptions(<br>         html.WithHardWraps(),<br>      ),<br>   )<br>}</pre><p>Cool! Now we have created a simple markdown parsing client. Next, we need to add the public function that is accessible by other modules to parse the markdown into HTML:</p><pre>func ParseMD(source string) (string, error) {<br>   var buf bytes.Buffer<br>   if err := mdParser.Convert([]byte(source), &amp;buf); err != nil {<br>      return &quot;&quot;, err<br>   }<br>   result := buf.String()<br>   <br>   return result, nil<br>}</pre><p>Next, let’s create an endpoint where we can render our markdown to some webpage. First, let’s define the endpoint function in the main.go file&#39;s main function:</p><pre>e.GET(&quot;/markdown&quot;, func(e echo.Context) error {<br>   markdowns := &quot;# Header1\n## Header 2&quot; // Markdown example<br>   parsed, err := markd.ParseMD(markdowns)<br>   if err != nil {<br>      return err<br>   }<br>   res := map[string]interface{} {<br>      &quot;ParsedMarkdown&quot;: parsed, <br>   }<br>   return c.Render(http.StatusOK, &quot;markdown&quot;, res)<br>})</pre><p>This endpoint will serve yet to-be-created template called markdown where we should pass the content of the following markdown:</p><pre># Header 1<br>## Header 2</pre><p>as ParsedMarkdown and pass it down to the template body. If rendered correctly, it should be something similar to this:</p><pre>&lt;h1&gt;Header 1&lt;/h1&gt;<br>&lt;h2&gt;Header 2&lt;/h2&gt;</pre><p>Next, we should create a new html file where the rendered markdown should live. It should be similar to what we learned in Part 1.</p><p>Let’s name it as /public/markdown.html:</p><pre>{{define &quot;markdown&quot;}}<br>&lt;!-- This is tailwind class for bright blue-greyish background, horizontally centered div with padding of 6 in all direction--&gt;<br>&lt;div class=&quot;bg-slate-100 mx-auto p6&quot;&gt; <br>   {{.ParsedMarkdown}}<br>&lt;/div&gt;<br>{{end}}</pre><p>As we learned in Part 1, partial is not a valid HTML. This is where HTMX comes in handy, as we can reuse the index.html again, and add a button that will swap with the partial markdown.html and we will get valid HTML after the swap.</p><p>To do that, let’s modify our index.html a little bit by adding the following lines of code under the user-info &lt;div&gt; we had previously:</p><pre>&lt;div id=&quot;user-info&quot;&gt;<br>   ...<br>&lt;/div&gt;<br>&lt;!-- Put following lines here--&gt;<br>&lt;div id=&quot;markdown&quot;&gt;<br>   &lt;button hx-get=&quot;/markdown&quot; hx-target=&quot;#markdown-part&quot; hx-swap=&quot;innerHTML&quot;&gt;<br>      Parse Markdown<br>   &lt;/button&gt;<br>&lt;/div&gt;</pre><p>This will simply add a button underneath the previous button we had, and it will call /markdown via HTMX and swap the innerHTML of the markdown &lt;div&gt; accordingly.</p><p>Now, if everything is according to plan, we should see a well-rendered markdown in our blog post. We should try to run it now.</p><p>Run the tailwind build command (npx tailwindcss -i ...etc) and then run the go server ( go run .) and open localhost:4040 in our server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*ey_o97zQZ4qQW3t0.gif" /></figure><p><strong>Yeay!… or not?</strong> While the Tailwind class we specified before is rendered correctly, the header looks the same… <em>what gives? Is the markdown rendering not working?</em></p><p>Nope, it’s working just fine.</p><p>Press F12 and open inspector, and see exactly that we have already rendered both &lt;h1&gt; and &lt;h2&gt; as per the standard rendering of Markdown to HTML:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*4QFuX487ja1Tpcgq.png" /></figure><p><em>But it looks a bit..</em> <em>underwhelming</em> isn’t it? you would think that a well-rendered markdown would be similar to what GitHub offering would look like. But let alone have nice styling, &lt;h1&gt; and &lt;h2&gt; does not render any differently.</p><h3>Tailwind Typography</h3><p>We will not cover all the styling parts, as it will take quite a long time. But this would be the perfect moment to introduce one of the most useful Tailwind Extensions: <strong>Tailwind Typography</strong>.</p><h3>Why Tailwind Typography?</h3><p>Realistically when it comes to styling, we can include tailwind classes in the HTML and call it a day. But I am personally against this for three reasons:</p><ul><li><strong>Introducing CSS class will open the opportunity for XSS attack, especially when it comes to User Generated Content. </strong>However, it would be less of an issue if this was going to be used for a personal project or you know most likely you’re going to be the one making the content.</li><li><strong>As of right now, GoldMark does not have an easy way to add custom attributes.</strong></li><li><strong>You typically do not want to make the content of a blog post carry its own styling</strong>. Decoupling the content of your blog from the UI (including theme, color, and many others) allows you to modify the UI after the fact.</li></ul><p>With that in mind, we still need to somehow introduce styling to our content. There are ways to do this by using CSS selectors like this:</p><pre>.h1 {<br>   @apply text-slate-900<br>}</pre><p>But applying this globally against HTML elements will also cause more styling issues down the line. Fortunately, Tailwind has the exact solution to our problem which is Tailwind Typography.</p><p>I won’t go deep dive into what is Tailwind Typography, but I will just jump straight to the specific implementation we’re aiming for: <em>stylize the different headers.</em></p><h3>Implementing Tailwind Typography</h3><p>It’s rather easy to do. First, make sure that the extension is already declared in the tailwind.config.js:</p><pre>module.exports = {<br>  content: [&quot;./public/**/*.html&quot;],<br>  ...<br>  plugins: [<br>     require(&#39;@tailwindcss/typography&#39;), // Ensure this line added<br>  ],<br>}</pre><p>Then go back to our markdown.html code up there for a second:</p><pre>{{define &quot;markdown&quot;}}<br>&lt;!-- --&gt;<br>&lt;div class=&quot;bg-slate-100 mx-auto p6&quot;&gt; <br>   {{.ParsedMarkdown}}<br>&lt;/div&gt;<br>{{end}}</pre><p>We should modify the parent div class attribute in it to be like this:</p><pre>{{define &quot;markdown&quot;}}<br>&lt;!-- please look at the class attribute content--&gt;<br>&lt;div class=&quot;bg-slate-100 mx-auto p6 prose prose-h1:text-4xl prose-h2:text-3xl prose-h3:text-2xl prose-h4:text-xl prose-h5:text-lg&quot;&gt; <br>   {{.ParsedMarkdown}}<br>&lt;/div&gt;<br>{{end}}</pre><p>Those extra classes are pretty straightforward. Let’s take the prose-h1:text-4xl as example:</p><ul><li>If prose class is applied, then please apply the following styling to h1 element.</li><li>please apply class of text-4xl (text size 4xl in tailwind) to h1 element.</li></ul><p>All other attributes are the same, but just applying it to other header sizes.</p><p>Now if we’re to run our code again, it should show something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wivo9_5rZajZs31I.png" /></figure><p>Looks great right? But you might be wondering why we got more than we bargained for. Like now it’s centered horizontally and has a specific width applied to it. That’s what prose class is used for. You can read more <a href="https://github.com/tailwindlabs/tailwindcss-typography">here</a>. But the gist is it&#39;s just what Tailwind Typography does and it will help us build our simple blog faster.</p><h3>Putting it all together</h3><p>Now all of the ingredients are here:</p><ul><li>Render from Markdown to HTML on the server.</li><li>Display rendered HTML to the client.</li><li>Stylize the HTML.</li></ul><p>Next, we need to put it all together. The steps we’re going to take should be consist of:</p><ol><li>Create a new page and add a text area where the client can write their markdown.</li><li>Use hx-post and hx-trigger to send the markdown to the server to be rendered in real time.</li><li>Add an endpoint to accept the markdown text, and render it to HTML, then return the HTML to the client, and make use of hx-swap.</li></ol><p>So let’s just get into this now.</p><h3>Create a New Page</h3><p>First, let’s create a new endpoint to start fresh:</p><pre>e.GET(&quot;/editor&quot;, func(c echo.Context) error {<br>	return c.Render(http.StatusOK, &quot;editor&quot;, nil)<br>})</pre><p>This endpoint should return a new page that will host our simple editor. But before it can do anything, let’s create the ./public/editor.html first, so we can see what we&#39;ll be making:</p><pre>{{define &quot;editor&quot;}}<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;!-- copy paste from index.html --&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>   &lt;div class=&quot;flex flex-row w-full&quot;&gt;<br>      &lt;textarea <br>         class=&quot;flex-1 p-6 min-h-96&quot;<br>         id=&quot;editor&quot;&gt;<br>      &lt;/textarea&gt;<br>      &lt;div <br>         id=&quot;preview&quot; <br>         class=&quot;flex-1 bg-stone-50 p-6 min-h-96&quot;&gt;<br>      &lt;/div&gt;<br>   &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br>{{end}}</pre><p>It’s a simple HTML page with div and has two elements as its child. One of which is textarea marked as editor and the other is simply div marked as preview. Both of which have equal widths and are split in half in the middle.</p><p>What we’re going to make is a split editor where you write your markdown on the left side, and render the output on the right.</p><p>If done correctly, it should render to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cr5yzNlkcO91Y1wx.png" /></figure><p>Next, we’re going to repurpose the markdown.html we had previously to display the content on the preview side. But first, we need to modify it:</p><pre>&lt;!-- before --&gt;<br>&lt;div class=&quot;mx-auto p-6 prose prose-h1:text-4xl prose-h2:text-3xl prose-h3:text-2xl prose-h4:text-xl prose-h5:text-lg&quot;&gt;<br>&lt;!-- after --&gt;<br>&lt;div class=&quot;prose prose-h1:text-4xl prose-h2:text-3xl prose-h3:text-2xl prose-h4:text-xl prose-h5:text-lg&quot;&gt;</pre><h3>HTMX Boogaloo!</h3><p>Next is the fun part. We’re going to make use of the hx- attributes to add some interactivity to the textarea above. Add the following attributes to the textarea :</p><pre>&lt;!-- add the hx-..., type, and name attributes --&gt;<br>   &lt;div class=&quot;flex flex-row w-full&quot;&gt;<br>      &lt;textarea <br>         ...<br>         hx-post=&quot;/editor/render&quot; <br>         hx-trigger=&quot;keyup delay:500ms&quot; <br>         hx-target=&quot;#preview&quot;<br>         hx-swap=&quot;innerHTML&quot;<br>         type=&quot;text&quot;<br>         name=&quot;content&quot;&gt;<br>      &lt;/textarea&gt;<br>      ...<br>    &lt;/div&gt;</pre><p>Those extra attributes bring us quite a lot of functionality on the table. When described, it will do the following:</p><ul><li>hx-trigger =&gt; Whenever event keyup happened ( keyup is triggered whenever the user stops typing on the keyboard), and debounces the event for 500ms.</li><li>hx-post =&gt; Then after that, send an AJAX Request POST to endpoint /editor/render.</li><li>hx-target =&gt; After that, put the response from the AJAX towards the element with the CSS Selector id of preview (hence the # prefix).</li><li>hx-swap =&gt; And please put the response <strong>inside</strong> the target element.</li><li>name =&gt; When AJAX happens, please carry the content textarea along. And please set the Form-Data key to content.</li></ul><p>If you run it and start typing in the text area, you will see that there’s a new AJAX request against /editor/render the endpoint which returns 404.</p><p>If you open the Request tab, you&#39;ll see the exact content of the text area in the form of data, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*evaeTYgv-iP4tbD7.png" /></figure><p>Which is good! now we know that we can interactively send the text area content to the server, and the server will be able to render the HTML for us!</p><h3>Final Piece to The Magic</h3><p>Next, we need to create the aforementioned /editor/render endpoint. This time we will be using POST :</p><pre>// Create  following endpoint in the `main.go`<br>e.POST(&quot;/editor/render&quot;, func(c echo.Context) error {<br>  // This code will bind the Form-Data content <br>  // to the struct RenderReq<br>  var payload RenderReq<br>  err := c.Bind(&amp;payload)<br>  if err != nil {<br>    return err<br>  }<br>  // Next, we render the RenderReq.Content<br>  // which should be markdown using our parser<br>  parsed, err := markd.ParseMD(payload.Content)<br>  if err != nil {<br>    return err<br>  }<br>  // And just like the example before<br>  // we put the parsed markdown in the result<br>  // and render the `markdown.html` template.<br>  res := map[string]interface{}{<br>    &quot;ParsedMarkdown&quot;: parsed,<br>  }<br>  return c.Render(http.StatusOK, &quot;markdown&quot;, res)<br>})<br>...<br>// Create following struct outside the main function<br>type RenderReq struct {<br>  Content string `json:&quot;content&quot; form:&quot;content&quot;`<br>}</pre><p>Once we add the endpoint, and restart the deployment you should be able to do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-_0udPmEY009U99e.gif" /></figure><p>And just like that, we have our server-rendered Markdown done. It’s not that much code but we achieve quite a lot here!</p><h3>Final Words</h3><p>Now that we’re finished with this part 3, we have some room to breathe. In the next part, we’ll be improving the Developer Experience a little bit by adding:</p><ul><li>TempL for component-based UI, similar to JSX</li><li>Air for hot reload</li><li>ESBuild so we can use JS Libraries.</li></ul><p>Looking forward to it, don’t you? See you in part 4!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75c80cc5f470" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Personal Blog With HTMX + Go Part 2 — Integrating TailwindCSS]]></title>
            <link>https://medium.com/gravel-engineering/personal-blog-with-htmx-go-part-2-integrating-tailwindcss-412ebc4dcc97?source=rss-4c11fceb1e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/412ebc4dcc97</guid>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[htmx]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Muhammad Wyndham Haryata Permana]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 04:38:48 GMT</pubDate>
            <atom:updated>2023-10-18T04:38:48.304Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyqwCNQVKneGewL3J6IJKA.png" /></figure><h3><strong>Personal Blog With HTMX + Go Part 2 — Integrating TailwindCSS</strong></h3><p><em>This is the second part in my journey documenting my effort creating personal blog (which you can access </em><a href="https://mwyndham.dev/"><em>here</em></a><em>). You can read the previous part </em><a href="https://mwyndham.dev/articles/personal-blog-with-htmx-go-part-golang-templating"><em>here</em></a><em> or the Medium version instead </em><a href="https://mwyndham.medium.com/this-blogpost-also-posted-in-my-personal-blog-which-you-can-access-here-dd856c61001"><em>here</em></a><em>.</em></p><h3>Our Goal This Time</h3><p>Previously, we’ve manage to create a simple interactive elements with HTMX, this time, as promised, I would start integrating TailwindCSS into the processs. I will assume you have the code of the previous blogpost so this will continues directly from that.</p><h3>Short Intro on How Tailwind Works</h3><p>The basics of how tailwind can work in a Go project consists of these elements:</p><ul><li>tailwind cli</li><li>tailwind.config.js</li><li>base main.css file</li><li>target output css file (mine usually called tailwind.css)</li></ul><h3>Tailwind CLI</h3><p>requires npm and npx in the development PC. It was not required during deployment though.</p><p>This is how we mostly interact with tailwind. It’s job is basically to scan through the files that we dictates as the source, then tries to find the predefined tailwindcss classes by using pattern matching.</p><p>Once it finds the matching classes, it will then adds the correct css class with all of it’s properties into the output .css file we want. We then can just include this output css class into our HTML to render the css.</p><h3>tailwind.config.js</h3><p>This is the configuration file where we dictates how tailwind works in the particular project we’re in. Here we need to define the Path &amp; Pattern where we store our html files for tailwind to scan. More on that Later.</p><h3>Setting up Tailwind Into Our Project</h3><h3>Installing TailwindCSS CLI</h3><p>First, we need to install tailwind. You need to have npm installed in your development system. Don&#39;t worry, you don&#39;t need to have npm runtime during deployment, it will only needed to install the tailwind-cli.</p><p>As of the writing of this article, this is how you can install tailwind cli into your system:</p><pre>npm install -D tailwindcss</pre><p>It should then install the whole suites for you.</p><h3>Setting Up Configuration</h3><p>Next, we need to initiate tailwind in our project. To do this you only need to run:</p><pre>npx tailwindcss init</pre><p>Just make sure that your terminal is currently lives in the project directory you want to work on. Or else, it will just initiate wherever your terminal currently running on.</p><p>After running this terminal command, it will creates new file called tailwind.config.js that usually going to look like this:</p><pre>module.exports = {<br>      content: [&quot;./src/**/*.{html,js}&quot;],<br>      theme: {<br>        extend: {},<br>      },<br>      plugins: [],<br>    }</pre><p>The config as it is is alright, but we need to modify one thing. Let’s assume your project structure is like this:</p><pre>- /project-dir<br>    - template<br>        - template.go // This is the templating renderer we have previously<br>    - public<br>        - index.html<br>        - ...<br>    - main.go</pre><p>If we follow the structure above, we’re saving our *.html files in the public directory. So we need to tell tailwind that there is the place it should look for files to parse the classes.</p><p>To do that, modify the content section in the config above into this:</p><pre>...<br>module.exports = {<br>      content: [&quot;./public/**/*.html&quot;],<br>      ...<br>    }<br>...</pre><p>Which is basically telling tailwind to find every subdirectory of /public (hence the /**), and look for any file that has .html extension (/*.html).</p><h3>(Optional) Add VSCode Extensions</h3><p>There are 2 extensions in VSCode that will makes our life better when dealing with Tailwind:</p><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss">Tailwind CSS IntelliSense</a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode">Prettier</a></li></ul><p>These 2 things are works in tandem, as TailwindCSS IntelliSense will gives us the autocompletion things in tailwind which is very important as the pre-defined classes in tailwind is a lot.</p><p>Prettier on the other hand will automatically sort our css classes in the order that is consistent with Tailwind’s own class definition, which makes bulk rename of classes easier if you have multiple elements that has the same css class structure.</p><p>Both handles that by default so all you need to do is install it and you will immediately able to use it.</p><h3>(Optional) Neovim LSP</h3><p>If you sick of VSCode and uses Neovim instead, you can get similar functionality using <a href="https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#tailwindcss">LSPConfig</a> for TailwindCSS.</p><p>Setting up Prettier is a bit of a mixed bag though, as one of the most popular Neovim config for Prettier requires null-ls which is, as of the writing of this article, already enters Archive Mode and no more development is being done.</p><p>Alternatively, You can use <a href="https://github.com/iamcco/diagnostic-languageserver">Diagnostic Language Server</a> which includes Prettier, or try to hack around prettier LSP youself following <a href="https://prettier.io/docs/en/vim">Prettier’s own documentation in using it in VIM</a>.</p><h3>Creates Our Primary CSS File</h3><p>While not required, we may want to have custom css classes our own to handle several unique casses that tailwind may not able to solve easily.</p><p>To do that, first we create new directory, let say, dist where we would put our statically serveable files for our blog. After that, let&#39;s create a new main.css file:</p><pre>$&gt; mkdir dist<br>$&gt; cd dist<br>$&gt; echo &#39;@tailwind base;\n@tailwind components;\n@tailwind utilities;&#39; &gt; main.css</pre><p>Which then should creates a new main.css file that contains several information:</p><pre>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><h3>Compiling the Output</h3><p>After all of the configuration is done, now we need to test whether our configurations will output the correct tailwind css output or not. To compile, we can call this function:</p><pre>npx tailwindcss -i ./dist/main.css -o ./dist/tailwind.css</pre><p>If you’re familiar enough with any tools, it’s pretty clear what happened here:</p><ul><li>set the input file to be main.css in the /dist directory</li><li>set the output file to be tailwind.css in the /dist directory</li></ul><p>If all things well, you will see a new tailwind.css file in the /dist directory, and roughly look like this at the top:</p><pre>/*<br>! tailwindcss v3.3.2 | MIT License | https://tailwindcss.com<br>*/<br>...</pre><p>With this, all of the setup related to TailwindCSS is complete, we can start using it in our go project.</p><p><em>Note: For easier time in compiliing tailwind css, you may want to use </em><em>--watch flag to makes the tailwindcss cli keep alive and watching changes from our code.</em></p><p><em>I will revisit the whole build process in the later part, like using auto hot reload tools and makes tailwind be part of that instead of separate watcher.</em></p><h3>Serving CSS Files</h3><p>Just kidding, there is one more thing before we continue to using tailwind. Remember that we already have the .css files that we need, but as of right now, we&#39;re not yet serving that files to be accessible by our HTML code in the client.</p><p>To do that, we need to add 1 more routes in our main.go file that points to the whole directory. Luckily, echo has pretty good out-of-the-box solution for this.</p><p>You only need to add following lines in the main function:</p><pre>e.Static(&quot;/dist&quot;, &quot;dist&quot;)</pre><p>And basically any file inside the dist directory will be accessible via the /dist path in our URL.</p><p>Next, we need to point to our css file in our html file. In this example I will show how to add it to our index.html file:</p><pre>&lt;head&gt;<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;/dist/tailwind.css&quot; /&gt;<br>...<br>&lt;/head&gt;</pre><p>And now our tailwind css classes is accessible by our html code!</p><h3>Testing our Setup</h3><p>Now, lets try to add very simple background into our name_card.html. You still remember this file right? Let&#39;s add red background, a bit of padding, and rounded corner to the parent &lt;div&gt;:</p><pre>&lt;div class=&quot;bg-red-100 p-4 rounded-xl&quot;&gt; // Add these classes!<br>    &lt;p&gt;User Personal Information:&lt;/p&gt;<br>    &lt;ol&gt;<br>        &lt;li&gt;Name: {{.Name}}&lt;/li&gt;<br>        &lt;li&gt;Phone: {{.Phone}}&lt;/li&gt;<br>        &lt;li&gt;Email: {{.Email}}&lt;/li&gt;<br>    &lt;/ol&gt;<br>&lt;/div&gt;</pre><p>Now, let’s run our project again, but don’t forget to compile the output files first:</p><pre>npx tailwindcss -i ./dist/main.css -o ./dist/tailwind.css</pre><p>Now let’s run our code and we should have this as the output:</p><figure><img alt="output of the tailwind config, with red background, padding 4, and rounded-xl" src="https://cdn-images-1.medium.com/max/643/1*-I8sabx7ljuv4mVXOJMzdw.png" /></figure><p>Good!</p><h3>Wrapping Up, and What’s Next</h3><p>With this, the setting up TailwindCSS is complete. We made it works pretty flawlessly with our Go template file and renders the output properly.</p><p>In the next part, we will start to creates the whole thing about blogging in the first place: <strong>Markdown Editor</strong>. It would not reusing existing WYSIWYG editors out there like CkEditor or any Javascript-based Markdown Editor.</p><p>Instead, it will have fancy server side markdown rendering and has realtime preview of our markdown codes. And this time, we will actually uses HTMX to our advantage!</p><p>Seems exciting? please eagerly wait for the next part!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=412ebc4dcc97" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gravel-engineering/personal-blog-with-htmx-go-part-2-integrating-tailwindcss-412ebc4dcc97">Personal Blog With HTMX + Go Part 2 — Integrating TailwindCSS</a> was originally published in <a href="https://medium.com/gravel-engineering">Gravel Product &amp; Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neovim Presets are Bad for Beginner, Sincerely, from Noob Wasting 2 Month Learning It]]></title>
            <link>https://mwyndham.medium.com/neovim-presets-are-bad-for-beginner-sincerely-from-noob-wasting-2-month-learning-it-483db4db75bd?source=rss-4c11fceb1e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/483db4db75bd</guid>
            <category><![CDATA[neovim]]></category>
            <category><![CDATA[setup]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[vim]]></category>
            <dc:creator><![CDATA[Muhammad Wyndham Haryata Permana]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 13:32:57 GMT</pubDate>
            <atom:updated>2023-10-16T23:35:54.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQZvcPn3l9p-Ug_d27ezuw.png" /><figcaption>My Current Neovim Setup</figcaption></figure><p><em>I also published this blogpost in my personal blog which you can read </em><a href="https://mwyndham.dev/articles/neovim-presets-are-bad-for-beginner-sincerely-from"><em>here</em></a><em>.</em></p><p>First thing first, pardon me for being very ranty in this article. As I will unload my frustration learning NeoVim for the first time ever. There is something (very) good by the end of this though: <strong><em>I ended up loving Neovim</em></strong>. So if you’re interested, please keep reading.</p><h3>TL;DR</h3><p>If you’re absolute noob in Neovim, this is the advice from fellow noobs:</p><ul><li>Don’t immediately use neovim.</li><li>Use vim motion bindings in your existing IDE. familiarize yourself with it first.</li><li><strong>Starts Neovim from scratch.</strong> Don’t use presets like NVChad, LazyVim or LunarVim. It is not about bragging rights, it is actually easier just start from scratch, just a bit tedious.</li><li>Understands how configurations, plugins, packages works by doing it yourself.</li><li>Only then you can retry using presets, with the understanding of how customizations works.</li></ul><p>If you don’t know where to start, just follow ThePrimeagen <a href="https://youtu.be/w7i4amO_zaE?si=hP-6mExIL5UBJHW6">0 to LSP Tutorial</a>. There will be some breaking changes for some of the plugins used in that video, but it is easily solvable and by that time you should be comfortable dealing with Lua.</p><h3>Motivation</h3><p>I have been, frustrated, to say the least, with my experience with VSCode. At first, I felt it simple, fast(er) than my usual IDE (I am still Android Dev at that time) which is Android Studio, and has nice default keybinding that I can get used to very easily.</p><p>I move to VSCode after getting comfortable with my career-switch into Android-turned-Backend-turned-Fullstack roles that I am now. My stack is Golang, and during the switch, I use GoLand as my IDE, then to VSCode. I move away from GoLand simply because it’s expensive and if I can get equally good experience elsewhere for free, I’ll take that money back.</p><p>Long story short, I ended up hating it. Why? well:</p><ul><li>The more I add extensions, the worst it gets. And workspace setting is cumbersome yet useless.</li><li>Global search in the sidebar? come on.</li><li>When does it opens in the new tab and when will it open in the current tab? no one knows…</li><li>It does not have default key binding for go to implementation. Crazy for an IDE not have this by default.</li><li>It only allows create new file if you right click on a folder and not on a file. I usually ended up use cat or echo instead.</li><li>Sometimes it’s communication with gopls gets funky and my imports throws error everywhere.</li><li>And the most important part: <strong><em>It has default, uneditable, UI Type Face</em></strong>. I’m not talking about editor font, I’m talking about that UI font. It’s bland, uninspiring, and urrgghh I want to vomit for how “corporatey” it is. I know it’s minor thing but every time I opens VSCode I reel back for a minute seeing that default type face. I hate it so much.</li></ul><p>And I finally gave up after I have to learn Ruby on Rails (which I regret, btw) for my work, and VSCode just decided to just give up on me and everything just break. I had to go back to my IntelliJ subscription for the sake of not going insane. RubyMine is amazing, but it’s expensive.</p><h3>How The Adventure (Wrongly) Started</h3><p>I’ve known vim for a long time. I also have bad experience with it when trying to use it not knowing about vim motion at all. Then I heard about Neovim from Dreams of Code’s video on the <a href="https://youtu.be/i04sSQjd-qo?si=VoZfyQfgBVZ3K2-r">perfect setup for Go in Neovim</a>. I’m intrigued, why does people keep swear by vim being a good editor? hell, even IDE? I’m in the market of new IDE right know so anything goes.</p><p>Then I started to look around, and I found creators like ThePrimeagen (which also start my Primeagen React binge addiction) that also endorse Neovim. Okay, seems like at least it’s doable to learn Neovim properly.</p><p>This is where I got wrong.</p><p>I came in with the wrong mindset. I am looking for IDE replacement immediately. While I’m not averse to learn the nitty gritty (including vim motion), I want one ready to use setup that I can just <em>learn</em>. You know, the readymade stuff that has decent default stuff and I can modify it later kind of thing. Just like VSCode.</p><p>I started by followings the video I mentioned above, following the setup step by step, and got frustrated.</p><p>Before I explain my failings, let me explain what the setup entails. Mind you it is not bad setup, it just that I understand nothing as an absolute Neovim noob.</p><p>It uses NVChad, then for autocomplete it uses gopls and and nvim-lspconfig. For auto formatting it uses null-ls and it uses dlv as the debugger.</p><h3>My Misfortune with Everything</h3><p>First, turns out NVChad does not have nice defaults. It does not attempt to have out of the box support for <em>any</em> language at all. You have to deal with lsp yourself which is very daunting for total noob.</p><p>Secondly, I haven’t familiarized myself with Vim Motion. So following that tutorial is slow and painful, and I understand nothing. I don’t know how to make a new file and directory in Neovim, so I resort to use the terminal instad using mkdir and echo. Sometimes I accidentally delete files, other times my file is suddenly full of letter e or u.</p><p>Thirdly, I have zero understanding of lua and how it interacts with neovim. I have general understanding as a programmer, but I had zero understanding why the setup goes the way it does in that video. Lua file here, add config there, but why?</p><p>Then mason, man, mason. I very much understand and appreciate mason now, but at that time I hate it so much. It basically install it&#39;s own tooling for me, but then it causes issues as most of that tools is already installed in my system.</p><p>One of which, is golangci-lint. This tool introduce breaking changes in version 1.53, which is known by me and the reason why I pin my local version to 1.52. But when I setup NVChad with it, I ended up telling mason to install golangci-lint too, which, by default aims for the latest which is version 1.54. And I don&#39;t realize that mason does this.</p><p>It took me quite a while to find the reason why my linter broke whenever I uses Neovim but fine whenever I use other editor. Turns out whenever I use Neovim, it uses the golangci-lint installed by mason. I wasted a whole day solving this.</p><p>Then I reset everything and started fresh again. I still assume that NVChad is not my cup of tea. So I started again but this time using LazyVim. It goes roughly the same. This time even worse, because it “smart” installation process, I don’t know whatever it is happening behind the scene.</p><p>LazyVim also has it’s own keybinding on top of Neovim’s own vim motion. In the key binding guide section on it’s web, it has foreign keys such as &lt;leader&gt;, &lt;C&gt;, &lt;A&gt; etc.</p><p>And whenever I look up what &lt;leader&gt; is, all answer I get is &quot;it&#39;s up to you what &lt;leader&gt; key is&quot;. <em>Geez, I know</em>, but what I want to know is <strong>WHAT IS THE DEFAULT LEADER KEY IS</strong>.</p><p>Turns out it spacebar.</p><p>I just want to know that the leader key is a spacebar.</p><p>God damn looking for that information alone frustrates me.</p><h3>Simple vs Easy</h3><p>A lot of presets makes assumption on how much you, the potential users, already known about Vim. Usually, the assumption goes for familiarity with vim motion, understands how Lua works with neovim, or understanding the common key binding Vim has.</p><p>This assumption is not good for total beginner. Which, by definition, not even know what to ask for.</p><p>Presets tries to make someone familiar with Vim enjoys their new installation. They installs things such as Telescope by default. It has default, nice, File tree simulating VSCode, and it has mason integration from the get go.</p><p>But noobs does not understand nor need any of that. Yes it’s good if you’re familiar with common IDE and coming to Neovim and having “similar” interface. But the fundamental way to navigate Neovim itself is not addressed.</p><p><strong>For noob, the easiest way to learn using Neovim is to learn it from scratch</strong></p><h3>How I Ended Up Loving Neovim</h3><p>Okay, I’m 1.5 months in and have nothing to show except using vim mode in VSCode with a very dodgy result (NeoVIm extension in VSCode is actually using the local machine Neovim, so any configuration there would also affect the experience in the VSCode). I will rant about this another time but alas, this is not the time to rant about VSCode again.</p><p>Then, during a long weekend holiday, I finally I bit the bullet and says <strong>“hey, you know what? I have nothing to lose so I should just start everything from scratch and learn the damn thing”</strong>.</p><p>Then I opens up my watch later playlist and whip up <a href="https://youtu.be/w7i4amO_zaE?si=hP-6mExIL5UBJHW6">The Primeagen Video’s on 0 to LSP</a> which I already put off watching for some time now. I follow it step by step, first from just trying to put hello world in Lua, then followed by setting up Packer, Mason, LSP from sratch using <a href="https://github.com/VonHeikemen/lsp-zero.nvim">lsp-zero</a> and understanding what the hell actually is treesitter, lsp, and lsp config.</p><p>I don’t follow the tutorial to a T mind you, as the setup is around Typescript, JavaScript and Rust. I set my environment to a Golang instead by installing gopls LSP and golangci-lint-lsp instead. But honestly, kudos to Prime for being such a good teacher, I understand enough what actually happened to find my way around by myself.</p><p>By the end of the video, I have nice simple setup for Go development in Neovim. I have linter and autocomplete working, syntax highlighting working incredibly well, and find several life changing tools in it (man harpoon is actual game changer, and hijacking Telescope to do grep search is incredible).</p><p>I also realize that many things coming by default in IDE is not necessarily important. File tree is actually not necessary if you have quick and easy access to the whole directory via Explorer, along with incredible tools such as Telescope. So I choose to omit file tree alltogether.</p><p>After 3 days using this setup to totally famliarize myself (and also adding several plugins myself such as templ and tailwind css), I revisit the Dream’s of Code video above. And man, what a difference between understanding the context and not.</p><p>I now understand everything he said, every step of the way, and able to adapt several of the plugins he shows during the video even if he’s not using packer and I use it. I still does not ended up using NVChad as I already have good working setup and I don’t want to start over again. Plus, alot of things in NVChad honestly things that I does not need.</p><p>I skipped several things such as null-ls due to it already in archive mode, but I install all other things including delve which is also finally completes the transformation of my Neovim setup into an IDE by having native debugger.</p><h3>Where Am I Now</h3><p>As of the writing of this article, I’ve been using Neovim for 4 months, and I can only be more in love with it even more by the day.</p><p><strong>Vim motion is absolute godsend </strong>and I don’t know how can I navigate any other text document without it anymore, how vim prefer key combo rather than simultaneous keypress is honestly makes me wonder why we everything default to simultaneous keypress nowadays. Its easier for me to pres `space + p + o` in consecutive order rather than tryijg to press all of them at thr same time. And the most important thing:</p><blockquote><strong><em>I love having to enact hadouken everytime I want to do debug session.</em></strong></blockquote><p>I still doubting that Neovim makes me any more productive, faster or anything resembling measurable difference in how I deliver my code, but I appreciate it way more for being the more fun experience of coding.</p><p>My conclusion still stands though. Neovim preset is absolutely not the best way for any absolute Vim beginner to begin using Neovim.</p><p>Thanks.</p><p><em>P.S: I ended up never setting up Ruby on Rails stuff on Neovim due to our company moving on from using Ruby to full-on Golang. Another bullet dodged :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=483db4db75bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Find it Hard To Reuse Root Template in Go + HTMX, So I Made My Own (Little) Tools To Solve It]]></title>
            <link>https://medium.com/gravel-engineering/i-find-it-hard-to-reuse-root-template-in-go-htmx-so-i-made-my-own-little-tools-to-solve-it-df881eed7e4d?source=rss-4c11fceb1e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/df881eed7e4d</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[htmx]]></category>
            <dc:creator><![CDATA[Muhammad Wyndham Haryata Permana]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 08:13:46 GMT</pubDate>
            <atom:updated>2023-09-15T08:13:46.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISsIziETevR8eZk427W6bQ.png" /></figure><p>This blogpost is part of my documentation for my journey in implementing HTMX using Go for my personal Blog. <a href="https://mwyndham.dev/articles/i-find-it-hard-to-reuse-root-template">You can also read this blogpost in my own blog here.</a></p><p>HTMX has a very good integration with Golang, but that does not mean that everything is a rose and rainbow. This blogpost will show you one area where vanilla Go Template is lacking when it comes to integrating with HTMX: the partial vs page.</p><blockquote><em>Before we continue, please be mind that I am exploring this on my own. So if what I found here is basically a non-issue (like there are more obvious solution) or I just jumped the shark with my gung-ho solution, then please tell me about it! Thanks!</em></blockquote><h3>The hx-push-url Scenario</h3><p>Let’s imagine you have a index page that has button to navigate to a content. You’re using hx-get to transition to that content. Now if the user chooses to refresh the page, you will be back to the index without the content part of the page.</p><p>Let’s assume you do not want that because it will be a bad user experience. You want if user refresh the page, they will be still in the content part of the UI.</p><p>HTMX gives us helpful tools such as hx-push-url to push our hx-get url towards browser history. Now, even if user refresh the page, it will still accessing the content part of the view. But now you have bigger problem.</p><p>Let’s see what’s inside index page:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    ... <br>&lt;/head&gt;<br>&lt;body id=&quot;root-body&quot;&gt;<br>    &lt;p&gt;This is Index body&lt;/p&gt;<br>    &lt;button hx-get=&quot;/content&quot; hx-target=&quot;#root-body&quot; hx-push-url=&quot;true&quot;&gt;<br>        Navigate to Content<br>    &lt;/button&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>And then let’s see what’s inside content part:</p><pre>&lt;p&gt;This is content body&lt;/p&gt;<br>&lt;button hx-get=&quot;/&quot; hx-target=&quot;#root-body&quot; hx-push-url=&quot;true&quot;&gt;<br>    Back to index<br>&lt;/button&gt;</pre><p>We immediately see that content does not looks as complete as index. It was not a valid HTML, it lacks head, it lacks body, etc. Which is understable, as we want content as some sort of partials that can be cheaply sent towards the user.</p><p>But now because we push the url towards browser history, we let user access this incomplete partials. Whenever user refreshes the page (in this example is whenever user access the /content url), they will be greeted with incomplete page that only consist of the partials we push previously.</p><p>We can solve this by checking whether the request was triggered by HTMX or not. If it was sent by HTMX, let’s send a partials, and if it was not triggered by HTMX, let’s send a full page with the partials inside it.</p><p>To see whether a request were triggered by HTMX, we could just check whether HX-Request header exist or not. Easy.</p><p>But the bigger problem is how will we provide the templates for each scenario.</p><h3>Duplicates of Templates</h3><p>Now, how do we provide two different-but-same template in which ones would be composed as a page but the other just as a partial? Golang templating has one weakness: <strong>reusing top-level component in nested scenario</strong>. It is rather easy in Go to compose bigger component from smaller ones:</p><pre>{{define &quot;page&quot;}}<br>    &lt;div&gt;<br>        {{template &quot;top&quot; .}}<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>        {{template &quot;right&quot; .}}<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>        {{template &quot;bottom&quot; .}}<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>        {{template &quot;left&quot; .}}<br>    &lt;/div&gt;<br>{{end}}</pre><p>But whenever we need to reuse components in from the outer layer of the template, says, the &lt;html&gt; tag and &lt;header&gt; where it wraps around another component like this:</p><pre>&lt;!-- How do we reuse this whole html--&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>        ... <br>    &lt;/head&gt;<br>    &lt;body id=&quot;root-body&quot;&gt;<br>    &lt;!-- but allows to add any template here? --&gt;<br>    {{template &quot;content&quot; .}}<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>It will starts to be very hard very quickly. How do we reuse a parent component with customizable inner components?</p><p>One possible way to work around this issue is to provide 2 different template. For example, let say we have content.html and content_page.html to represent partial and page respectively.</p><p>For example content.html:</p><pre>{{define &quot;content&quot;}}<br>    &lt;p&gt;This is content body&lt;/p&gt;<br>    &lt;button hx-get=&quot;/&quot; hx-target=&quot;#root-body&quot; hx-push-url=&quot;true&quot;&gt;<br>       Back to index<br>    &lt;/button&gt;<br>{{end}}</pre><p>And for the content_page.html:</p><pre>{{define &quot;content_page&quot;}}<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>        ... <br>    &lt;/head&gt;<br>    &lt;body id=&quot;root-body&quot;&gt;<br>        {{template &quot;content&quot; .}}<br>    &lt;/body&gt;<br>&lt;/html&gt;<br>{{end}}</pre><p>And this is how it will looks in the file system:</p><pre>- /page<br>    - content.html<br>    - content_page.html<br>    - index.html<br>    - index_page.html<br>- /component<br>    - head_tags.html<br>    - header.html<br>    - footer.html</pre><p>You can immediately see the issues with this approach. <strong>First</strong>, we will always need to have duplicates of templates. Even if we’re extracting as much component from the template as possible, the minimum each *_page.html could look like:</p><pre>{{define &quot;content_page&quot;}}<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>        {{template &quot;head_tags&quot; .}}<br>    &lt;/head&gt;<br>    &lt;body id=&quot;root-body&quot;&gt;<br>        {{template &quot;content&quot; .}}<br>    &lt;/body&gt;<br>&lt;/html&gt;<br>{{end}}</pre><p>Or even something ugly like this:</p><pre>{{define &quot;content_page&quot;}}<br>{{template &quot;upper_page&quot; .}} // including DOCTYPE and html definition<br>&lt;body id=&quot;root-body&quot;&gt;<br>    {{template &quot;content&quot; .}}<br>&lt;/body&gt;<br>{{template &quot;lower_page&quot; .}} // including the closing tags for html<br>{{end}}</pre><p>Where we require 2 different templates to always be in pair (see upper_page and lower_page template).</p><p><strong>Secondly</strong>, we will need to keep track of 2 different file all the time, both the non page and the page ones, all while requires us to specify which ones to render each time we know it should be rendered as a page. This is tedious and error prone!</p><p>Another solution is to pass the raw html as a string value and use it as a template params, something like this:</p><pre>body := `<br>&lt;p&gt;This is content body&lt;/p&gt;<br>    &lt;button hx-get=&quot;/&quot; hx-target=&quot;#root-body&quot; hx-push-url=&quot;true&quot;&gt;<br>       Back to index<br>    &lt;/button&gt;<br>`<br>template.ExecuteTemplate(w, &quot;index&quot;, body)</pre><p>But this cause so much more issue, like having either HTML directly in go page or somehow you need to manually parse HTML without using template tools, it’s an unsustainable work around IMHO.</p><p>But then how do we solve it? should we go all the way using templating tools/framework such as TempL, Hugo, etc? Well, not quite as this is actually a solved issue but the solution is a bit unexpected (at least for me).</p><h3>(Obviously) You can have more than 1 template!</h3><p>Turns out Go do provide some sort of solution to this, but not in the way that you might expect.</p><p>So, if we’re looking at most of the template examples out there in the web, most of the time they will always show you only 1 instance of template.Template. For example:</p><pre>...<br>td := Todo{&quot;Test templates&quot;, &quot;Let&#39;s test a template to see the magic.&quot;}<br>t, err := template.New(&quot;todos&quot;).Parse(&quot;You have a task named \&quot;{{ .Name}}\&quot; with description: \&quot;{{ .Description}}\&quot;&quot;)<br>...</pre><p>The code above was taken directly from <a href="https://blog.gopheracademy.com/advent-2017/using-go-templates/">GopherAcademy’s tutorial on Template</a>. And they’re not alone in this, <a href="https://echo.labstack.com/docs/templates">Labstack’s Echo’s own guide on using template is only using 1 instance of template</a>. It is not wrong per se to do this as it shows the example on using template. But if you think about it, you realize that there is nothing stopping you to have more than 1 instance of template.Template!</p><p>Now let’s imagine instead of just having 1 template.Template instance, we have a map[string]*template.Template instead, and we&#39;re composing each page as it&#39;s own template, mapped!</p><p>But how does this solve the problem exactly? well, <strong>the definition of a template is only relevant to what other component available during the parsing</strong>.</p><p>It does not care if there is multiple instance of the same definition as long as they does not parsed into 1 template at the same time. So for example we can have as much as {{define &quot;body&quot;}} definition as possible, as long as during ParseFiles, we only include one of those.</p><p>Now with that knowledge, we know we could have 1 template each to represent a single page, we can realistically have this (let’s say this is root.html):</p><pre>{{define &quot;root&quot;}}<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>        ...<br>        {{template &quot;head&quot; .}}<br>    &lt;/head&gt;<br>    &lt;body id=&quot;root-body&quot;&gt;<br>        {{template &quot;body&quot; .}}<br>    &lt;/body&gt;<br>&lt;/html&gt;<br>{{end}}</pre><p>Which should represent our “root” structure. Now we can try to represent the index page, let say we name it index.html:</p><pre>// This will render to the &quot;head&quot; section of the root<br>{{define &quot;head&quot;}}  <br>    &lt;title&gt;Page Index&lt;/title&gt;<br>{{end}}<br><br>// This will render to the &quot;body&quot; section of the root,<br>// and we assume this is the partials.<br>{{define &quot;body&quot;}}   <br>    &lt;p&gt;This is Index body&lt;/p&gt;<br>    &lt;button hx-get=&quot;/content&quot; hx-target=&quot;#root-body&quot; hx-push-url=&quot;true&quot;&gt;<br>        Navigate to Content<br>    &lt;/button&gt;<br>{{end}}</pre><p>And this is also how we represent the content.html:</p><pre>{{define &quot;head&quot;}}<br>    &lt;title&gt;Page Content&lt;/title&gt;<br>{{end}}<br><br>{{define &quot;body&quot;}}<br>    &lt;p&gt;This is content body&lt;/p&gt;<br>    &lt;button hx-get=&quot;/&quot; hx-target=&quot;#root-body&quot; hx-push-url=&quot;true&quot;&gt;<br>        Back to index<br>    &lt;/button&gt;<br>{{end}}</pre><p>Now we can try to reuse our root.html files whener we parse the files during the template initiation:</p><pre>tmpIndex := &amp;template.Template{}<br>template.Must(tmp.ParseFiles(&quot;/path/to/root.html&quot;, &quot;/path/to/index.html&quot;))<br>templates[&quot;index&quot;] = tmpIndex<br>...<br>tmpContent := &amp;template.Template{}<br>template.Must(tmp.ParseFiles(&quot;/path/to/root.html&quot;, &quot;/path/to/content.html&quot;))<br>templates[&quot;content&quot;] = tmpContent</pre><p><strong>And Voila!</strong> we’re basically reused the root component into each of the template instance. Now we can simply selectively render either the root or the partial component (in this example the body template):</p><pre>//to render the page<br>templates[&quot;index&quot;].ExecuteTemplate(w, &quot;root&quot;, nil)<br>//to render the partial<br>templates[&quot;index&quot;].ExecuteTemplate(w, &quot;body&quot;, nil)</pre><h3>Generalizing the Solution and Wrap It as a Library</h3><p>The solution above seems easy but managing templates for each page can be a bit of a mess. This does not include repeat task where you need to supply the components needed to compose the partial in the first place (if you decided to do micro-components as such):</p><pre>template.Must(tmp.ParseFiles(&quot;/path/to/root.html&quot;, &quot;/path/to/index.html&quot;, &quot;/path/to/other/components.html&quot;...)) // This is repeating task.</pre><p>Hence I made this simple library which you can find <a href="https://github.com/muhwyndhamhp/tmax">here</a>. This library does 4 things:</p><ul><li>scan recursively through every subdirectory of component, and append them to every template during parsing files.</li><li>map every specified page partials as it’s own separate template instance</li><li>render the correct UI from simple pattern (you can do &quot;root#index&quot; to render a page or just &quot;index&quot; for partials for example)</li><li>provide common interface for framework (<strong><em>currently only for Labsctack Echo</em></strong>).</li></ul><p>How to use it? first you can pull my library:</p><pre>go get github.com/muhwyndhamhp/tmax</pre><p>Then, you can attach the template renderer to echo instance:</p><pre>// This is the interface to initiate template renderer (currently only for labstack echo)<br>func NewEchoTemplateRenderer(e *echo.Echo, rootName, viewName, componentPath string, viewPaths ...string) error<br>// Example of implementation<br>err := tmax.NewEchoTemplateRenderer(e, &quot;root&quot;, &quot;body&quot;, &quot;public/components&quot;, &quot;public/views&quot;,...)<br>if err != nil {<br>    panic(err)<br>}</pre><p>Each and every function parameters described:</p><ul><li>rootName -&gt; the definition of the root componenet (eg. &quot;root&quot;)</li><li>viewName -&gt; the definition of the partial component (eg. &quot;body&quot;)</li><li>componentPath -&gt; the parent path that contains all of the &quot;*.html&quot; templates (except the partial components which needs to be in separate directory)</li><li>viewPaths -&gt; variadic value where you can pass all of the partial component, it will scan recursively but you can pass each component individually if you wanted it.</li></ul><p>Then whenever you want to render , you can do it this way:</p><pre>func main() {<br>    e := echo.New()<br>    ...<br>    e.GET(&quot;/&quot;, func(c echo.Context) error {<br>        if isHXRequest(c) {<br>            // This will render partial<br>            return c.Render(http.StatusOK, &quot;index&quot;, nil) <br>        } else {<br>            // This will render page<br>            return c.Render(http.StatusOK, &quot;root#index&quot;, nil) <br>        }<br>    })<br>...<br>}<br><br>// This is function to see whether the request comes from HTMX or not<br>func isHXRequest(c echo.Context) bool {<br>    ...<br>}</pre><p>And I would assume this is how you would manage the template directory structure:</p><pre>- /public // it does not have to be public, can be any directory<br>    - /views // where you put the partials<br>    - /components<br>        - root.html // you don&#39;t have to put it here, any sub directory inside the component folder will do.<br>        - /atomic<br>            - search.html<br>            - text-area.html<br>            - ...<br>        - ... any template html file or directory you want</pre><p>That’s it!</p><h3>Final Words</h3><p>That’s my journey in solving the issue about reusing root structure in a Go Template project. This solution does not necessarily required you to use HTMX but I find the usecase while building something using it.</p><p>What do you think? is it helpful? is it good? or is it unnecessary and I jump the shark by doing things this way?</p><p>Let me know what you think!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df881eed7e4d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gravel-engineering/i-find-it-hard-to-reuse-root-template-in-go-htmx-so-i-made-my-own-little-tools-to-solve-it-df881eed7e4d">I Find it Hard To Reuse Root Template in Go + HTMX, So I Made My Own (Little) Tools To Solve It</a> was originally published in <a href="https://medium.com/gravel-engineering">Gravel Product &amp; Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Personal Blog with HTMX + Go Part 1 — Golang Templating Setup]]></title>
            <link>https://medium.com/gravel-engineering/this-blogpost-also-posted-in-my-personal-blog-which-you-can-access-here-dd856c61001?source=rss-4c11fceb1e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd856c61001</guid>
            <category><![CDATA[htmx]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Muhammad Wyndham Haryata Permana]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 15:55:21 GMT</pubDate>
            <atom:updated>2023-10-18T04:39:08.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFnSqh9ZAlA9_WOvBhDIyQ.png" /></figure><p>This blogpost also posted in my personal Blog which you can access <a href="https://mwyndham.dev/articles/personal-blog-with-htmx-go-part-golang-templating">here</a>.</p><h3>Preface</h3><p>Recently, I just made a post where I announce that I’ve made a personal blog from scratch using HTMX and Golang as the backbone of it, skipping JavaScript Framework alltogether. You can read the <a href="https://mwyndham.dev/articles/i-made-this-website-using-htmx-go-in">blogpost here</a>.</p><p>This will be the part 1 of many on my HTMX + Go journey, where it will document my process on setting up HTMX first time for my personal blog (which if you read this article in Medium, you can visit it <a href="https://mwyndham.dev/">here</a>).</p><p>I wont be covering the process in detail as in tutorials, but more of a journal where I document what I’m doing, what is my blockers, and how I overcome (or side-step) it, along with various knick knacks I found during the process.</p><p>This series will skip a lot of basic stuff, so I don’t expect complete newbie to follow along. Questions is greatly appreciated though so don’t be shy to just hit me with it in the comment below!</p><h3>The Setting Up</h3><h3>Template Renderer</h3><p>First I need to make sure that I can serve HTML files using <a href="https://github.com/labstack/echo">Labstack Echo</a>, as it is my personal HTTP Router of choice. <a href="https://echo.labstack.com/docs/templates">If we follow the template section of Echo’s Guide</a>, we should provide some sort of “Template Renderer” which implement Echo’s own Renderer interface.</p><p>To do that, I came up with this:</p><pre>type Template struct {<br>    Templates *template.Template<br>}<br><br>func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {<br>    return t.Templates.ExecuteTemplate(w, name, data)<br>}<br><br>func NewTemplateRenderer(e *echo.Echo, paths ...string) {<br>    tmpl := &amp;template.Template{}<br>    for i := range paths {<br>        template.Must(tmpl.ParseGlob(paths[i]))<br>    }<br>    t := newTemplate(tmpl)<br>    e.Renderer = t<br>}<br><br>func newTemplate(templates *template.Template) echo.Renderer {<br>    return &amp;Template{<br>        Templates: templates,<br>    }<br>}</pre><p>The idea with this template renderer is that I can supply variadics of string which represent&#39;s the path where I put the html template files. This is necessary due to template.ParseGlob unable to recursively look for template files. <strong><em>Don&#39;t forget that you should not import the </em></strong><strong><em>html/template!! but import </em></strong><strong><em>text/template instead!</em></strong></p><h3>Hello World</h3><p>Now we can test it by creating simple echo server and try to serve simple html file. Let’s start with the usual Hello World, by creating a new index.html file in public path:</p><pre>{{define &quot;index&quot;}}<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Hello, World!&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;p&gt;Hello, World!&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br>{{end}}</pre><p>This is just simple html file. But notice the double curly braces ({{}}) sandwiching the html file. This is the go templating tag. In the example above, I simply define a new template with the name of index which I can access directly in go code later.</p><p>Now let’s create a simple echo server:</p><pre>...<br>func main() {<br>    e := echo.New()<br>    <br>    // Little bit of middlewares for housekeeping<br>    e.Pre(middleware.RemoveTrailingSlash())<br>    e.Use(middleware.Recover())<br>    e.Use(middleware.RateLimiter(middleware.NewRateLimiterMemoryStore(<br>        rate.Limit(20),<br>    )))<br><br>    // This will initiate our template renderer<br>    template.NewTemplateRenderer(e, &quot;public/*.html&quot;)<br>    e.GET(&quot;/hello&quot;, func(e echo.Context) error {<br>        return c.Render(http.StatusOK, &quot;index&quot;, nil)<br>    })<br><br>    e.Logger.Fatal(e.Start(&quot;:4040&quot;))<br>}<br>...</pre><p>This echo server will run in port :4040 and will render any file .html that was located in the public directory. Then I also create a new endpoint /hello where it will serve the index. Run it and supposedly I should get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*Q2rurmusZ8ZrYq22jvYn-w.png" /></figure><h3>Passing Value to Template</h3><p>Now I need to see whether I can pass dynamic values to the template. That’s the point of templating after all. First, I need to modify the index.html code a little bit:</p><pre>...<br>&lt;p&gt;Hello, World!&lt;/p&gt;<br>&lt;p&gt;Greetings, {{.Name}}!&lt;/p&gt;<br>...</pre><p>Once again the double curly braces. In this example I want to pass a value named Name into the html file. Then I need to modify my server a bit:</p><pre>...<br>e.GET(&quot;/hello&quot;, func(e echo.Context) error {<br>    res := map[string]interface{}{<br>        &quot;Name&quot;: &quot;Wyndham&quot;,<br>    }<br>    return c.Render(http.StatusOK, &quot;index&quot;, res)<br>})<br>...</pre><p>This will make the renderer take the value of res as the root value, and will find any child value with the key of Name. It should then render the result like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*gEyOOKRoa7RVVind6ZVk1g.png" /></figure><h3>Nested Template and Passing Value Between Template</h3><p>Now the last part before we start dealing with HTMX is that whether I could nest another template into the index template. To do that, I created this simple template file named name_card.html:</p><pre>{{define &quot;name_card&quot;}}<br>&lt;div&gt;<br>    &lt;p&gt;User Personal Information:&lt;/p&gt;<br>    &lt;ol&gt;<br>        &lt;li&gt;Name: {{.Name}}&lt;/li&gt;<br>        &lt;li&gt;Phone: {{.Phone}}&lt;/li&gt;<br>        &lt;li&gt;Email: {{.Email}}&lt;/li&gt;<br>    &lt;/ol&gt;<br>&lt;/div&gt;<br>{{end}}</pre><p>Then we need to modify the index.html another bit. First delete the greetings line, then add the following:</p><pre>...<br>&lt;p&gt;Hello, World!&lt;/p&gt;<br>&lt;!-- Delete this line &lt;p&gt;Greetings, {{.Name}}!&lt;/p&gt; --&gt;<br>{{template &quot;name_card&quot; .}}<br>...</pre><p>Then we need to once again modify our server:</p><pre>...<br>e.GET(&quot;/hello&quot;, func(e echo.Context) error {<br>    res := map[string]interface{}{<br>        &quot;Name&quot;: &quot;Wyndham&quot;,<br>        &quot;Phone&quot;: &quot;8888888&quot;,<br>        &quot;Email&quot;: &quot;skyscraper@gmail.com&quot;,<br>    }<br>    return c.Render(http.StatusOK, &quot;index&quot;, res)<br>})<br>...</pre><p>Now if I’m right here, I should be able to render the personal info like so. The logic here is that we’re passing a map of interface with 3 key pair value containig Name, Phone, Email.</p><p>And we&#39;re accessing those in the name_card by using the double curly braces. But to make sure that the name_card template receive the values, we need to pass the res values into them hence the extra . in the {{template &quot;name_card&quot; .}} inside the index.html.</p><p>And sure enough:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*k-We12WNLuGZohy_LF1MLA.png" /></figure><p>We manage to nest multiple template file and pass around a variables between them! Now that we’re done with the templating setup, let’s touch HTMX a little bit.</p><h3>Using HTMX to Reveal a Contact Info</h3><p>I would create a simple view where It would list a name and a button next to it to reveal the contact info. To do that, first I need to add HTMX to this project. To make things simple, I would add it via CDN for the moment:</p><pre>&lt;head&gt;<br>    ...<br>    &lt;script src=&quot;https://unpkg.com/htmx.org@1.9.5&quot; integrity=&quot;sha384-xcuj3WpfgjlKF+FXhSQFQ0ZNr39ln+hwjN3npfM9VBnUskLolQAcN80McRIVOPuO&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;</pre><p>This will add the HTMX into our code via CDN. Now we need to modify our index.html once again to not directly reveal the user info:</p><pre>...<br>&lt;p&gt;Hello, World!&lt;/p&gt;<br>&lt;!-- Delete this line {{template &quot;name_card&quot; .}} --&gt;<br>&lt;div id=&quot;user-info&quot;&gt;<br>    &lt;p&gt;{{.Name}}&lt;/p&gt;<br>    &lt;button hx-get=&quot;/get-info&quot; hx-target=&quot;#user-info&quot; hx-swap=&quot;innerHTML&quot;&gt;Reveal Info&lt;/button&gt;<br>&lt;/div&gt;<br>...</pre><p>This will basically set the UI to only reveal the name part, and setting up a button where it will hit the /get-info endpoint, and then target the #user-info element and swap the inner part of the target element (basically left the &lt;div&gt; alone and change everything inside the &lt;div&gt;).</p><p>Okay, that seems like a lot of jargon. I won’t explain it here as it has been told better in the htmx webpage which you can access <a href="https://htmx.org/">here</a>. Now let’s move on by creating new endpoint handler in our server that should be able to handle the /get-info path:</p><pre>e.GET(&quot;/get-info&quot;, func(c echo.Context) error {<br>    res := map[string]interface{}{<br>        &quot;Name&quot;: &quot;Wyndham&quot;,<br>        &quot;Phone&quot;: &quot;8888888&quot;,<br>        &quot;Email&quot;: &quot;skyscraper@gmail.com&quot;,<br>    }<br>    return c.Render(http.StatusOK, &quot;name_card&quot;, res)<br>})</pre><p>It is almost identical to the /hello ones but it has two major difference:</p><ol><li>change the path to /get-info, which is obvious.</li><li>change the target template to name_card.</li></ol><p>But wait! isn’t name card wasn’t a valid HTML file? it does not has doctype, it does not have header, etc. and Yes, you&#39;re correct. But this is <strong>HTMX in action</strong>. It will not swap the whole page, but <strong>only the targeted part,</strong> in this case user-info element that we specify in the index.html.</p><p>Now, without further ado, let’s run the server and see what happened:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FduSbzGXEvfQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DduSbzGXEvfQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FduSbzGXEvfQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e6d81d4cd0c77775fbbe58cbef25c11/href">https://medium.com/media/1e6d81d4cd0c77775fbbe58cbef25c11/href</a></iframe><p>Holly molly! that works! Now that we now HTMX works well with Go Template, we can finally working on our blogging site. But unfortunately, I won’t be covering it in this article. I would comeback soon though, it won’t be long!</p><h3>Conclusion</h3><p>Thanks for reading this blogpost. The takeaway here is that Go Template is very flexible to use and it also works well with HTMX, at least in this small simple scope here. In the following blogpost we will create a basic CRUD where we can store our articles in the DB and access it in the browser.</p><p>A little bit spoiler though: I won’t be using that much HTMX in there, or the after, and after that too. Turns out You don’t need that much HTMX when it comes to blogging web. Shocking I know. But we will use it extensively when we came to the part where we create our pagination, search, and reatime Markdown renderer.</p><p>So look forward to that! Thanks for reading!</p><p>EDIT! The second part is out! you can read it here:</p><p><a href="https://medium.com/gravel-engineering/personal-blog-with-htmx-go-part-2-integrating-tailwindcss-412ebc4dcc97">https://medium.com/gravel-engineering/personal-blog-with-htmx-go-part-2-integrating-tailwindcss-412ebc4dcc97</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd856c61001" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gravel-engineering/this-blogpost-also-posted-in-my-personal-blog-which-you-can-access-here-dd856c61001">Personal Blog with HTMX + Go Part 1 — Golang Templating Setup</a> was originally published in <a href="https://medium.com/gravel-engineering">Gravel Product &amp; Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go + HTMX + Tailwind — Create Beautiful Responsive Web Apps (?!) Without Javascript (sort of)]]></title>
            <link>https://medium.com/gravel-engineering/go-htmx-tailwind-create-beautiful-responsive-web-apps-without-javascript-sort-of-3d096c57524b?source=rss-4c11fceb1e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d096c57524b</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[htmx]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Muhammad Wyndham Haryata Permana]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 05:58:54 GMT</pubDate>
            <atom:updated>2023-08-21T04:48:32.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nn2VHORgQ79oFOKFW-eFfA.png" /><figcaption>HTMX Attributes in a HTML</figcaption></figure><h3><strong>Go + HTMX + Tailwind — Create Beautiful Responsive Web Apps (?!) Without Javascript (sort of)</strong></h3><p>Yes, you read the title correct. There is a way to create a whole suite of Web Apps without you need to touch Javascript. No, I’m not crazy.</p><p>And the solution might be viable even for your next billion dollar startup ideas. It is so viable in fact, that it was mind boggling how convulted and difficult front end dev nowadays with React, Angular, and Vue.</p><h3>What’s the secret?</h3><p>The secret ingredient is actually only 1 thing: HTMX. HTMX is a tools that allows us to extend the functionality of a HTML and promotes Hypermedia Driven web development.</p><p>But what does HTMX does exactly? I will quote the first paragraph in their <a href="https://htmx.org/">homepage</a>:</p><blockquote><em>htmx gives you access to </em><a href="https://htmx.org/docs/#ajax"><em>AJAX</em></a><em>, </em><a href="https://htmx.org/docs/#css_transitions"><em>CSS Transitions</em></a><em>, </em><a href="https://htmx.org/docs/#websockets"><em>WebSockets</em></a><em> and </em><a href="https://htmx.org/docs/#sse"><em>Server Sent Events</em></a><em> directly in HTML, using </em><a href="https://htmx.org/reference/#attributes"><em>attributes</em></a><em>, so you can build </em><a href="https://htmx.org/examples/"><em>modern user interfaces</em></a><em> with the </em><a href="https://en.wikipedia.org/wiki/HATEOAS"><em>simplicity</em></a><em> and </em><a href="https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm"><em>power</em></a><em> of hypertext</em></blockquote><h3>…What? That’s it?</h3><p><strong>Yes, that’s it!</strong> but think again for a second. What makes a web app… a web app? What makes web app differs from the good old Static Webpages? The key difference between the two is basically 1 thing and 1 thing only: <strong>Responsive.</strong></p><p>It reacts to user input quickly, it does not require you to change webpage to do simple things. Everything is in a beautiful modals, popups, and floating item that reacts to your behaviour.</p><p>HTMX <strong>offers</strong> such responsiveness by using several tricks that allows us to replace HTML element with server-sent response that also contains HTML.</p><p>Let see following’s example:</p><pre>&lt;script src=&quot;https://unpkg.com/htmx.org@1.9.4&quot;&gt;&lt;/script&gt;<br>  &lt;!-- have a button POST a click via AJAX --&gt;<br>&lt;button hx-post=&quot;/clicked&quot; hx-swap=&quot;outerHTML&quot;&gt;<br>    Click Me<br>&lt;/button&gt;</pre><p>and in the backend (which is Go) we create simple router that returns HTML:</p><pre>e := echo.New()<br>e.POST(&quot;/clicked&quot;, func(c echo.Context) error {<br>    return c.HTML(http.StatusOK, `<br>    &lt;p&gt;You Clicked Me!&lt;/p&gt;<br>    `)<br>})</pre><p>In action, it will look like this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fc2Qc_1FXolA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dc2Qc_1FXolA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fc2Qc_1FXolA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/728924d9445f8d9fb87d566000b84529/href">https://medium.com/media/728924d9445f8d9fb87d566000b84529/href</a></iframe><p>This might sound simple but anyone that has ever working in Web Front End development will swear that this is mindblowing.</p><p>And this is the basis of responsivity in HTMX. It allows us to <strong>replace existing element</strong> on a page with <strong>REST API response</strong> from the server. <strong><em>It introduce responsivity and reactivity to an old technology of Static Web Page.</em></strong></p><h3>Now to the Meat of the Matter</h3><p>This will be <strong>a series of articles</strong> documenting all of my effort in learning how to create full responsive web apps using just Go + HTMX + Tailwind CSS. By the end of the series, we will be able to create something like this: <strong><em>A Blogging App that has realtime Markdown Renderring done in the Backend</em></strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkDZ9lASnqqM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkDZ9lASnqqM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkDZ9lASnqqM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf99f6d5591793a4160e0b38cb1ce379/href">https://medium.com/media/bf99f6d5591793a4160e0b38cb1ce379/href</a></iframe><p>In the next article, I will present the basic setup that was needed to create a HTMX + Go based web. It will introduce you to several HTMX attributes that corresponds to various functionality.</p><p>See you there!</p><h3>Next Up</h3><ol><li>Setting up Go + HTMX : Create Responsive Web Pages. (Work in Progress)</li><li>Introducing Tailwind in a Server Side Rendered Web Apps. (Work in Progress)</li><li>Rendering Markdown without JavaScript. (Work in Progress)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d096c57524b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gravel-engineering/go-htmx-tailwind-create-beautiful-responsive-web-apps-without-javascript-sort-of-3d096c57524b">Go + HTMX + Tailwind — Create Beautiful Responsive Web Apps (?!) Without Javascript (sort of)</a> was originally published in <a href="https://medium.com/gravel-engineering">Gravel Product &amp; Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using custom struct for JSONB Type in SQLC]]></title>
            <link>https://medium.com/gravel-engineering/using-custom-struct-for-jsonb-type-in-sqlc-f0350d4df967?source=rss-4c11fceb1e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0350d4df967</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sqlc]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Muhammad Wyndham Haryata Permana]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 00:37:53 GMT</pubDate>
            <atom:updated>2023-08-10T00:41:52.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBUqIIHKhCeoWAyRb_bzHw.png" /><figcaption>Spoiler for Solution</figcaption></figure><p>Before reading this content, I highly recommend you follow the <a href="https://medium.com/gravel-engineering/using-sqlc-for-orm-alternative-in-golang-ft-go-migrate-pgx-b9e35ec623b2">Using SQLC for ORM alternative</a> as prior reading material. This note will continues where we left of that part.</p><h3>How SQLC Handles JSONB Types By Default</h3><p>It’s common for any models to have metadata column that may contains any form of data that may related to our models but not classifiable:</p><pre>CREATE TABLE products (<br>    id BIGSERIAL PRIMARY KEY,<br>    name varchar NOT NULL,<br>    description TEXT,<br>    slug varchar NOT NULL,<br>    public_metadata jsonb NOT NULL DEFAULT &#39;{}&#39;::jsonb,<br>    private_metadata jsonb NOT NULL DEFAULT &#39;{}&#39;::jsonb,<br>);</pre><p>In this example we have public_metadata and private_metadata. By default, sqlc will assign those jsonb to a byte array:</p><pre>type Product struct {<br>    ID int64<br>    Name string<br>    Description pgtype.Text<br>    Slug string<br>    PublicMetadata []byte<br>    PrivateMetadata []byte<br>}</pre><p>This might be alright, but sometimes we want to at least have some structure to it. For example, we know that the metadata format will always be consist of type map[string]string or even slightly more abstract map[string]interface{}.</p><p>Only having []byte will requires us to cast and convert the format.</p><h3>How to Add Type definition for JSONB</h3><p>To solve that issue, we can do following things. First we may define our new type that we want that value to be assigned on:</p><pre>package typeext<br><br>// in this example I want to assign it to map[string]interface{}<br>type JSONB map[string]interface{}<br><br>// You can put any kind of type tho, including struct<br>type CustomParams struct{<br>    Params1 string<br>    Params2 int64<br>}</pre><p>Then we can just put it in the sqlc.yaml inside the gen: go: segment:</p><pre>gen:<br>    go:<br>        package: &quot;db&quot;<br>        sql_package: &quot;pgx/v5&quot;<br>        out: &quot;db&quot;<br>        overrides:<br>            - column: &quot;products.public_metadata&quot;<br>              go_type:<br>                  # for import, package and type please refer the go code above<br>                  import: &quot;github.com/muhwyndhamhp/material-go/utils/typeext&quot;<br>                  package: &quot;typeext&quot;<br>                  # put your type here, <br>                  # if you want struct instead, put the CustomParams<br>                  type: &quot;JSONB&quot;<br>            - column: &quot;products.private_metadata&quot;<br>              go_type:<br>                  import: &quot;github.com/muhwyndhamhp/material-go/utils/typeext&quot;<br>                  package: &quot;typeext&quot;<br>                  type: &quot;JSONB&quot;</pre><p>and re generate via:</p><pre>sqlc generate</pre><p>It will change the product struct into:</p><pre>type Product struct {<br>    ID int64<br>    Name string<br>    Description pgtype.Text<br>    Slug string<br>    PublicMetadata typeext.JSONB<br>    PrivateMetadata typeext.JSONB<br>}</pre><p>And that’s it!</p><p>By the way, this solution does not only constrained on JSONB, but basically any data type, though it is most useful for JSONB type.</p><p>Thanks for reading!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0350d4df967" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gravel-engineering/using-custom-struct-for-jsonb-type-in-sqlc-f0350d4df967">Using custom struct for JSONB Type in SQLC</a> was originally published in <a href="https://medium.com/gravel-engineering">Gravel Product &amp; Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using SQLC for ORM alternative in Golang, ft. Go-Migrate & PGX]]></title>
            <link>https://medium.com/gravel-engineering/using-sqlc-for-orm-alternative-in-golang-ft-go-migrate-pgx-b9e35ec623b2?source=rss-4c11fceb1e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9e35ec623b2</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sqlc]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Muhammad Wyndham Haryata Permana]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 07:28:17 GMT</pubDate>
            <atom:updated>2023-08-10T00:39:46.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEQgAdG04VjcfMPTwZlC4g.png" /><figcaption>SQLC Generated Go code</figcaption></figure><p>For those who does not know what SQLC is, it is a Database tools to generate idiomatic type-safe go code that derived from our own SQL Queries.</p><p>Why using <a href="https://docs.sqlc.dev/en/latest/index.html">SQLC</a> you may asked? because ORM only great if you have rather basic relationships between models OR you basically omit any modern relational DB feature for ease of use. Once you have the needs to modify models in the non-basic ways, you&#39;re start to tangle the ORM code and may or may not impact performance due to unoptimized queries.</p><p><a href="https://docs.sqlc.dev/en/latest/index.html">SQLC</a> is here for people that comfortable using SQL Queries but want the type safety of Go, basically dealing with the uncomfortable part of actually using Database in any programming language, but still allowing us to make deep, optimized modification as any people with SQL know-how can relate.</p><h3>Setting up SQLC</h3><p>SQLC comes in various flavour, you can embed it directly via brew:</p><pre>brew install sqlc</pre><p>Or via Go Instal (Go &gt;=1.17):</p><pre>go install github.com/kyleconroy/sqlc/cmd/sqlc@latest</pre><p>Or via Go Get:</p><pre>go get github.com/kyleconroy/sqlc/cmd/sqlc</pre><p>It also has docker image for those that needed it in a pipeline somehow:</p><pre>docker pull kjconroy/sqlc</pre><p>After you install SQLC in any way, you should then afterward has access to it in terminal via sqlc command.</p><h3>Using SQLC in Go Project</h3><p>After you Initiate a Golang project, you can start using SQLC by first creating it&#39;s configuration file in sqlc.yaml:</p><pre>version: &quot;2&quot;<br>sql:<br>  - engine: &quot;postgresql&quot;<br>    # queries refers to where our manually created queries located<br>    queries: &quot;query.sql&quot; # will refer a file<br>    # or<br>    queries: &quot;misc/queries&quot; # will refer a directory<br>    # schema refers to where our schema definitions located<br>    schema: &quot;schema.sql&quot; # will refer a file<br>    # or<br>    schema: &quot;misc/migrations&quot; # will refer a directory<br>    gen:<br>      go:<br>        package: &quot;db&quot;<br>        sql_package: &quot;pgx/v5&quot;<br>        out: &quot;db&quot;</pre><p>This YAML specifies several things:</p><ul><li><strong>Engine</strong> -&gt; What kind of DB you&#39;re using. In this example we&#39;re using postgresql</li><li><strong>Queries</strong>-&gt; File/Directory for where you store your SQL Queries. These queries is the source target for SQLC to generate type-safe Go code.</li><li><strong>Schema</strong> -&gt; FIle/Directory for where you store your schema logic. SQLC has support for go-migrate schema structure of up.sql and down.sql format. Else, you may want to just dump the schema in a single schema.sql file.</li><li><strong>Gen</strong> -&gt; specify the auto-generated parts of the SQLC, in this example it will generate Go specific implementation:</li><li><strong>Package</strong> -&gt; specify the package name of the generated code.</li><li><strong>Out</strong> -&gt; specify the path where the generated code will be put on.</li><li><strong>SQL_Package</strong> -&gt; due to lib/pq package is currently entering maintenance mode, we&#39;re encouraged to use pgx driver instead. This will specify the pgx version that SQLC will be basing on.</li></ul><h3>Using SQLC to generate Type-Safe Models from schema</h3><p>In this example, I will demonstrate how to use <a href="https://github.com/golang-migrate/migrate">go-migrate</a> as the companion tools. After setting up <a href="https://github.com/golang-migrate/migrate">Go-Migrate</a>, we can create new migration via:</p><pre>migrate create -ext sql -dir misc/migrations CreateAuthor</pre><p>It will create xxxxxxx_CreateAuthor.up.sql and xxxxxxx_CreateAuthor.down.sql in misc/migrations (Remember that this is the path of schema in the sqlc.yaml).</p><p>There we can define the migration up and the migration down of our codes. Then I will create a schema for authors table:</p><pre>CREATE TABLE authors (<br>    id BIGSERIAL PRIMARY KEY,<br>    name text NOT NULL,<br>    bio text<br>);  <br><br>CREATE INDEX IF NOT EXISTS &quot;idx_authors_id&quot; ON &quot;authors&quot; (&quot;id&quot;);</pre><p>This will do 2 things:</p><ul><li>tell go-migrate what migration needed to be executed</li><li>tell sqlc what is the schema for table authors</li></ul><p>Then after that, we can migrate our DB so our author table would be created. Migrate the authors table via :</p><pre>migrate -database &lt;Put your DSN here&gt; -path=misc/migrations up all</pre><p>After that we can generate the model for authors via</p><pre>sqlc generate</pre><p>It will then create a new file called db/models.go that contains:</p><pre>package db<br><br>import (<br>    &quot;github.com/jackc/pgx/v5/pgtype&quot;<br>)<br><br>type Author struct {<br>    ID int64<br>    Name string<br>    Bio pgtype.Text<br>}</pre><h3>Using SQLC to generate Type-Safe Functions that execute DB Transactions</h3><p>Now that we have the model, we also want to create various transactions. SQLC doesn&#39;t generate transaction for us, instead, we&#39;re supposed to create our own transaction.</p><p>First we should create new file called authors.sql inside misc/queries (Remember this is the queries path we define in the sqlc.yaml up above):</p><pre>-- name: GetAuthor :one<br>SELECT * FROM authors<br>WHERE id = $1 LIMIT 1;<br><br>-- name: ListAuthors :many<br>SELECT * FROM authors<br>ORDER BY name;<br><br>-- name: CreateAuthor :one<br>INSERT INTO authors (<br>    name, bio<br>) VALUES (<br>    $1, $2<br>)<br>RETURNING *;<br><br>-- name: DeleteAuthor :exec<br>DELETE FROM authors<br>WHERE id = $1;<br><br>-- name: UpdateAuthor :one<br>UPDATE authors<br>SET <br>    name = $2,<br>    bio = $3<br>WHERE id = $1<br>RETURNING *;</pre><p>Here, we&#39;re defining several queries that refers to various operations. sqlc will read the comment structure above the queries to define what the function is and what kind of return format it wants.</p><pre>-- name: CreateAuthor :one</pre><p>This comments means:</p><ul><li>Name of the function is CreateAuthor</li><li>It should return exactly 1 schema of authors.</li></ul><p>Other than :one, it also support :many for returning more than 1 schema in a list, and :exec which means it won&#39;t return any schema (only executing the SQL).</p><p>After that we can exec:</p><pre>sqlc generate</pre><p>again to both generate the model and the function. It will then create file db/authors.sql.go:</p><pre>package db<br><br>import (<br>    &quot;context&quot;<br>    &quot;github.com/jackc/pgx/v5/pgtype&quot;<br>)<br><br>const createAuthor = `-- name: CreateAuthor :one<br>INSERT INTO authors (<br>    name, bio<br>) VALUES (<br>    $1, $2<br>)<br>RETURNING id, name, bio<br>`<br><br>type CreateAuthorParams struct {<br>    Name string<br>    Bio pgtype.Text<br>}<br><br>func (q *Queries) CreateAuthor(ctx context.Context, arg CreateAuthorParams) (Author, error) {<br>    row := q.db.QueryRow(ctx, createAuthor, arg.Name, arg.Bio)<br>    var i Author<br>    err := row.Scan(&amp;i.ID, &amp;i.Name, &amp;i.Bio)<br>    return i, err<br>}<br><br>// And many more below as you define your queries...</pre><h3>Using SQLC generated function in a program</h3><p>One more thing that I haven&#39;t mentioned is that other than generating models.go and authors.go inside db path (or any path that you specify in sqlc.yaml), it will also generate db.go file which functions as the entry points for our queries.</p><p>Code example below will show a simple example how we can call our newly made type-safe go code to fetch an author:</p><pre>func run() error {<br>   ctx := context.Background()<br>  <br>   d, err := pgxpool.New(ctx, &quot;user=user_name dbname=db_name sslmode=disable host=localhost port=5678&quot;)<br>   if err != nil {<br>    return err<br>   }<br>  <br>   q := db.New(d)<br>  <br>   insertedAuthor, err := q.CreateAuthor(ctx, db.CreateAuthorParams{<br>      Name: &quot;Mr Beans&quot;,<br>      Bio: pgtype.Text{<br>       String: &quot;The funniest man alive&quot;,<br>       Valid:  true,<br>      },<br>   })<br>   if err != nil {<br>    return err<br>   }<br><br>   log.Println(insertedAuthor)<br>}</pre><p>That&#39;s it! 🎉</p><h3>Further Notes</h3><p>This conclude the basic setups for SQLC in a Go project. But I suppose there is more than that to a project. Further readings can be found below:</p><ol><li><a href="https://medium.com/gravel-engineering/using-custom-struct-for-jsonb-type-in-sqlc-f0350d4df967">Using custom struct for JSONB Type in SQLC</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9e35ec623b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gravel-engineering/using-sqlc-for-orm-alternative-in-golang-ft-go-migrate-pgx-b9e35ec623b2">Using SQLC for ORM alternative in Golang, ft. Go-Migrate &amp; PGX</a> was originally published in <a href="https://medium.com/gravel-engineering">Gravel Product &amp; Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recognizing Face in Android using Deep Neural Network + TensorFlow Lite]]></title>
            <link>https://medium.com/gravel-engineering/recognizing-face-in-android-using-deep-neural-network-tensorflow-lite-be980efea656?source=rss-4c11fceb1e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/be980efea656</guid>
            <category><![CDATA[tensorflow-lite]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Muhammad Wyndham Haryata Permana]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 08:10:43 GMT</pubDate>
            <atom:updated>2022-07-20T08:10:43.140Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>In the <a href="https://medium.com/gravel-engineering/google-mlkit-quick-and-easy-face-detection-in-android-db991a742ec2">previous article,</a> we explored how we could implement face detection in android apps to introduce a face recognition pipeline on mobile devices.</p><p>Before we start, there are various jargons that readers should know about, such as <strong>Deep Neural Network, Convolutional Neural Network,</strong> <strong>Triplet Loss </strong>and <strong>Inference Time </strong>which I’ll happily explain below:</p><ul><li><strong>Deep Neural Network</strong></li></ul><p>When we talk about neural networks, we talk about how machine learning works. A neural network consists of several connected units called nodes. These nodes mimic how a neuron in a human brain works, and each node will process the input, then give the result and pass this result to the next node. These chains of nodes are basically what a neural network is.</p><p>These nodes are then grouped into a layer, and this layer has a specific kind of input and a specific kind of output.</p><p>When we want to solve a problem, we often need multiple kinds of outputs, and can’t be simply contained to single processing. Therefore, to solve this, we need another layer that will do different things to solve different problems.</p><p>And when the layer count is more than 1, it means the neural network has “depth” as in multiple layers, hence Deep Neural Network.</p><ul><li><strong>Convolutional Neural Network</strong></li></ul><p>In mathematical terms, Convolutions means a mathematical operation on two functions, let’s say <em>f</em> and <em>g</em> to produce a third function <em>h </em>that expresses how the shape of the function is modified by one another.</p><p>In the context of neural networks, it means that we replace the general matrix multiplication that is usually the calculation involved inside a neural network with convolution operation instead.</p><p>This process gives better results when it comes to processing visual imagery, including facial recognition, object recognition, and various other visual processing.</p><ul><li><strong>Triplet Loss</strong></li></ul><p>What is triplet loss? Triplet loss is a loss function (which is a function that maps events or values of variables, in this case, an array, into a real number representing cost or loss associated) for machine learning algorithms.</p><p>This loss function work where an input (which we called “<strong>Anchor</strong>”) is compared to pre-existing matching input (means the known input which we know that is the same person as the anchor, called “<strong>positive</strong>”) and pre-existing non-matching input (a totally different person, called “<strong>negative</strong>”).</p><p>The goal of this loss function is to minimize the distance between <strong>anchor </strong>to <strong>positive </strong>and maximize the distance between <strong>anchor </strong>to <strong>negative.</strong></p><ul><li><strong>Inference Time</strong></li></ul><p>Inference time is a metric of how long a machine learning model runs to decide on a solution. In computing terms, how long is an output being made for each input being made.</p><p>Kinda understand it now? Great! Now let’s move on to the implementation of Face Recognition.</p><h3><strong>Implementation</strong></h3><p>Our implementation of Face Recognition uses something called<a href="https://www.tensorflow.org/lite"> TensorFlow Lite</a> to run various implementations of pre-trained models of<a href="https://towardsdatascience.com/a-laymans-guide-to-deep-neural-networks-ddcea24847fb?gi=408c280c2a60"> the Deep Neural Network</a> (DNN) based Face Recognition Algorithm.</p><p>What is TensorFlow Lite? Tensor Flow Lite is a library that’s developed by Tensor Flow to run Machine Learning models that are developed in Tensor Flow Language to run on edge/mobile devices. This enables us to convert existing Machine Learning models into a format that even mobile phones can run and apply.</p><p>I won’t explain how to install/apply this library to the android project. You can actually learn how to apply it properly here, but I do explain the step I took personally to complete this project.</p><p>There are various models that can be used, but for brevity’s sake, I’ll use two particular models, which are:</p><ul><li><a href="https://arxiv.org/abs/1804.07573"><strong>MobileFaceNet</strong><br></a> A Convolutional Neural Network Based Implementation of<a href="https://arxiv.org/abs/1801.04381"> MobileNet V2</a> for face recognition with reduced parameters that allows it to work with a mobile device at a reasonable accuracy. The output of this model is Euclidean space of 192-bytes parameters. As the author explains:</li></ul><blockquote>We present a class of extremely efficient CNN models, MobileFaceNets, which use less than 1 million parameters and are specifically tailored for high-accuracy real-time face verification on mobile and embedded devices.</blockquote><ul><li><a href="https://arxiv.org/abs/1503.03832"><strong>FaceNet</strong><br></a>Another implementation of Convolutional Neural Network that implements the Embedding to a Euclidean space of 128-bytes parameters to map the face in a likeness array. This method leverages the Triplet Loss method during its training and achieves almost impeccable performance results.</li></ul><p>Between these two algorithms that I have chosen, there are advantages and disadvantages when being applied to run with Android Apps:</p><p><strong>MobileFaceNet</strong></p><ul><li>Based on MobileNet V2 (retrofit to V3)</li><li>Very Fast Inference time (168–320ms for dataset source, +-160ms for typical)</li><li>Reduced Parameters, can run on less powerful SoC (System on Chip, or what we usually called the “Processor” or “Brain” of a mobile phone).</li><li>Not so accurate recognizing face with an expression</li><li>Not so accurate recognizing face rotation</li><li>More accurate when using straight face photo</li><li>Input format ARGB8888 112x122 px Bitmap</li><li>Output format Float Array 192D</li><li>Small Model size (5.1 MB un-Quantized)</li></ul><p><strong>FaceNet</strong></p><ul><li>Relatively slow inference time (560–1496ms for dataset source, +-200ms for typical)</li><li>Not run well on slow SoC (System on Chip, or what we usually called the “Processor” or “Brain” of a mobile phone).</li><li>Can handle more variables in environment and facial expression including dark environment, smile, and visible teeth.</li><li>Can detect a person even if using a mask</li><li>Can handle Face Rotation to some degree</li><li>Input format ARGB8888 160x160 px Bitmap</li><li>Output format Float Array 128D</li><li>Large Model size (45MB un-Quantized)</li></ul><p>Currently, our implementation of Face Recognition in Android is using pre-DNN-ed Images that specify each person like this :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d670da7d979192191583a55103dd8115/href">https://medium.com/media/d670da7d979192191583a55103dd8115/href</a></iframe><p>Where Likeness is the Result of Euclidean space from the DNN model used via TensorFlowLite. This Euclidean space is representing the likeness of a face in an N-Dimensional Array, where we could do some simple arithmetic to calculate the average distance to each recognized face.</p><p>Then following the flowchart below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/0*P9gnwwo0Vw1uq21j" /></figure><p>We can determine which person is which from our pre-DNN-ed list of people. The explanations of step by step from the flowchart above are as explained below:</p><ul><li>Following the Face-Detection step previously, we already had an image with ARGB8888 at specified <em>n x n</em> Resolution which the model requires. (112 x 112 px for MobileFaceNet and 160 x 160 px for FaceNet).</li><li>This image was then inputted to the DNN Model, waiting for output</li><li>If the output is successful, then we should have an <em>N-Dimensional </em>array that represents the Likeness of a face in a Euclidean space.</li><li>This likeness then compared to our existing list of people above.</li><li>For each person in the list above, we calculate the L2 Euclidean Distance from the Result we have to each likeness a Person has. This distance was then averaged for each person.</li><li>After each person’s distance is averaged, then we take the smallest average, the person associated with this smallest average is our candidate of similarities.</li><li>This smallest average compared to our predetermined maximum distance, which in this case that we took reference from the<a href="https://github.com/serengil/deepface/blob/master/deepface/commons/distance.py"> DeepFace library</a> (1.0 for FaceNet and 1.0 for MobileFaceNet).</li><li>If the smallest average is bigger than our maximum distance, then we assume that this is not the same person as our candidate. If yes, we assume that it is indeed the same person.</li></ul><p>Then for the implementation in the Android app, we require dependency below :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/841aeb25a218be76e7d6b50abc4507fa/href">https://medium.com/media/841aeb25a218be76e7d6b50abc4507fa/href</a></iframe><p>Then make sure our model (which should be .tflite model) is added to /app/src/main/assets path.<br>For implementations, after we got the cropped image from the Face Detection process, we need to convert them to ByteBuffer :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34a1275fd34a92676c434f59ddd8e5cd/href">https://medium.com/media/34a1275fd34a92676c434f59ddd8e5cd/href</a></iframe><p>Then run the Inference process to DNN Model :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36c7d18c0ab0f3477c87b6a049876eaa/href">https://medium.com/media/36c7d18c0ab0f3477c87b6a049876eaa/href</a></iframe><p>This FloatArray Result is the Likeness array that we got from the DNN model. Which should be calculated as mentioned step-by-step above.</p><p>As for how we calculate the distance, we have two possible method, one is using L2 Normalization by finding the Normalized value of two arrays (one array is the the array of the result from above and the other is the array from our pre-calculated database) which we can use the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75830062dfe3ff3457dd7ae27101a886/href">https://medium.com/media/75830062dfe3ff3457dd7ae27101a886/href</a></iframe><p>And another method called Cosine Similarity between 2 array:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40a82bfc0d6cf2d798385b610df65d17/href">https://medium.com/media/40a82bfc0d6cf2d798385b610df65d17/href</a></iframe><p>What was this distance calculation for? Basically this: you had the result from the face recognition model. This result comes in the format of arrays. The model itself doesn’t which face is who, but the result of this array is basically the coordinate of a dot in an n-dimensional graph, with n representing the size of the array (128 or 192 respectively).</p><p>Previously we had the pre-calculated face data that pass from the same model, this array also represents the same data we mentioned above. From this, we should be able to calculate the distance between the array we got from the new face vs our database of arrays that represents specific faces.</p><p>This n-dimensional distance calculation can be done by Cosine Similarity mentioned above, with x1 representing the new array we had, and x2 representing the database of data we had previously. It is also doable to use L2 Normalization between 2 arrays as a preliminary step.</p><p>As for the Result in Android Implementation using the FaceNet model, we can see the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/0*4QxmWHGrIGgbcqEZ" /></figure><p>As you can see, the average of each person in our database shows as above:</p><ul><li><strong>Wyndham: 0.70820</strong></li><li>Zidni: 1.190301</li><li>Alfin: 1.075332</li><li>Reza: 1.012211</li></ul><p>The Person with the lowest Average Distance is Wyndham, and because it is lower than our maximum limit of<strong> 1.0</strong>, we can determine that this person indeed a person called Wyndham.</p><p>Great! We have implemented a proper Face Recognition system in an app and see the result. Unfortunately, All of that implementations aside, there are some requirements and limitations which may or may not be dealbreakers for your particular application. Few which I list below:</p><ul><li>Minimum SDK is 21 (Lollipop 5.0)</li><li>Minimum Tested System RAM is 2GB</li><li>Has Camera Access</li><li>Can be fooled with photograph</li><li>The Model Size is big and incompressible.</li></ul><h3><strong>What’s next?</strong></h3><p>As we see throughout this article, it is possible to do Face Recognition on mobile/edge devices. This implementation in particular uses pre-existing models to recognize the faces. On the implementation side of things, we are using TensorFlow Lite, available on various platforms, including Android.</p><p>Before we can use proper face recognition tho, we need to prepare our face data first, which we touch upon in the first article. After we have a proper face image that we can use for face recognition, we convert the image to a byte array, then run it through the pre-trained model, and the result we can use to calculate the distance between the scanned image and with existing databases of images.</p><p>When it comes to the model, it is uses several models that uses the same basic methods: Convolutional Neural Network with Triplet Loss.There are various models available, but in this example, I’m using 2 in particular: MobileFaceNet and FaceNet.</p><p>In the next article, we will explore another field of machine learning in mobile devices, some of which include text recognition and filling up missing data in such a way that we can extract proper information from it.</p><p>Thank you very much and see you in the next article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be980efea656" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gravel-engineering/recognizing-face-in-android-using-deep-neural-network-tensorflow-lite-be980efea656">Recognizing Face in Android using Deep Neural Network + TensorFlow Lite</a> was originally published in <a href="https://medium.com/gravel-engineering">Gravel Product &amp; Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google MLKit: Quick and easy Face Detection in Android]]></title>
            <link>https://medium.com/gravel-engineering/google-mlkit-quick-and-easy-face-detection-in-android-db991a742ec2?source=rss-4c11fceb1e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/db991a742ec2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-neural-networks]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ml-kit-android]]></category>
            <category><![CDATA[ml-kit]]></category>
            <dc:creator><![CDATA[Muhammad Wyndham Haryata Permana]]></dc:creator>
            <pubDate>Fri, 08 Apr 2022 06:15:06 GMT</pubDate>
            <atom:updated>2022-04-08T06:15:06.726Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The core of facial recognition systems has been developed over the years, the first similar system was developed in the 1960s as a computer application. Its utilization has been used in many industries outside the regular-like implementation of technology. One of its early utility applications was for preventing criminal activity by recognizing peoples’ faces so they cannot multiply identical faces to register under different names (for fraud prevention) in the USA.</p><p>As more cutting-edge technology has developed significantly, this majorly affects the development of facial recognition utilization. Nowadays, facial recognition systems can be easily found in every aspect of our lives, starting from handheld devices, security systems, to smaller sensors in vehicles. This rapid development phenomenon caught our eyes and might attract one’s mind “How could you do that?”. Therefore this article will be “Demystifying the Face Recognition”.</p><h3>Demystifying the Face Recognition</h3><p>I bet some questions might appear in one’s mind after reading the intros above, one of them would probably like, <em>“Great! Now, how to implement it?”</em>. First thing first, let’s look at some steps to achieve such goals. To achieve full face recognition implementation, we need to separate this into 3 major steps:</p><ul><li><strong><em>Face Detection (What this article covers)</em></strong></li><li>Deep Neural Network</li><li>Result Classification Method</li></ul><p>The diagram below will hopefully help you understand how each step corresponds to what:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkV4Hc6XbukV5E6wadfgwA.png" /></figure><p><strong>As stated above, Face Detection</strong> comes first. It may be pretty self-explanatory, however, you may find it confusing regarding <em>“What is the difference between </em><strong><em>Face Detection </em></strong><em>and </em><strong><em>Face Recognition ?</em></strong><em>”.</em></p><p><strong>Face Detection</strong> is the process to <strong>see/identify </strong>faces from an image. On the other hand, <strong>Face Recognition</strong> is the process of <strong>differentiating faces </strong>and classifying them to identify a person. Therefore, to distinguish the two identical (but not the same) jargons, we can point out on the main process one is aimed for.</p><p>Referring to Diagram 1, Face Recognition consists of 2 steps: <strong>Deep Neural Network</strong>, and <strong>Classification</strong>. On the other hand, the scope of this article only covers the Face Detection part.</p><p>Based on human <em>point of view, </em>differentiation between one face to others is pretty apparent, but not for computers. If computers were provided with an image, all they see is a bunch of 0 and 1 (<em>binary</em>); they do not understand why this array of 0 and 1 is a face and why the others are not. Therefore, we are supposed to train the Face Recognition process with images with faces in them, so they translate the binary they see as recognition.</p><p>Face detection — also called facial detection — is an <a href="https://searchenterpriseai.techtarget.com/definition/AI-Artificial-Intelligence">artificial intelligence</a> (AI) based computer technology used to find and identify human faces in digital images. Face detection technology can be applied to various fields — including security, <a href="https://searchsecurity.techtarget.com/definition/biometrics">biometrics</a>, law enforcement, entertainment, and personal safety — to provide surveillance and tracking of people in real-time. (<a href="https://searchenterpriseai.techtarget.com/definition/face-detection">Corrine, B. 2020</a>).</p><p>This is where Google MLKit jumps to help. Inside the Google MLKit suite, there is this function called<a href="https://developers.google.com/ml-kit/vision/face-detection/android"> Face Detection Library</a>. This tool helps us simplify the process of face detection by simply, well, doing it for us. We need to supply it with an image (or images) into it and ask the library to provide us with where the face/faces are located in the image. It then allows us to crop that particular area and gives us good old face data that we can use to supply our next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1UWNrITWZGmn3kv6gnjFTw.png" /></figure><p>Now that we understand each term and where <strong>MLKit</strong> lands in this process, we can start to enter the nitty-gritty implementation. In this case, it is using the <strong>Android Platform.</strong></p><h3>Face Detection Implementation</h3><p>Our Implementation for Face Detection is using Google’s <a href="https://developers.google.com/ml-kit">MLKit library</a>. This library allows us to detect faces in an image and also detect several parameters such as:</p><ul><li>Key Facial Feature</li><li>Face Contour</li><li>See Expressions such as Smile and Open Eyes</li><li>Face Angle of Rotation</li><li><strong>Bounding Box where the Face is located in an image</strong></li></ul><p>This implementation assumes that you are already familiar with Android Projects and will not specify how you get the Bitmap/Image we’re going to use to implement. You may add your own implementation of a camera, file browsing and/or network image as a source.</p><p>What we target is only to detect any face in a frame of video / in a single image, and extract the required face image into a separate, treated image that is usable for Deep Neural Network implementation to work. Each implementation of DNN will have different requirements, and we must consider which algorithm we use to extract the image.</p><p>By default, the face detection library allows us to set various options for face detection. Because we’re only needing Bitmap Face data with n x n dimension, we will use minimal settings that do not detect anything other than Bounding Box.</p><p>To add MLKit Face Detection support to an android project, you should add this dependency to the build.gradle file at the app level:</p><pre>implementation &#39;com.google.mlkit:face-detection:16.1.2&#39;</pre><p>Great! after that, we need to set the <strong>FaceDetector</strong> client up and running.</p><p>This code below shows how we implement the <strong>faceDetector</strong> client for Facial Detection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d3784f150f626f435324c199c1e1c8e/href">https://medium.com/media/6d3784f150f626f435324c199c1e1c8e/href</a></iframe><p>This<strong> faceDetector </strong>client is the main ingredient in our process. You can save this variable as injectable Singleton or a new instance in your Fragment/Activity. Your call.</p><p>Then we need to prepare the image(s) that we want to detect the face on. As mentioned above, you may implement your own code to source the image. This part assumes we already had the Bitmap variable necessary for the process.</p><p>As the diagram above shows, we want to convert this image to NV21 Byte Array. This is not strictly necessary, but this format is recommended to further increase the detection time required for the Face Detection to work.</p><p>This code below shows how we implement converting our Bitmap to NV21 ByteArray which then we convert to InputImage that we used to supply the faceDetector client we set up earlier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e15e427407fcf011a0a9689a449b2b59/href">https://medium.com/media/e15e427407fcf011a0a9689a449b2b59/href</a></iframe><p>As for how the Extension works, you can see the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5682327fea969a14f836b7b57908a633/href">https://medium.com/media/5682327fea969a14f836b7b57908a633/href</a></iframe><p>The whole process of face detection can be seen in the Flowchart below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0jOI7rvFMjaCFbbQbX5b_w.png" /></figure><p>Step by step explaining the graph above:</p><ol><li><strong>First, We need to prepare the image source</strong>. this can be retrieved from a Camera or local Image. In Android what is required for this step is to acquire any Image in Bitmap Format.</li><li><strong>Then we continue with Image Pre-Treatment</strong> is an optional step. By default, most bitmaps will use the ARGB-8888 format. This format would be fine when used with MLKit Face detection, but we can save some extra processing time by converting it into NV21 ByteArray format which would boost the detection speed significantly. This Bitmap or ByteArray shall then be converted to the InputImage variable that can be inserted into the faceDetector.</li><li><strong>MLKit Face Detection</strong> step consists of inserting the InputImage into faceDetector. We should also attach addOnSuccessListener.</li><li><strong>If there the images contains any face</strong>, then onSuccessListener will be invoked and will return the Face object which contains information as mentioned above such as BoundingBox, Landmark, etc. but the actual contains will follow the settings we set previously, if we set the Detector to LANDMARK_MODE_NONE then no landmark will be retrieved.</li><li><strong>The next step</strong> if we assume that any face is detected from the source image is to extract just the face into the specific n x n dimension bitmap that we use for DNN Model. This can be achieved via BoundingBox that is provided inside the Face object we retrieved previously. This BoundingBox will contain the coordinate of which each point of a Rectangle that will contain the Face is placed on the source Image. The image below will show what is BoundingBox and where it is in an image, and how we cut the face image to be supplied into the DNN model.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8y891vIwXN1iaK6itLdXA.jpeg" /><figcaption>Where Bounding Box is Located</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/1*bA2ykuPMKmyVEh6eXo9SgA.png" /><figcaption>Result of the Face Detection</figcaption></figure><h3>Lesson Learned</h3><p>These are the following points that you need to know about the Face Recognition process:</p><ul><li>We can break the Face Recognition process into 3 major steps: Face Detection, Deep Neural Network, and Classification.</li><li>We have seen that Google MLKit helps us to do face detection easily to extract face data. You can use the extracted face data to feed the Deep Neural Network.</li></ul><p>Alas, the lesson learned might be the last part of the Face Recognition article. But don’t worry, as we’ll talk more about <strong>Deep Neural Network on Mobile Devices using TensorFlow Lite </strong>in the next article. Stay tuned on Gravel’s page for updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db991a742ec2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gravel-engineering/google-mlkit-quick-and-easy-face-detection-in-android-db991a742ec2">Google MLKit: Quick and easy Face Detection in Android</a> was originally published in <a href="https://medium.com/gravel-engineering">Gravel Product &amp; Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>