<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Ulrich Kautz Blog</title><link>https://ulrichkautz.com/</link><description>Recent content on Ulrich Kautz Blog</description><generator>Hugo -- gohugo.io</generator><language>en-us</language><lastBuildDate>Fri, 23 Oct 2026 00:00:00 +0100</lastBuildDate><atom:link href="https://ulrichkautz.com/index.xml" rel="self" type="application/rss+xml"/><item><title>Who is your next Agent?</title><link>https://ulrichkautz.com/posts/2026-10-23_who-is-your-next-agent/</link><pubDate>Fri, 23 Oct 2026 00:00:00 +0100</pubDate><guid>https://ulrichkautz.com/posts/2026-10-23_who-is-your-next-agent/</guid><category>agentic</category><category>ai</category><category>writing</category><description>What comes after the current generation of coding agents? Is there something to know now? Where are we headed?</description><content:encoded><![CDATA[<p>How are you coding these days? My current solo-project stack is Claude Desktop with <a href="https://github.com/obra/superpowers">Superpowers</a>. (Can I say good ol’ superpowers at this point? It’s been more than a few months). There are so many options now and it feels I might be missing out on something. So I tried to see beyond my own nose and gave a couple of other solutions a spin over the last week or two. I’ll probably compile a more detailed landscape article in the next days / weeks, but here is the gist already.</p>
<h2 id="starting-point">Starting Point</h2>
<p>I went along the same trajectory of agentic coding as most: from advanced auto-complete, to early agent panels, back to terminal coding agents, and now to full-on agentic coding applications. Claude Desktop in my case. I think many made that journey, probably most. Sure, a lot may argue here for terminal only - which I can empathize with, but coordinating multiple subagents I found just so much easier with proper application windows. But these are details that come down to personal preference and flavor. More important is the fact we are now running agents that run a multitude of subagents.</p>
<p>What I was curious about in my recent investigation is: What is the next level? What is the next step equivalent to when we went from advanced auto-complete to agentic coding? What may I be missing out on?</p>
<h2 id="next-more-of-the-same">Next: More of the Same</h2>
<p>What I found was more of the same. Quite literally: Where <code>claude</code>, <code>codex</code>, <code>opencode</code> provide primarily an interface to communicate with one agent to work on one task the next generation (I tried: <a href="https://www.onorca.dev">Orca</a>, <a href="https://orchestrator.inc">Agent Orchestrator</a>, <a href="https://paseo.sh">Paseo</a>) come with interfaces that allow you to work on multiple tasks simultaneously.</p>
<p>On the lower end the tools here behave more-or-less like Claude Desktop: You have multiple sessions, can make use of Git worktrees to work on concurrent tasks. On the upper end you truly feel like the dreaded micromanager: a Kanban-esque interface where your agents scurry to move the work from one stage to the next on remote machines, and you are only involved on the tail ends: spec and review.</p>
<p>From what I can tell you really need “fitting work” to reap the benefits of concurrent agents. For example: working on my local machine on a Rust project I am quite often bound to executing work sequentially, simply because <code>cargo build</code> and <code>cargo test</code> work well executing on different worktrees, yet any single execution will eat my whole CPU just fine. You can try to game the system (e.g. <a href="https://github.com/mozilla/sccache">sccache</a> and friends) only so much in my experience.</p>
<p><em>The</em> hard constraint for productivity at this level is <em>we humans</em>. Whether you parallelize execution or not, <em>you</em> still have to review the spec and plans, <em>you</em> still must be available for in-plan-execution-questions (and yes, they will come, unless you work in a highly synthetic, predictable environment). And yes, <em>you</em> still have to rigorously review the work in the end; faster agents doing more work doesn’t mean their quality improves.</p>
<p>At best you can optimize your workload so that the agents wait only a little, while you alternate between tasks, spec review and code review - but wait they will. How much you can increase your work impact this way, before high-frequency context switching will either spiral your own <a href="https://ulrichkautz.com/posts/2023-04-13_interruptions-the-silent-high-performance-killer/#why-do-interruptions-increase-error-rate">error rate</a> out of control, or send you into cognitive burn-out, remains to be seen.</p>
<h2 id="future-more-hope-trust">Future: More <del>Hope</del> Trust</h2>
<p>It’s not flying cars, but bottomless trust (or rather hope) that will power the future. Alas according to what you can find in terms of the next next generation. Welcome to the software factories, or how some call it lovingly: dark factories. Not nefarious at all! Well, the more you read into it, the more you may doubt that last statement. Or that is just me.</p>
<p>The gist is here: You provide goals, not tasks. The agents then go and run with it: They create their own specs and plans, but you are not involved in either their review. Nor would you review code. You review would be behavioral: does it do, does it feel, does it behave as I want it to? You would not need to know much about the implementation anymore. The end goal here is to enable “normal people”, not software developers, to write and maintain software. You are still a decision engine, but at a much higher level than before.</p>
<p>The tools in that realm are currently highly experimental. A big and well discussed candidate is <a href="https://github.com/gastownhall/gastown">Gas Town</a>. Well, not <em>is</em> but <em>was</em>, as the developer <a href="https://yegge.ai/essays/the-shape-of-things-to-come/">kind of shut it down</a>. The AAIF folks spun up an intentionally extremely transparency-focused clone called <a href="https://aaif.io/blog/welcome-to-glass-town-building-a-software-factory-with-a-paper-trail">Glass Town</a> - it seems I am not the only one finding this scary.</p>
<p>Another, even more experimental looking variant is <a href="https://github.com/fabro-sh/fabro">fabro</a> - just in case you want to give it a swing. I’d appreciate it if you would let me know how that went! I am simply not brave enough to try it myself in earnest.</p>
<p>There is plenty more if you go looking, but there be dragons for sure.</p>
<p>That’s it. I will share the research in a bit.</p>
<p>I’d be very curious to know what you are using and what constraints you are facing?</p>
]]></content:encoded></item><item><title>I failed my own Turing Test</title><link>https://ulrichkautz.com/posts/2026-10-20_i-failed-my-own-turing-test/</link><pubDate>Tue, 20 Oct 2026 00:00:00 +0100</pubDate><guid>https://ulrichkautz.com/posts/2026-10-20_i-failed-my-own-turing-test/</guid><category>agentic</category><category>ai</category><category>writing</category><description>How failing to spot my own writing in a blind AI test revealed the cognitive trap that prevented me from writing short articles.</description><content:encoded><![CDATA[<p>I have a lifelong affliction that has often massively frustrated me and certainly has held me back in countless ways over the years. Here it is: I suck at short-form writing. Or so I thought, until I ran into a conundrum last week. Note: this doesn&rsquo;t mean I don&rsquo;t suck, but if I do, then for other reasons than I thought. And that is freeing!</p>
<p>What I thought, or rather observed, was that I was entirely unable to write any short text about any topic I wanted to write about. I came to each text with an idea, usually an observation I made or a question that plagued me for which I found an answer I liked to share. Something that surely could be expressed in a few hundred words over the course of an hour or three. Or so I thought. What then inevitably happened, each time, was that the text blew up; both in space - thousands of words - and in time - weeks, sometimes months. <em>Each time!</em> It vexed me, but I simply couldn&rsquo;t help myself and I didn&rsquo;t know why! Until now, that is.</p>
<p>My newly gained perspective emerged from a somewhat distant place, yet closely related. As an engineer, I love to build. I love to find technical solutions for all the problems that I face - just because. In that spirit I was recently building a custom AI integration designed to ingest a person’s whole writing corpus - both content and style (if you must know: RAG + stylometrics behind MCP server). Armed with this corpus the AI is then enabled to emulate the person&rsquo;s voice while drawing on their opinions, beliefs and knowledge to really imitate them as closely as possible. Sounds somewhat scary, but is not nefarious at all. Quite the opposite: it&rsquo;s a prosthetic, a tool to help the likes of me to express themselves in their authentic voice when they are otherwise not able to. Be that for a strange ineptitude to write short-form texts, or social anxiety to share their thoughts, or overwhelm when using social media, or any reason you can think of.</p>
<p>In that process I came to a point where I had to fine tune my tool. My approach was a simple, blind experiment: a series of triplets of writing examples. One taken from my actual texts, one generated by the AI based on my integration and one generated by AI without any of my influence. Only the topics matched - roughly.</p>
<p>And here it got hairy: I could not tell them apart. Not at all! That absolutely stumped me. I should be able to recognize at least a text I wrote myself in the past, no? I mean, there are only so many options. Let&rsquo;s say my integration indeed worked as advertised. Then it might “fool” me - that was the point - and I would not be able to tell it from my original writing. If, on the other hand, my integration was bad, then I might not see a difference between the texts generated with and without my voice. Or I might see three entire different styles. Still, there should always be at least one text that peeks out: either my authentic one, or the generic one. Neither was the case for me! Mind you: my writing problem forced me to spend countless hours of detailed research and long thinking on how to condense that into individual sentences that really express what I mean. How could I not recognize these products of weeks, if not months of sweat and tears?</p>
<p>That was surprising, to put it mildly. It also got me thinking. Well, investigating and then thinking. What I found is that there is a large body of research in cognitive psychology about the topic of text comprehension (<a href="https://link.springer.com/article/10.1007/s11145-020-10118-1">Kintsch, van Dijk</a>). It segregates the comprehension into three distinct levels:</p>
<ol>
<li><em>Surface Code</em>: The How. The exact words; remembering a poem or a text passage verbatim</li>
<li><em>Textbase</em>: The What. The distilled information; knowing the exact facts of what was written.</li>
<li><em>Situation Model</em>: The Why. The underlying model, abstract concept; making sense of the writing.</li>
</ol>
<p>Not everyone, it turns out, excels at all the levels equally. I am terrible at (1), ok’ish at (2) and excel at (3). That means if I read a text, I get what it&rsquo;s saying, I mostly remember the points that were made, but I have not the foggiest as to the precise words. Or even shorter: I discard the envelope, but retain the message. This is why I cannot even tell my own writing apart from a machine generation - as long as the structure of the points being made is similar. Yes, that was the case. That was my only instruction to the text generation: “make this point”.</p>
<p>Learning this about myself was freeing. It matches flawlessly with my whole life experience. There are countless examples, starting in school never being able to recite any poem or text. I remember being baffled how friends - who were otherwise much better in school than I - told me they had to memorize math formulas to use them in the tests. Math was my only saving grace, but not for my ability to remember, but because the models (as I would call them now) made sense, and once I got them it was effortless to apply them when the patterns matched.</p>
<p>So how did that connect to writing short stories? Well, it didn&rsquo;t. Or not immediately. All I knew at this point was that I understood something about my ability to read, that also frustrated me throughout my life, that wasn&rsquo;t just me “sucking at reading”. I am actually pretty good at reading, just not in the way I measured it, which was: exactly remembering passages.</p>
<p>Understanding this felt empowering. I mulled it over and over in my head in the following days. I shared my insight with my wife. It took a while for the coin to drop: <em>The Why</em>. My brain&rsquo;s happy place is “The Why”. I may want to share an anecdote, a short “aha” I experienced while tinkering. Then I start writing it down. Then something happens: My brain kicks into gear, and steers me into the direction of its feel-good place: <em>let&rsquo;s research what the related field of sciences knows about that. Let&rsquo;s put that experience into a bigger perspective of the whole world. Let&rsquo;s build a definite ontology around it. And don&rsquo;t forget a practical framework, that can be used for all future cases for everyone everywhere and forever!</em></p>
<p>Well, it&rsquo;s not <em>that</em> bad - but close. And yes, that shoe fits me perfectly. I want to wear it. I feel safe and giddy wearing it. Yet, it kept me from writing short stories, because any short-form I ever attempted simply devolved into a research paper or essay - most of which never saw the light of day, as that got me into a gazillion tangents, deep angst of “not getting it fully right” and just provided weeks or months of surface go astray or otherwise find a reason not to finish.</p>
<p>So here we are. I am writing a short-form text, yet I am drawing (almost) only on memory. I am using even a story arc, of sorts. I wrote it in hours, not a day, not a week, least of all a month. Knowing about myself how I comprehend text, and subsequently how it steers me in writing helped me to now see clearly when I veer off into essay territory. Not that I never want to write long-form again, quite the opposite, but I rather have the choice.</p>
<p>Of course, it wasn&rsquo;t that easy and straight forward. There was much more reflection, discussions with my patient wife and, yes, research in between my insight and this article. But the cat is out of the bag, to quote a <a href="https://de.wiktionary.org/wiki/die_Katze_aus_dem_Sack_lassen">German proverb</a>. You may be the judge of the outcome. Sure, this article is not as short as I wanted it to be and, yes, I could not help but investigate at least a little bit while writing. However I am sure it&rsquo;s as with everything: it&rsquo;s a journey. I just found my starting point.</p>
<p>Either way: how do you understand text and what keeps you from publishing all you want?</p>
]]></content:encoded></item><item><title>Why care about DevEx?</title><link>https://ulrichkautz.com/posts/2025-04_why-care-about-devex/</link><pubDate>Tue, 15 Apr 2025 00:00:00 +0100</pubDate><guid>https://ulrichkautz.com/posts/2025-04_why-care-about-devex/</guid><category>devex</category><category>developer experience</category><category>developer productivty</category><category>devx</category><description>Maximize software development impact with DevEx. Learn how improving developer education, competence, motivation, and environment drives faster delivery, higher quality, and more innovation.</description><content:encoded><![CDATA[<p>Software runs the world. From small start-ups to big tech, software businesses are ubiquitous and affect almost everyone daily. Moreover, traditional companies that once thrived without much technology now find themselves embracing software as a core business requirement. Where there is software, there is software development. Where there is software development, there are often hidden costs, bottlenecks and waste - and humans who burn out from frustrating processes and high-stakes pressure.</p>
<p>There is one discipline in the software development world that addresses these problems and it is called <em>Developer Experience</em> - or <em>DevEx</em> for short. In recent months, I’ve often found myself explaining what DevEx is to people outside of the tech industry. That turned out to be really helpful for me, even though it wasn’t easy to describe the impact of DevEx without using technical concepts like CI/CD, platform, IDE, IaC, etc. This led me down a few rabbit holes, but eventually I gained a new perspective that I&rsquo;d like to share.</p>
<h2 id="devex-in-a-nutshell">DevEx in a Nutshell</h2>
<p>If you run a business, then you care about the bottom line. To have any bottom line worth thinking about, you need a product or service that provides value for a large enough number of customers. Then you need to make them aware and want to buy whatever it is that you are selling. In short you need at least a viable market, product-market fit and the right marketing strategy.</p>
<p>If the business has software development at its core then this bottom line is also directly linked to the software engineering work that goes into it: How fast are features shipped? How quickly can the course be corrected when market conditions change or new information arises? How much time does maintenance take away from moving forward? Is decision making supported by high quality feedback loops? Are customers complaining about reliability? And so forth.</p>
<p>Multiple disciplines have emerged over the years that take on these challenges: The DevOps movement revolutionized how we think about building, delivering and shipping software. Platform engineering aims to solve common scaling problems. Part of this ecosystem is the field of <em>DevEx</em> that this article is about.</p>
<p>So what is DevEx then?</p>
<p>From my own experience, reading articles, blogs, job descriptions and social media posts over the years I found there is a broad spectrum of how people think of DevEx. On one side of this spectrum is the view that DevEx is in charge of building tools that help developers more easily and faster test and release their software. More specifically, that often translates to the team that owns the software delivery pipeline (i.e. the processes and tools that get the software from the development to the user). I think of this as <em>Functional DevEx</em>.</p>
<p>On the other side of the spectrum DevEx looks at the whole developer journey (i.e. from hire to leave) as if it were a critical system. That makes all frictions and blockers that affect the impact that the developer can have (on the outcome) a concern. This implies a potential agenda everywhere that can affect the developers doing their work: processes, culture, and of course <em>also</em> the tools that influence day-to-day tasks. I call this <em>Comprehensive DevEx</em>.</p>
<p>I am a big proponent of the latter, holistic approach. This is what I will be referring to when writing about DevEx in this article. I believe this is the only sensible approach that leads to significant positive impact for the business that applies it. What this impact is and how DevEx manifests it is what I want to convey here. In my previously mentioned discussions outside of the field I noted that doing so is not easy, because it often requires deep knowledge about software development work. There is a knowledge gap that hinders discussion. I want to bridge that gap with a thought-model that explains the impact of DevEx from first-principles.</p>
<h2 id="unpack-impact">Unpack Impact</h2>
<p>The impact that DevEx has on said bottom line is indirect: It acts upon the factors that lead to the outcome.</p>
<p>So what are these factors then?</p>
<p>Established DevEx frameworks, like SPACE, focus on measuring both human performance aspects (satisfaction, well-being, cognitive load, etc) and system performance aspects (error rate, throughput, stability, activities, etc). I won’t dive into any of that in this article nor will I expect that you, the reader, has any familiarity with the topic. Instead I will introduce four new factors. They are not intended to be used as directly-measurable metrics for day-to-day DevEx work. Their value is in providing an intuitively understandable framework that facilitates the discussion that I want to make happen - within and outside of engineering war rooms. I strongly believe that this will open up significant opportunities and alleviate real pain. Both on the engineering side and for the business.</p>
<p>Consider the following:</p>
<ul>
<li><strong>Education</strong>, encompassing all learning and knowledge gained that is relevant for impact.</li>
<li><strong>Competence</strong>, measuring how well education can be leveraged for impact.</li>
<li><strong>Motivation</strong>, describing the willingness to be impactful towards business goals.</li>
<li><strong>Environment</strong>, evaluating the structure and frictions of the system within which work is being done.</li>
</ul>
<p>The first three of these factors are traits of the engineers, the last is a trait of the organization.</p>
<p>To establish that these factors are sensible I will share a short thought experiment for all of them. In each I will provide a scenario where two potential hires only differ in one of the factors. If this difference is reasonably sufficient to predict the impact that the hires will have on the business outcome, then it is reasonable to assume that they are indeed good factors.</p>
<h3 id="education">Education</h3>
<p>Education - as a container word for any learning or knowledge gain, whether formal, informal or otherwise - should be almost intuitively clear. An example in the world of software engineering is easy to construct:</p>
<p>Say you run a business that provides a service or product through a custom iPhone App for your customers. Now you need to hire a developer to add more features to this App. You have two candidates: Alice, who has an impressive computer science degree and literally wrote <em>the</em> book on iPhone App development practices. Then there is Bob, who you know just started out looking into coding in his free time. You would expect Alice to be able to be productive and ship features that translate to increased adoption and revenue much quicker than Bob, because she has the knowledge to do so and Bob hasn&rsquo;t. You would expect Bob to take a long while to catch up to where Alice is already. You would very likely be right. Knowing only this difference, you can make a good prediction.</p>
<h3 id="competence">Competence</h3>
<p>Competence - as all the experience and developed understanding to apply your education for effect - is equally intuitively obvious. Considering again that hiring scenario, this time Alice and Bob both have a comparable computer science degree, but Alice has already worked for ten years in the field at various well-reputed companies. Her resume and self-presentation in the interview show that she has seen a lot of interesting tech problems in her career - and that she was able to solve them creatively and learn from them. The specifics of her past work align well with what she is expected to do in this new role. Bob however is fresh from the university. He has great aspirations and a puppy-eyed enthusiasm. He has not yet any idea of what kind of challenges await in field-work, but he feels his university degree prepares him for every eventuality. Knowing this it is reasonable to predict that Alice is much more likely to be impactful than Bob - just on the basis of their perceived work competence.</p>
<h3 id="motivation">Motivation</h3>
<p>Motivation - as the internal drive, interest and willingness to exert effort towards a goal - clearly predicts outcome too. This time Alice and Bob have comparable education and work experience. The difference this time is their drive. Assuming you can look in their head and see that Alice is genuinely interested in the work and really wants to help reduce the pain that your product is mitigating for your customers. On the other hand Bob is bored, burned out and considers this opportunity just as another gig to make some easy cash. Based solely on this, you can correctly predict that Alice is much more likely to deliver a higher impact towards your goals than Bob is.</p>
<h3 id="environment">Environment</h3>
<p>Environment - as the sum of all the tools, organizational structures and processes that are part of the value generation and affect the developer - is certainly factoring into the outcome. It is not under the control of the candidates, but it is the context in which they are being hired into. To see the effect Alice and Bob are moved after the hiring stage. Both have equal education, competence and are highly motivated. Alice works in an organization where she can focus on developing the App. She gets effortless highly accurate feedback from the users and can roll out changes within minutes. Bob&rsquo;s workplace requires him to spend a lot of time in coordination meetings, he rarely has an hour of uninterrupted time to work on the App. New releases require a lot of approvals from different departments and many highly stressful, manual steps. They are done only monthly, bundled together with many other developers changes. Given this, it should be obvious that Alice is much better positioned and therefore much more likely to contribute a lot more outcome.</p>
<h2 id="hiring-problem">Hiring Problem?</h2>
<p>While the environment is not in the control of the candidates, the other factors are independently good predictors for the outcome of their potential work impact. Surely, a good hiring pipeline can account for them? Well, no. Or rather: only somewhat, and it depends on the nature of the business that is hiring.</p>
<h3 id="ramp-up-costs">Ramp-Up Costs</h3>
<p>Say your business is a restaurant and you have poached a known top chef from a competing eatery. It would be reasonable to expect that your new hire is able to serve their signature dish equally well in your place as they did at their previous employment. Assuming access to all the right equipment, ingredients, etc, of course.</p>
<p>However, if your business is in tech and you hire a senior engineer then things look quite different. Unless that is your first hire in a new venture, there is likely already a large code base, or many, and often a rather complex technical infrastructure that goes along with that. To understand the current state the engineer often needs to understand the history that led to it as well. More so, previous design intentions and choices often still make up a good part of the active code, even if they are superseded by novel approaches. It will take time for this new engineer to be able to safely roll out changes. It will take even longer until that engineer is anywhere near their peak performance. In large infrastructures a year and more are perfectly expected ramp-up times. This ramp-up time is longer for higher level engineers, which usually goes along with more experience. The reason is of course that higher levels come with greater responsibilities and therefore larger scopes of complexity that must be integrated.</p>
<h3 id="domain-costs">Domain Costs</h3>
<p>During this ramp-up time the new engineer will improve their <em>Education</em> by integrating the domain knowledge: Understanding of the code base, infrastructure, organization, culture, and so forth. They add to their <em>Competence</em> by applying their knowledge and navigating the domain (the workplace). Their <em>Motivation</em> is also affected by the experience of the engineer while going through this process and being confronted with the <em>Environment</em>. Negative experiences (like frustration, confusion, anger) usually drain motivation quickly, whereas positive experiences (like success, feeling supported, aha-moments, leveling, etc) build it up.</p>
<p>In other words, in addition to the education, competence and motivation that the engineer comes with there is:</p>
<ul>
<li><em>Domain Education, that</em> can only be acquired after joining the company and learning about the local setup, code, structures, etc.</li>
<li><em>Domain Competence,</em> that can be only gained when already working within the structure of the company.</li>
<li><em>Domain Motivation</em>, that is shaped by the experience of the individual engineer in the <em>Environment</em>.</li>
</ul>
<p>I am going to call this the **Domain Cost. **The price that has to be paid to approach peak or even high performance.</p>
<h3 id="somewhat-a-hiring-problem">Somewhat a Hiring Problem</h3>
<p>Back to the question whether this is a hiring problem: If there is a very low domain cost, then sure. If there is high domain cost, then only insofar that hiring can filter for <em>potential</em> peak performance and <em>potential</em> timeframe to get there. With tech companies, unless they just start out, there is almost always a high domain cost, because it simply reflects the size and complexity of the structures that make it up and that individual contributors must deal with.</p>
<p>To be clear, my use of <em>peak performance</em> may imply that this is only about getting the last few percentage points of performance: It is not. This is about even low to moderate performance. The best software engineer in the world won’t be able to be productive if they don’t know how to ship code, have no clue where to make changes, or are unable to get the right approvals if that is needed.</p>
<h3 id="process-not-destination">Process, not Destination</h3>
<p>Complexity usually tends to breed more complexity. Your tech business is not static. The code-base is not static: it may be refactored and restructured massively and many times over its lifetime. The infrastructure is not static: it may evolve through designs, or arising opportunities, it will shrink, grow and generally scale many, many times. Processes resulting from organizational structures are not static, because organizations tend to re-organize themselves periodically, they move through expansions and contraction, they are influenced by many changing factors like changes in leadership or market conditions.</p>
<p>That means: the domain specific knowledge continuously evolves, corrects itself, extends, deprecates and so forth. This is why I chose <em>Domain Costs</em> over <em>Ramp-Up Costs</em>. The expenditure is continuous. It starts with a steeper curve (i.e. onboarding and ramp-up). It still will have many small and large curves ahead.</p>
<p>Do not fall into the trap of looking at this only as a “cost of doing business”, because this would leave a large opportunity on the table: leveraging this understanding well to vastly increase the outcome. This brings me to the topic of this post:</p>
<h2 id="devex-for-impact">DevEx for Impact</h2>
<p>A general recipe for DevEx work is hard to come by, although I will try to provide commonly applicable examples shortly. In real life the work is highly situational. DevEx is fundamentally interested in every step of the developer journey: starting with hiring, on-boarding, ramp-up, day-to-day and ending in off-boarding. Every aspect of the systems and organization that affect developer work along this journey is a concern of DevEx. While DevEx will not “run” all these places, it will certainly have an agenda for them if they cause friction or provide opportunities. The specific measures then depend on the situation of the organization: where is the largest friction to be removed? Where are the easiest gains to get?</p>
<p>Having this said, let&rsquo;s have a look at concrete actions that DevEx can undertake to improve the four factors. I will need to use some software development jargon to illuminate their effects, but I will try to limit that as much as possible.</p>
<p>Mind that what I propose are large scale initiatives, which bundle many individually useful efforts that could be undertaken separately, or at least iteratively. I aim for the bigger picture. Furthermore, none of these efforts need to be done by DevEx, although DevEx will be interested in ensuring that they come to be and is well positioned to initiate and drive them at the start.</p>
<h3 id="pave-the-delivery-pathway-cicd">Pave the Delivery Pathway: CI/CD</h3>
<p>Create standardized, automated pipelines that reliably build, test and deploy software changes with minimal or no manual intervention. Yes, this is “classic CI/CD”. The goal is to increase the efficiency of the software assembly line.</p>
<p>What does this impact?</p>
<ul>
<li><strong>Environment</strong>: Drastically remove friction in code delivery by categorically removing many manual error scenarios and eliminating manual efforts.</li>
<li><strong>Competence</strong>: Provide fast feedback loops for developers enabling rapid iteration and fast validation.</li>
<li><strong>Motivation</strong>: Eliminate frustration and anxiety that come with manual, high-risk software releases. Increase job satisfaction by allowing engineers to focus on development work.</li>
</ul>
<h3 id="unlock-engineering-know-how-knowledge-management">Unlock Engineering Know-How: Knowledge Management</h3>
<p>Create a centralized knowledge hub (sure, a wiki) that enables knowledge ownership and provides quality feedback pipelines to these owners. Enable domain actors to contribute with ease. Advocate organizational buy-in to prioritize and remunerate knowledge management work of engineers. Based on this, create and maintain a streamlined learning pathway for onboarding.</p>
<p>What does this impact?</p>
<ul>
<li><strong>Education</strong>: Flatten learning curves, especially during initial onboarding. Reduce distribution and access costs for crucial knowledge, lowering learning barriers.</li>
<li><strong>Competence</strong>: Reduce cognitive load of “hunting for information”. Increase confidence to act through reliable, authoritative information.</li>
<li><strong>Motivation</strong>: Signal interest in long-term growth of individual engineers, improving trust and goodwill.</li>
<li><strong>Environment</strong>: Reduce friction of navigating within systems. Disperse tribal knowledge boundaries.</li>
</ul>
<p>I think a note on using AI (or specifically LLMs) is needed here: I consider this an implementation detail, as it is “only” an interface for the information. A powerful one, but it builds on reliable and recent domain-specific information as any other interface would. The above proposed measures for knowledge ownership and ease of contribution are unchanged by that and I maintain that guided learning pathways are also not obsoleted, but amended by this technology.</p>
<h3 id="fast-track-talent-systematic-leveling">Fast-Track Talent: Systematic Leveling</h3>
<p>Establish a buddy system for onboarding and a career-long mentor system that incentivizes participation and is supported by best-practice knowledge and complemented by self-guided learning paths.</p>
<p>What does this impact?</p>
<ul>
<li><strong>Education</strong>: Extremely short feedback loops enable quick learning. Largest possible bandwidth for tacit knowledge and culture transfer. Enables continuous learning.</li>
<li><strong>Competence</strong>: Quickly overcome beginner problems in onboarding and ramp-up. Early exposure to production work, with safe-guards, builds confidence fast, reducing ramp-up strongly. Enables continuous skill development.</li>
<li><strong>Motivation</strong>: Strongly reduce anxiety and confusion during onboarding and ramp-up. Demonstrates deep investment in person, building loyalty and engagement.</li>
<li><strong>Environment</strong>: Supports collaborative and knowledge-sharing culture. Builds fast support pathways and deep connections that reduce communication friction.</li>
</ul>
<h3 id="empower-builders-developer-platform">Empower Builders: Developer Platform</h3>
<p>Create a unifying platform where developers can make use of standardized templates, tools and services (like requesting test environments, managing monitoring, accessing application logs, configuring scaling for applications, etc) that are entirely self-service and reduce the amount of complexity developers have to deal with.</p>
<p>What does this impact?</p>
<ul>
<li><strong>Environment</strong>: Increased consistency and reduced complexity free up mental resources. Reduce cognitive load reserved for secondary activities that are not development.</li>
<li><strong>Competence</strong>: Empowers engineers to manage their applications with low effort, giving them control and enabling them to focus on their core competencies.</li>
<li><strong>Motivation</strong>: Less frustration when engaging with infrastructure, through hardened and performance-optimized workflows.</li>
<li><strong>(Education)</strong>: Persist organizational knowledge in code, countering knowledge degradation and enabling knowledge validation.</li>
</ul>
<h3 id="bridge-team-silos-cross-team-exposure">Bridge Team Silos: Cross-Team Exposure</h3>
<p>Create structures to give individual engineers the chance to rotate temporarily in other teams (especially adjacent ones) to transfer both explicit and tacit knowledge peer-to-peer.</p>
<p>What does this impact?</p>
<ul>
<li><strong>Education</strong>: Creates a channel for tacit knowledge transfer. Breaks down knowledge silos. Enables T-shaped knowledge building (deep learning in specialization, broad understanding of context).</li>
<li><strong>Competence</strong>: Improved decision making abilities through better understanding of related systems and organizations.</li>
<li><strong>Motivation</strong>: Forms bonds, contributes to motivating we-feeling.</li>
<li><strong>Environment</strong>: Establishes shorter communication pathways. Improves collaboration.</li>
</ul>
<h2 id="how-much-impact">How Much Impact?</h2>
<p>You may have noticed a lack of any hard numbers that predict the business outcome in the previous examples. That could not be helped. DevEx is similar to adjacent disciplines like security or reliability. They all affect the very “fabric” and shape of the systems that they are part of, which makes predictions rather difficult. It is very challenging to quantify the damage to customer-trust - and the bottom line in the years to come - that was <em>prevented</em> by thorough security measures. It is almost impossible to count the outages that <em>did not happen</em> due to top-notch reliability efforts. Similarly, it is futile to attempt to measure the impact of inventions that were made because of continuous learning structures that have been put in place. Or the time saved by automating annoying processes that then freed engineering resources to improve documentation, which then prevented countless person-years of information hunting, and so forth.</p>
<p>The field of medicine provides an excellent comparison. A medical doctor knows what “healthy” looks like, generally speaking. Similarly DevEx practitioners know what a “healthy” system looks like and what a “healthy” developer journey entails: smooth workflows, fast feedback, uninterrupted information flow, stable and efficient operations, etc. Medicine uses “pain” as an indicator for health problems. So does DevEx, although it calls this “friction”, which manifests as developer frustration, slow processes, unreliable tooling, or production incidents. Both medicine and DevEx can formulate treatments to improve the state towards “healthier” (see the previous examples). Both think of their domain (the human body and respective tech organization) as complex systems where changing one part influences many others.</p>
<p>Now, a medical doctor can still confidently say that healing a broken leg will enable a patient to walk and run substantially faster. However, they would <em>not</em> be able to predict how many seconds faster the healed patient would run in a 100 meter sprint. The notion itself is ridiculous. In that same sense can DevEx identify significant friction (i.e. the “broken leg”) and confidently state that addressing that will improve the outcomes: faster delivery, higher quality, more innovation, etc. So while the precise impact of individual measures may be forever elusive, there is no question whether “curing” unhealthy components is tremendously beneficial to the whole.</p>
<p>Having this said: DevEx, reliability, security and medicine have plenty of hard numbers to go on. They are all strongly leaning on empirical evidence. However, these are proxy metrics. Like DORA’s metrics, which are well established by now, they can be used to measure the health and identify friction, but they won&rsquo;t give you a good prediction for the bottom line of the next quarter.</p>
<h2 id="conclusion">Conclusion</h2>
<p>I hope this article illustrates how a comprehensive DevEx can impact the bottom line by improving the factors that lead to it. Needless to say, I have only I provided a snapshot of what is possible</p>
<p>I am deeply curious how others look at DevEx and see the opportunities it offers. Write to me, if you have opinions!</p>
]]></content:encoded></item><item><title>The Expert Deadlock Dilemma</title><link>https://ulrichkautz.com/posts/2024-06-03_the-export-deadlock-dilema/</link><pubDate>Mon, 03 Jun 2024 00:00:00 +0100</pubDate><guid>https://ulrichkautz.com/posts/2024-06-03_the-export-deadlock-dilema/</guid><category>deadlocks</category><category>engineering</category><category>teams</category><category>productivity</category><description>Uncover the hidden pitfalls that lead to costly Expert Deadlocks in engineering teams and learn practical strategies to break free from the quagmire of indecision.</description><content:encoded><![CDATA[<p>This article is written for software engineers that work in collaborative settings. It is also interesting for anyone on the business end of tech and everybody that works in supporting tech teams with decision making (if only to read the perspective of someone on the receiving end of that support).</p>
<p>If the following story speaks to you, then keep on reading:</p>
<blockquote>
<p>A small team of software engineers sits together in a cramped, windowless conference room. It smells like sweat and sugary drinks. The AC tries to make up for its inability to sufficiently air the room by producing more noise. Snacks, laptops, and whiteboard markers litter the table in the center. This is the fifth time this week that these people have come together to talk. It is only Wednesday. The last two weeks looked no different.</p>
<p> </p>
<p>Despite everyone on the team being really experienced in their domain, which they all share, you can feel the tension. Nobody is at ease. Odd glares are exchanged. People shift in their seats and seem not to be able to find a comfortable position. One member frantically scrolls through a large document. Another cleans the whiteboard on the wall with quick and needlessly powerful strokes that speak of anger and frustration, something that is palpable in the room. You can see varying degrees of the same frustration and the same anger written on everyone&rsquo;s face. And exhaustion. Everyone looks as if they haven&rsquo;t slept for days. They have. Their fatigue is caused by hours upon hours of discussion over days and weeks. Discussing what? A simple question, really: what is the best approach to solve &lt;this problem&gt;?</p>
<p> </p>
<p>_By now, everyone in the team has developed a strong opinion about that. The trouble is just: Not two of them agree on what the best approach is. Only that the other&rsquo;s methodology is flawed and ridden with pitfalls. Only that much is agreed. One of the engineers makes a throat-clearing sound and starts to say, &ldquo;I think I have found another perspective to illustrate why we should not consider the outcomes of yesterday&rsquo;s proof-of-concept a valid sample, because&hellip;&rdquo; which is as far as that goes, before a chorus of moans and snarls from the others around the table puts an end to this attempt. &ldquo;Really?&rdquo; asks another. &ldquo;You spent the rest of your time yesterday trying to prove that we are unable to agree on even that much?&rdquo; Heads around the table nod vigorously, and the first speaker starts to turn red. &ldquo;Yeah, really,&rdquo; the exasperated reply bursts out, &ldquo;we cannot go forward if it is clear that we will fail on this path!&rdquo; More irate sounds emerge, and the mood in the room noticeably sours by at least one more octave.</p>
</blockquote>
<p>Let&rsquo;s pause here. This illustrates what I&rsquo;d call an <em>Expert Deadlock</em>. Nothing is moving forward. Nothing is being decided. Everyone is mad. It is bad for every individual involved because it smokes you up, burns you out. It is bad for the business because it is the most unproductive state possible: total stalemate. It may not be as bad as illustrated in every case. Sometimes you are able to still progress in some areas while being in a deadlock with only specific decisions. Sometimes a deadlock lasts only for days and not weeks (or months). Either way. It is always very taxing in the moment and it always has the potential to cause long lasting damage in the team relations.</p>
<p>Have you been here? Are you in that picture? How do you think a mess like this came about? How can you fix it?</p>
<p>Well, I&rsquo;ve been there. I&rsquo;ve seen it happen to others, and I&rsquo;ve heard about it, too. Speaking to a friend who currently is in a similar place is what triggered me to write about it now. There are many variants of this scenario. Often, it is not as bad as my fictional story above - at least not yet. Sometimes it is worse. From what I can tell, this is not an uncommon occurrence at all. Alas, among software engineers, which is my realm of experience. If you haven&rsquo;t seen it yet, count yourself lucky. Or not, because then you might not know how to handle it when you encounter it. We&rsquo;ll get to that later.</p>
<h2 id="casus-belli">Casus Belli</h2>
<p>So, how do we end up in a dilemma like this then? From my observations there are many individual reasons and contextual circumstances that contribute. I am not interested in those. What I care about are the common, underlying patterns. If they are known you will fall prey less easily to them. Let me also be clear: this is not about bad actors that have bad intentions, are motivated by greed, or are malicious - or any such notions. I am sure all of that could easily yield a situation as described - but it is not needed. This happens to juniors and highly experienced people alike, who work together in good faith, and with good intentions.</p>
<p>The following reasons I’ll be discussing here are all contributing. All of them are sufficient, as in: they are enough to produce an Expert Deadlock. All of them are also probabilistic, as in: You can get away with any of them, if your circumstance allows it. I highly doubt that this list is comprehensive. It is only the list that I have experienced myself so far.</p>
<h3 id="goal-glitches">Goal Glitches</h3>
<p>A common contributor to messy situations is the good ol’ <em>misalignment of goals</em>. If this divergence is known, then it&rsquo;s easy: you can account for that - or choose to part ways. However, if it is not known, then it becomes awkward. You may pitch your idea with the best reasons that are fully supported by data and still you find yourself rejected. And probably hurt. The other person simply doesn&rsquo;t share your priorities as they have a different goal in mind. Imagine we are both bakers and I try to convince you that blue icing is the way to go, as proven by extensive empirical research. You simply don’t care, because you cannot see how this contributes to the goal of healthy cakes that you have in mind. We are badly misaligned here. The chance of us finding an approach we both agree on is very low – especially as long as we both operate under the assumption that the other is sharing our goals.</p>
<p>This contributes to Expert Deadlocks in two ways: First, by people simply talking past each other. I’ve taken part in hours of heated discussion only to find out that everybody was talking about something different entirely. You might think this could only yield a brief deadlock, because such misunderstandings are certainly uncovered quickly, right? Well, if you are lucky, yes. However, it doesn’t take long for emotions to become entangled and then for stung egos to supersede rational argument. Once at that stage, it is not easy to think straight and even the obvious may elude you. Not only can it take much longer than you think to even identify the misalignment when in this state, people that are that riled up may still choose to continue arguing either way.</p>
<h3 id="deep-ends">Deep Ends</h3>
<p>The holy triangle of the three Ps - Perfectionism, Pragmatism, Passion - is both a curse and a blessing in any software engineering endeavor. They must be carefully balanced to arrive at a desirable outcome.</p>
<p>Perfectionism makes us focus on details that might be essential. It drives us to optimize and iterate until we can make true breakthroughs. Too much perfectionism leads to many <a href="https://ulrichkautz.com/zettel/yak-shaving/">yaks losing their fur</a> and many <a href="https://ulrichkautz.com/zettel/going-down-a-rabbit-hole/">rabbits being disturbed in their holes</a>. Nothing is ever shipped because something can always be improved, or polished, or refactored, or &hellip;</p>
<p>Pragmatism makes us focus on solving the problem. It allows us to be open to any approach. It drives us toward efficiency. Too much pragmatism results in a whatever-attitude and sloppy solutions. Trashware systems, the eventual outcomes, are as maintainable as they are usable: not.</p>
<p>Passion is <em>The _key motivator. It feeds us energy. It makes us stay after hours and come back early in the morning. It drives us towards impossible goals – and makes them possible. Too much passion makes us blithely impervious to facts and data: “_The critics are just afraid</em>” or “<em>You just fail to see the vision</em>”. A marvelous approach to create spectacular art. A terrible mistake for the business of engineering.</p>
<p>Expert Deadlocks can easily arise from an excess of both perfectionism or passion. Either makes for a great foundation for last stands on the least relevant hills. I cannot see extreme pragmatism leading to a deadlock. However, it can create meetings where nobody gives a sh*t and that comes with its own pitfalls.</p>
<h3 id="tunnel-vision">Tunnel Vision</h3>
<p>This happens to the best of us: You are deeply into a topic, say a technical solution of sorts, then you gradually lose perspective of the big picture until you are so focused on the task that you forget why you started it. You simply lose sight of the reasons for your actions (and everything else) by focusing entirely on those actions. That is not a wholly wrong approach either: we humans are <a href="https://asana.com/resources/multitasking">single-taskers</a> after all, and we are much <a href="https://ulrichkautz.com/posts/2023-04-13_interruptions-the-silent-high-performance-killer/#why-do-interruptions-increase-error-rate">less prone to errors</a> when doing one thing, than when doing multiple things. This focus increases the quality of our work. Even if this work is unnecessary or counterproductive.</p>
<p>I’ve seen Expert Deadlocks arise – even with rather seasoned engineers that you would think know better (and yes, I was one of them) – when people just get <em>too</em> invested into a solution to be able to back out easily. It hurts to do that. Nobody wants to get hurt. It&rsquo;s so much easier just to keep going. A room full of engineers that are afraid to lose all the efforts they have put in over the last days / weeks / months – not to speak of all the self-worth that is bound up in that – is not the most rational place.</p>
<p>Being able to step back, take a breath, detach yourself from the emotions of an approach and refocus on the bigger picture is both a skill and a function of culture. It can be learned and it can be taught. And it can be prevented if acknowledging or making mistakes is punished.</p>
<h3 id="fear-is-the-mind-killer">Fear Is The Mind-Killer</h3>
<p>This brings me to another common cause. And it is a sneaky one. While being able to step-back and regroup is a great skill, it can also be overdone. Being afraid to commit to a pathway. Ever seeking the comfort of the higher-level perspective. While that may not end in the clash of strong opinions, it ends in a myriad of evaluations, trials and proof-of-concepts that eventually have no value because they never go far enough to have any effect at all.</p>
<p>Thereby it can also lead to an Expert Deadlock by creating a room full of critics and nitpickers. Everyone then only sees problems with everyone else’s solution. Always one more alternative that needs to be reviewed. Effectively nobody is willing to take the risk of having signed off on a future failure. The only proposals are then either so outlandish that there is no chance in hell that they will be accepted (so there is no risk to propose them) or they are so vanilla that doing them or not makes no difference (and there is no risk of failure).</p>
<h3 id="dog-eat-dog-ethos">Dog Eat Dog Ethos</h3>
<p>Somewhat related to the previous point is a culture of hyper-competitiveness. A place where everyone is pitted against each other, where any advancement requires continuously winning against somebody else (or cutting them down, to step over them). I know this may sound like the bad actors I said this would not be about. To this I’d say (with sadness): if it is culturally / structurally caused, then the actors are not bad, just rational.</p>
<p>Either way I think it’s pretty obvious how this creates a breeding ground for Expert Deadlocks: The overarching incentive is to promote yourself. If it is more important to look good than to make headway towards a shared goal, then why would you? Agreeing to a proposal from your boss, so as to increase the chances of climbing up the ladder yourself? <em>Sure, a concession here may get me a promotion</em>. Agreeing to a proposal of a peer, however suitable and beneficial? <em>Nah, if they shine and get the promotion then I won’t</em>.</p>
<h3 id="feedback-void">Feedback Void</h3>
<p>This is the big one. Big as in: All of the above can be mitigated or aggravated by how this is done. The previous point about hyper-competitiveness illustrates how feedback loops that stimulate bad behavior lead to a deadlock. This is about how the lack of them can be even worse. Feedback is essential to being able to formulate goals and specify the right work that needs doing to achieve those goals.</p>
<p>How those feedback loops are implemented depends on the individual organization: They might come as leaders that are sufficiently knowledgeable and involved to be able to make decisions and can act as tiebreakers. Or they emanate from a community culture where proposals of solutions can be discussed without fear of giving critique nor reluctance to receive criticism (think RFCs). Or both. Or something else entirely.</p>
<p>If such mechanisms are lacking and an individual team is entirely free-wheeling, then any of the above factors can easily take hold and grow. There is no steering mechanism that provides direction or even keeps us from falling into the abyss. The Expert Deadlocks that will eventually arise are likely one of the lesser problems that come out of it.</p>
<h2 id="make-progress-not-war">Make Progress Not War</h2>
<p>Nobody wants to be a character in the story at the beginning. Still, we find ourselves in such situations. We discussed some factors that make it more likely that we arrive in such a mess. The questions now are: How can we make sure that we do not end up here? And: if we do, how can we get out again? Prevention and remediation.</p>
<h3 id="prevention-strategies">Prevention Strategies</h3>
<p>Measures that reduce the risk that deadlocks arise are almost exclusively structural. Which means they must be implemented at organizational level. They must be part of the culture.</p>
<h3 id="culture-of-candor">Culture Of Candor</h3>
<p>If you do not know where to start, then start here. The following is absolutely fundamental for highly effective teams. You can look at it as a general antidote that strengthens teams’ abilities to work together and therefore immunizes against deadlocks and other ailments. It comes out of a body of decades of research, among which a multi-year study at Google that involved hundreds of their teams to answer the question: “<em>What makes teams effective?</em>”. It was called <em>Project Aristotle</em> and you can read up on the journey that it was <a href="https://www.nytimes.com/2016/02/28/magazine/what-google-learned-from-its-quest-to-build-the-perfect-team.html">here</a>.</p>
<p>The primary learning that you should take from that is the concept called <a href="https://ulrichkautz.com/zettel/psychological-safety/">Psychological Safety</a> – a term coined already at the start of the millennium by <a href="https://en.wikipedia.org/wiki/Amy_Edmondson">Prof. Edmondson</a> from the Harvard Business School. It measures the <em>degree to which people in teams / organizations <strong>believe</strong> that they can be candid without being punished for it</em>. There is of course more to it, but this is the gist. A team that rates high on Psychological Safety is much more likely to be effective. As a matter of fact: Google’s study did not find <em>any</em> other factor that came even close in predictive prowess. This efficiency also includes the ability to reach decisions smoothly, that is: without falling into Expert Deadlock traps.</p>
<p>So how can you help to improve the perception that candor does not backfire then? Well, if you are coming from the <a href="https://ulrichkautz.com/zettel/dev-ops/">DevOps</a>-world as I am, then you are probably immediately reminded of <a href="https://ulrichkautz.com/zettel/blameless-postmortem/">Blameless Postmortems</a>. Postmortems are processes to analyze previous incidents, so as not to repeat them. The practice of Blameless Postmortems shifts the focus away from individuals as the primary contributing factors and instead concentrates on the systemic causes. It has been very effective in addressing root causes and improving systems, hence it is by now widely accepted across the industry. Another consequence is that it makes candor without punishment a valued, nay necessary virtue.</p>
<p>Of course, this practice is only relevant for very specific situations: reviewing past incidents. In <a href="https://en.wikipedia.org/wiki/Systems_thinking">Systems Thinking</a> exists an idea that arrives at extremely similar conclusions as Blameless Postmortems, only it applies them to a much larger scope. It is called <a href="https://ulrichkautz.com/zettel/just-culture/">Just Culture</a> and it seems to be spreading through many industries. The principles are again the same: instead of blaming individuals when something goes wrong, it asks “<em>What are the causes?</em>” and then focuses on solving the systemic issues that such questions uncover. Optimized systems are the outcome. Again, this only works where candor is not punished but encouraged, thus looping back to Psychological Safety.</p>
<p>Note: this a prevention measure because it takes time to build a culture with sufficient trust to be candid. <strong>Do not attempt this in the moment of crisis.</strong></p>
<h3 id="escalation-path-safety-net">Escalation Path, Safety Net</h3>
<p>Setting everything up to lessen the likelihood of arriving at an Expert Deadlocks, as the previous point aims to, is where you start. However, consider that it takes only one nasty Expert Deadlock that leaves a formerly high-achieving team in tatters. Even if it doesn&rsquo;t fully destroy the team, each such highly-emotional stalemate chips away at the bonds of trust that tie the team together. High cost, even if you are able to make it low risk.</p>
<p>My years of work in reliability topics left me on the constant lookout for risk mitigation strategies. What comes to mind here is the need for safe-guards that trigger automatically before a critical threshold is reached. Those safe-guards should have the shape of escalation paths and a set of guidelines when they trigger. Like: <em>If we come out of the second meeting about the same topic without agreement, then we escalate</em>. The simpler the better. It is more important to establish this as a habit than to optimize for efficiency. Err on the side of escalating too early rather than too late. Escalating is cheap, failing to is not.</p>
<p>As for how the escalation plan should look: the best I have seen requires simply having an empowered <em>lead engineer</em> on each team. In less formal situations this role can also be filled by an inofficially agreed <em>tech lead</em>. Whatever the name, the point is that one person is the <em>predesignated decider</em>. They are handed the mighty decision-hammer that they can take out in the time of need to break a tie or to end a deadlock. A technical manager that is sufficiently involved in the day-to-day can also work. Worth mentioning here are the perils of micromanagement and running amok on a power-high (neither of which I will detail in this article). In any case: Decision making through escalation should be the exception, never the norm (if it is then this should ring alarm bells about the state of the team).</p>
<p>To emphasize the previous point about candor: this goes for tiebreakers as well. If they are afraid to make a decision their value is blunted at best and negative at worst (i.e. when their decisions are not based solely on best knowledge considering all input).</p>
<p>A single level of escalation will already mitigate the risk significantly. Another level, like a director or CTO that is indeed willing and able to be of value here gives a warm and fuzzy feeling to everyone involved – even if never really used.</p>
<p>I found that not only a lack of organizational planning but also an overemphasis on a culture of consensus leads to situations where such escalation paths are missing (or worse: are seen as bad, because they are &ldquo;too hierarchical&rdquo; or some such notion). While this approach may be admirable and can work in specific situations for a while, I think it ultimately leaves teams vulnerable. Without clear escalation paths, every disagreement has the potential to escalate into a full-fledged confrontation, putting the team at risk of falling into an Expert Deadlock.</p>
<p>Note that this is a prevention measure because designating anyone in a position that can serve as tiebreaker requires good faith and ideally is giving credence over time by solving smaller team issues. Attempting this in an active stalemate situation can easily backfire and burn more trust and bridges than you aim to repair. Otherwise see the following headline “<em>Utilize Peer Perspective</em>”.</p>
<h3 id="remediation-tactics">Remediation Tactics</h3>
<p>Having the above prevention measures in place goes a long way. However, as you are here reading this, chances are it is too late for you to think about this now.</p>
<p>If you are currently in a stalemate of sorts then your first priority is to get out of that. Following I will give you tactics that I found useful in the past. Of course, they won’t be all applicable to your current situation. You will have to cherry pick what makes most sense for your case. To do that you first need to know your options:</p>
<h3 id="peer-to-peer-arbitration">Peer-to-Peer Arbitration</h3>
<p>Shift the question! While you are in a deadlock to decide a particular question: can you still agree on something else? Like which pizza to order? If so, then good. There is hope for an easy out. Try to agree on the following: an external arbiter. This person must be experienced enough so that you all will trust their decision and far away enough so that you do not suspect bias. This is somewhat similar to the prevention measure of a tiebreaker, but different in that it is a one-off and cannot be someone already part of the team that is part of the stalemate.</p>
<p>Whomever you end up deciding on I would strongly recommend not to involve them in your (potentially heated) discussions but instead to give them a short(!) written summary of each branch of the decision tree that you are unable to agree on. Allow them to pick all of your brains if they have questions. Ideally in 1:1 meetings, so as not to have them influenced by the eye-roles and moans of despair that might come up in a group-setting. Now to the hard part: Await their decision. Trust it is good enough.</p>
<p>Note that only full agreement in advance of the arbitration will help you to break the stalemate. Pulling somebody new in without having the team’s consent only aggravates the issue and is not helpful (doubly so if they support <em>your</em> position).</p>
<h3 id="less-planning-more-driving">Less Planning, More Driving</h3>
<p>I had a really hard time to put this into words, so I have to fallback to story time again:</p>
<p>Imagine a gaggle of disagreeable Tolkien’esque dwarves that visit the surface for the first time. They are quarreling over the right route to take on a map. They all concur on the destination – a place full of precious treasures, gold and gemstones of course – but they cannot settle on how to get there. The destination is a long way out.</p>
<p>The map they are looking at is badly drawn. Some roads were clearly added later by an amateur. Annotations litter the canvas: “<em>road does not exist anymore</em>” it reads here or “<em>don’t trust this overpass, it has fallen down</em>” is written over there. The dwarves are loudly squabbling and arguing with each other. One proclaims angrily “<em>Your path is curving away from the destination! How could it possibly bring us there?</em>” Another exasperates “<em>The bridges you claim are there do not exist on the map! How would we get across those canyons?</em>” And so it keeps going on and on.</p>
<p>Riddle me this: how can you find out which of the dwarves knows the right path? Well, you can&rsquo;t. The thing is: they are all wrong. The reason is that the map is just too bad. Any plan based upon it is doomed to be wrong! There is really only one strategy that delivers the bearded travelers their destination: Stop looking at the map and look around instead, then head in the direction of their destination. Ideally find higher ground. Maybe scout ahead. Use the map only to navigate around large, unchangeable features like mountains or canyons. If they keep on doing that they will arrive eventually. Unless they discover an even better opportunity on their route, which might happen.</p>
<p>Why do I tell you this story about dwarves and maps? What does this have to do with remediation of Expert Deadlocks among engineers? Everything. If you are one of the engineers in a deadlock, then you did put your own proposal forward. Withdraw it. Now! Acknowledge that all of your solutions are based on incomplete / invalid information about the technical landscape. Worse, the landscape is ever shifting and evolving with new pathways popping up all the time, while old ones deteriorate or disappear entirely. The further ahead, the further in the future, the more wrong your assumptions will become.</p>
<p>If you cannot make this plain to everyone (remember: you are in a deadlock) you must break the deadlock by instead picking one of the other proposals that a) goes <em>mostly</em> <em>in the right direction</em> and b) is the most likely to <em>get more support by others</em>. While you should not assume that this chosen route will deliver you to your goal, you need to accept that it is enough to move ahead towards where you want to go. By that you take on the <em>role of the driver</em> that gets everyone moving in the right direction. <strong>Prioritize progression on the right trajectory over the specifics of the movement!</strong></p>
<p>Yes, there are a multitude of asterisks to this, many of which I simply <a href="http://ulrichkautz.com/zettel/tacit-knowledge/">cannot put into words</a>. I give this advice with the assumption in mind that most engineers strongly err on the side of overthinking. I am also harping on this point and wrote a whole story to bring it across because my advice often necessitates to go along with or even champion flawed plans. This seems especially hard to do for engineering-minded people. It certainly was (is?) for me. I think this is the case because among engineers subpar solutions are considered almost offensive. This is why criticism of our own solutions are often received as personal slights to our skills and abilities. Get over it. It is a deterrent from being a driver of progression. You are building an obstacle where you should build a ladder.</p>
<h3 id="use-the-right-tool">Use The Right Tool</h3>
<p>If there is one thing that humans excel at it is certainly tool creation and use. Tools are the distillation of learning into a device or process that makes doing specific things easier (or even possible). There is a whole pantheon of tools that are geared towards team decision making. I am by no means deep into this topic, but I have employed some such tools in the past and I have also seen them employed by others. More importantly I am in the lucky position to know someone closely that is extremely experienced in this field. <a href="http://amandaparker.co">My wife</a>. I picked her brain so that I can give you some immediately useful tools. Useful meaning: circumventing or hacking intentional or unintentional behaviors that are obstacles in the pathway towards making a decision.</p>
<p>Know that I have no affiliation with any of the following (nor do I use affiliate links). You can take this as “to the best of my knowledge”.</p>
<p><strong>1. Workshop Tactics</strong></p>
<p>I write this article with people like myself in mind: software engineers. I assume you are one. That means you are likely specialized in some deeper field in that domain – as I am. Hence you can conceive that there are other people specialized in other equally deep fields. You probably also know how rarely such a focused immersion coincides with the ability to communicate or explain it to someone on the outside. Are you with me so far? Ok. Here is the thing: there is someone that is deeply into the field that pertains to team decision making. This someone is named <a href="https://x.com/chburdett">Charles Burdett</a> and he happens to also be an amazing communicator. He used that to encode his knowledge in a way that is immediately actionable (drumroll) in the form of a deck of freaking playing cards! You can buy this deck for small money (search “<em>workshop tactics deck</em>”). Or you can use it entirely for free <a href="https://pipdecks.com/pages/workshop-tactics">online</a>. It even comes with a whole decision-tree interface that guides you exactly to a very useful set of immediate things that actual work to tackle. Try it.</p>
<p><strong>2. Design Sprint</strong></p>
<p>So there is this big internet company that has a lot of very expensive (because very good) people employed. They have a huge amount of great ideas that they want to bring to the rest of the world as products. As execution is generally hard, many such attempts to productize ended in a mess. Or if not: they took longer than anticipated and were more expensive than necessary. Consequently the big internet corpo was eager to find a reliable and reproducible way that allowed them to go from idea to product. This way also needed to be easy enough so that everyone could follow it without creating a mess. The company is named Google and the methodology they came up with is called <a href="http://www.gv.com/sprint/">Design Sprint</a>. It is a formalized 5-day process that starts with understanding the problem space, goes to sketching solutions, then making decisions and lastly validating the approach (it can restart from there if this fails). The leading inventor at Google was <a href="https://jakeknapp.com/">Jake Knapp</a> who later published the recipe of the sprint in a <a href="https://www.thesprintbook.com/">book called “Sprint”</a>.</p>
<p>Both of the above proposals share a couple of elements that make them rather efficient:</p>
<ol>
<li>Less overthinking, more momentum through time-boxing and other forced constraints</li>
<li>Focus through guidance of structured activities vs free-wheeling</li>
<li>Quick decisions through processes that whittle down options fast</li>
</ol>
<p>There is more to it, but this is what convinces me. I didn’t like the gamification aspects (just seemed contrived / fake). Still, not a great fan of that part. However, I am swayed as I have seen reliable results with good quality coming out of this. And quickly too.</p>
<h3 id="seek-professional-help">Seek Professional Help</h3>
<p>Who would have thunk: there is a whole industry that is facilitating the above. They are called (drumroll) <em>facilitators</em>. Mind blown. But seriously: if you cannot do this alone, there is no shame in getting help. You are already great engineers (I assume), there is no need for you to master this additionally. I mean, do it if you are interested! It is a great skill to have in any collaborative environment. Whatever you decide: do not stay and wallow in your misery.</p>
<p>You may have these kinds of resources in-house. Often <em>Product Managers / Owners</em> are knowledgeable about this. If you happen to have teams that care about <em>Learning and Development (L&amp;D)</em> they are certainly a good address. Generally <em>Human Resources</em> may be experienced as well. If none of that exists or is unhelpful then you will find aplenty resources externally. Ask your peers and friends if they have worked with anyone they can recommend – you might be surprised. Otherwise a google search for a local <em>facilitator</em> or <em>team coach</em> will certainly yield you a lot of results.</p>
<p>The equation that you should consider / pitch to business is simply this: X engineers are not productive for Y days due to stalemate equals Z money. Additionally, through team burn-out and breakage resulting from this, efficiency will be significantly down at least short- to mid-term. Likely long-term. Is this cost smaller or larger than professional help?</p>
<p>Note: If you are in a position to make that call: Make that call. If not then consider putting a limit on how much time you spend in your attempts to get the funds. I found myself frustrated in the past fighting against the wrong windmills (if you keep hearing “<em>sort it out yourself, you are all professionals</em>” then consider it a sign of resigned helplessness and move on).</p>
<h3 id="get-out">Get Out</h3>
<p>This is the hardest. And the easiest. It can feel like giving up. It is not. If you tried, really tried, to resolve your disagreements and still could not do it then acknowledge that and move on. It doesn’t mean you gave up, it means the cost of going in that direction exceeded the value it yields. This can feel almost like a break-up in a relationship. It can go equally wrong and leave everyone hating each other afterwards. Or it can go well and people agree to disagree and everybody just moves towards where they want to go next on their own. No harm done in this case.</p>
<p>Advice how to get this right probably fills books. The only one I can give you is to do it quickly, kindly and firmly. Above all be clear with yourself and anyone else – this is probably the greatest kindness of all. Remember that you can only control your own actions and nobody else’s. This is also where your responsibility ends.</p>
<h2 id="fix-it">Fix it?</h2>
<p>From what I can tell things (at least in the software engineering industry) are moving somewhat in the right direction – but not across the board, only in some select companies that invested the time and money to gain the metrics that make the factors of productivity crystal clear to them. So I think it is on all of us to change that. I do not exclude myself from this at all. Here is how I think you can help, depending on where you are:</p>
<p><strong>Tech Side (developers, engineers, product?, etc)</strong></p>
<p>Do you believe in using the right tool for the right job? If you do then make sure you act the part. Saying things like “<em>don&rsquo;t bother me with this non technical nonsense</em>” is a direct pathway to more frequent, more painful and longer meetings. Unnecessarily, because there are well researched practices and tools that are indeed getting the job (of reducing needed organizational chores) done. If you are already familiar with strategies and tactics to that effect then share them. If not then consider learning them. At the very least be open to take part in them. There <em>are</em> best-practices for collaborative environments. This does not come easy to me as well and I am getting it more often wrong than right. I get you. We just have to get this fixed.</p>
<p><strong>Business Side (managers, executives, product?, etc)</strong></p>
<p>The hidden costs of Expert Deadlocks in your engineering teams are significant. Beyond the immediate loss of productivity, these situations erode team cohesion and can lead to long-term and permanent efficiency declines. Investing in prevention and mitigation strategies isn&rsquo;t just a feel-good exercise – it&rsquo;s a necessary business expense of the same token as continuously investing into technical debt reduction is. The return on investment in terms of increased productivity, faster time-to-market, and improved team retention can be substantial.</p>
<p><strong>People Side (L&amp;D, HR, product?, etc)</strong></p>
<p>From where I am sitting your value proposition is not being received in the way I think you intend it. Speaking for myself as a software engineer: I am convinced by fewer, shorter and less painful meetings and subsequently more engineering time. You should focus on virtues like that if you aim for an enthusiastic “<em>hell yeah, I’ll do whatever you say</em>” from the likes of me. To put it bluntly: Right now you are often perceived as overhead by us. Additional things we have to do that detract from the things we want to do. This is a framing problem. This is a communication problem. I think you are also not convincing business as it stands. Alas the preventive measures I spoke about are rather elusive. Given the business risks they mitigate, they should be absolutely everywhere. TL;DR: Plz change your pitch.</p>
<h2 id="outro">Outro</h2>
<p>Wow. You made it. What a long post. Thanks for reading! I’d be curious to hear about your experience – whether you are a fellow code monger, or one of the brave souls that tries to help us heathens. <a href="https://www.linkedin.com/pulse/expert-deadlock-dilemma-ulrich-kautz-taste/">Comment or DM me on LinkedIn</a>.</p>
]]></content:encoded></item><item><title>The Rubber Duck That Talked Back</title><link>https://ulrichkautz.com/posts/2024-01-01_the-rubber-duck-that-talked-back/</link><pubDate>Mon, 01 Jan 2024 00:00:00 +0000</pubDate><guid>https://ulrichkautz.com/posts/2024-01-01_the-rubber-duck-that-talked-back/</guid><category>philosophy</category><category>machine-learning</category><category>artificial-intelligence</category><category>tools</category><description>How Conversational AI Assistant Systems are revolutionizing knowledge worker professions around the globe by becoming actually useful for individuals.</description><content:encoded><![CDATA[<p>In software engineering there is a practice that is called “rubberducking”. Or more precisely: rubber duck debugging. <a href="https://en.wikipedia.org/wiki/Rubber_duck_debugging">Look it up</a>, it is real. The expression comes from a hugely transformative book, called <em><a href="https://www.goodreads.com/en/book/show/4099">The Pragmatic Programmer</a></em>, that was written at the end of the last millennium. Rubberducking is a very simple technique that has been profoundly useful to sufficiently many people so that it stuck around. It goes like that: <em>When you have to reason through an intricate problem, then explaining it to a rubber duck that sits on top of your monitor, will help you to figure it out.</em> That’s about it. In its original form, rubberducking was specifically about finding hard-to-spot bugs in a large amount of lines of source code – but you can use it for any kind of problem. It also does not need a yellow rubber duck sitting on a monitor. You can use any toy or other inanimate object that you prefer. It will work. It will work brilliantly.</p>
<h2 id="why-does-it-work">Why does it work?</h2>
<p>Well, for a couple of reasons. First, by speaking your thoughts out loud you are forced to transform them from your inner thinking into externalized structures like words, phrases, or even full sentences. <strong>You are thinking aloud</strong>. Doing so inadvertently surfaces all the silent assumptions and subconscious conclusions you made – and the gaps therein. You will easily recognize those gaps, for they are hard to put into words. Once those gaps are known you can of course close them by attaining the missing knowledge. This in turn will increase your comprehension of the topic. In short: the rubber duck helped.</p>
<p>Another reason is that through speaking aloud you hear your words back. Sounds trivial. And it is, but it is also powerful. <strong>It sounded better in my head</strong> is a <a href="https://www.urbandictionary.com/define.php?term=That%20Sounded%20Better%20In%20My%20Head">common saying</a> for good reason. Alas I can personally attest that most of the things that sound great in my head somehow become incoherent noise once they leave my mouth on a gust of air. I am sure you have observed this with yourself and others as well. It is a rather common thing. A human thing. Hence, the rubber duck helps again (not only the speaker, but also the audience) by being the silent recipient of those bumbling first attempts to formulate a thought.</p>
<h2 id="when-doesnt-it-work">When doesn&rsquo;t it work?</h2>
<p>The rubber duck is very helpful, but it is no magic bullet. While it assists with applying reason to find a solution, it still requires you to do the legwork – so to speak – of gathering all the arguments and acquiring all the information that underpin them. In a word: research.</p>
<p>Research is the process of expanding your knowledge. There are endless possible ways to approach that. My own “standard algorithm” – that I apply when writing <a href="https://ulrichkautz.com/posts/2023-04-13_interruptions-the-silent-high-performance-killer/">more involved blog posts</a> – starts with finding and reading popular articles that target a non-expert audience in the domain I am interested in. This usually teaches me the right words to find broader “meta-studies”: writings that summarize the learnings in a discipline. This step makes me dig into the methodologies and the language that the field uses to communicate – at least to some depth. Armed with this knowledge, I can find, read and understand deeper papers and articles. This is usually sufficient to get the answers to the questions that come up while writing.</p>
<p>If you think this sounds like a lot of effort then let me assure you that you are correct. It is.</p>
<p>In my day job my research approach is similar, although I am usually targeting solutions to specific problems and I am normally already deep into the topic that I am investigating. You are probably doing something comparable. At least if you are working as any kind of knowledge worker.</p>
<p>None of that is new. It comes with the territory of working with information. It takes a lot of time.</p>
<h2 id="enter-conversational-ai-assistant-systems">Enter: Conversational AI Assistant Systems</h2>
<p>For about a year or so, I have had help with research. I hired an assistant. Well, not quite. I started using Conversational AI Assistant Systems (CAAS) like <a href="https://chat.openai.com/">ChatGPT</a>, <a href="https://bard.google.com/">Bard</a> and <a href="https://claude.ai/">Claude</a>. A lot. Concurrently. It is impossible for me to convey how much easier my research and subsequently writing has become. It made the process at least two magnitudes less painful – maybe more. It, quite literally, got me thinking. In this case, it got me thinking: <em>why does this work so well</em>? I mean, I had the same information accessible before. Via normal web search. Googling. Why is this new interface so much better supporting my research?</p>
<p>From what I can tell there are multiple answers. Let’s start with the obvious one: CAAS are <a href="https://en.wikipedia.org/wiki/Large_language_model">large language models</a> (LLM). They are trained on <a href="https://luv-bansal.medium.com/list-of-all-open-sourced-large-language-models-llms-a9e3927e8da8">mind bogglingly huge datasets</a> and can aggregate the interconnected information into coherent answers. This is a significant improvement over googling one thing, which just gives you two more things to look for, which each give you two more things and so forth. Keeping track of all these different threads of thought <a href="https://ulrichkautz.com/zettel/mental-model/">is not easy</a>. Human error is likely. The risk of finding yourself in a deep rabbit hole is continuously mounting. Not so with <strong>CAAS, that gives you a combined result in one understandable chunk</strong>. This compares best to the meta-studies I was mentioning earlier – only they are made on-the-fly for arbitrary questions that I have.</p>
<p>Now I can get to why I started with the story about rubber ducks above: CAAS helps you massively to formulate your thoughts. It turns out that it matters not whether you speak your thoughts out loud or write them down. As long as you do so with the intention that they can be understood by someone else the same corrective effect occurs. With one slight difference: <em>This rubber duck talks back</em>! And this is not a trivial difference. At the very least your questions will be reflected back to you through the answers the LLM spits back to you: If your formulation was ambiguous you will find that so is the reply. If the answer is seemingly wrong or unfitting: chances are your question was not what you wanted to ask. In short: <strong>CAAS gives you a continuous <a href="https://ulrichkautz.com/zettel/feedback-loop/">feedback loop</a> like a conversation with a (human) expert would</strong> (and yes: you can actually have a spoken conversation instead of a typed chat, if you prefer). More so, this feedback loop is guiding you to the answer in a way that smells very familiar to another known good practice: the <a href="https://en.m.wikipedia.org/wiki/Root_cause_analysis">root cause analysis</a> (or “<a href="https://en.wikipedia.org/wiki/Twenty_questions">20 questions</a>”).</p>
<p>Lastly the questions you ask a CAAS are rarely simple singular words or short sentences. You can formulate immensely more complex and nuanced queries that you can express in multi-paragraph length. And you will. The amount of information and conditions such questions can contain is vastly greater than what you can type into a web crawler search input like Google or Bing (until they become a direct interface to a CAAS as well, of course). You can also iterate repeatedly, which allows you to keep spinning your thoughts almost frictionless. <strong>CAAS allows your thinking to flow unhindered.</strong></p>
<h2 id="all-good-then">All good, then?</h2>
<p>As with any good thing: there are caveats. For CAAS, or rather the LLMs that underpin them, you will find serious concerns enumerated everywhere so I will make this short:</p>
<ul>
<li><strong><a href="https://en.wikipedia.org/wiki/Hallucination_(artificial_intelligence)">Hallucinations</a></strong>, where produced results (answers) are entirely wrong, nonsensical, surreal, etc. Trusting results blindly can easily <a href="https://www.forbes.com/sites/mollybohannon/2023/06/08/lawyer-used-chatgpt-in-court-and-cited-fake-cases-a-judge-is-considering-sanctions/">produce harm in the real world</a>.</li>
<li><strong><a href="https://en.wikipedia.org/wiki/Algorithmic_bias">Bias</a></strong>, where generated results are skewed due to unknown (or when malicious: known) trends within the training data. Prejudices propagate unhindered and can even <a href="https://www.nature.com/articles/s41746-023-00939-z">threaten lives</a>.</li>
<li><strong>Privacy concerns and security risks</strong>, where inputs leak into the training data and become available to other users or the providers that own the systems or <a href="https://owasp.org/www-project-top-10-for-large-language-model-applications">malicious third parties</a>.</li>
<li><strong>Creativity deterrent</strong>, which results from outsourcing thinking. I, for one, have a hard time navigating without Google Maps these days. How about you?</li>
</ul>
<p>This is certainly not an exhaustive list, but it should paint a picture of the scope of the problem. My stance is simple: <em>Use with care</em>. You can harm yourself (or others) with any tool. CAAS is just that: a very complex and very sophisticated tool. Personally, my biggest concern is the last item on the list: <em>impairing our ability to think creatively</em>. The other items are rather technical problems that will find a solution, given sufficient time and resources. But this last item has indeed the (slight) potential to cause <a href="https://en.wikipedia.org/wiki/Great_Filter">significant harm</a> in the long term.</p>
<p>However, where there are serious risks, there are also equally substantial chances and I am very excited to see what comes next.</p>
<h2 id="whats-next">What’s next?</h2>
<p>I think that CAAS will become ubiquitous, because it <em>is</em> the next generation of interface and it will enable a whole new generation of massively more powerful (and complex) tools that will make life and work easier. Here comes my wishlist:</p>
<blockquote>
<p>“In 1986, if you added up all the information being blasted at the average human being - TV, radio, reading - it amounted to 40 newspapers-worth of information every day. By 2007, they found it had risen to the equivalent of 174 newspapers per day.”
&ndash; <strong><a href="https://www.goodreads.com/en/book/show/57933306">Johann Hari, Stolen Focus, 2022</a></strong></p>
</blockquote>
<p>Living in the <a href="https://en.wikipedia.org/wiki/Information_Age">Information Age</a> is wrought with the problem of every individual being exposed to an ever <a href="https://www.martinhilbert.net/worldinfocapacity-html/">increasing bandwidth of information</a>. CAAS is the first tool that gives me hope that we will be able to mitigate or even reverse this destructive trend. Not by decreasing the amount of information that hits you, but by increasing the amount of information you can handle. Imagine a fully integrated CAAS that has access to your emails, slack messages and any other communication channels you use. And your documents. And your pictures. And everything else. Now imagine your CAAS automatically summarizes and prioritizes all communication streams for you – on the same level and with the same quality a highly trained, full-time human assistant can do today. Basically: CAAS has the potential to give you the signal while keeping away the noise. It could do even more: replying in your stead and interest to (some of the easier) communications. Or at least gathering all requested information and preparing replies or reply variants for your review. You get the gist. All of this would be possible today, however (afaik) it is not (yet) offered by any provider. I would call this a <strong>fully integrated, personal CAAS</strong>.</p>
<p>This immediately brings up another item: Trust. Currently, all CAAS are provided and maintained by private companies. You do not know what will happen to your data that you store with them. Maybe they are all great people with good morals - but who knows who buys them tomorrow? Maybe they have great intentions – but their security posture is far less comprehensive than they think and they lose all your highly private communication to some internet pirate from overseas. This is just a small excerpt of all the possible horror scenarios. Independent of this, there is also the question of data accessibility: say only your documents are with Google, but your company messaging is with Slack and your mails are hosted by a small local outfit. <a href="https://bard.google.com/">Google’s CAAS</a> will likely not be able access all of that. So to bring about this shiny future where CAAS can double as a full personal assistant there needs to be a different approach that assuages privacy concerns and is not tightly coupled with a single data-sphere. This could be solved in multiple ways. One would be to “offline CAAS”. This is entirely possible. A lot of very <a href="https://github.com/eugeneyan/open-llms">big LLMs are already available for download</a>. Big players like Apple are actively working to bring <a href="https://www.macrumors.com/2023/12/21/apple-ai-researchers-run-llms-iphones/">LLM execution to mobile devices</a>. This can be done! We need <strong>trusted, private, vendor-independent CAAS</strong>.</p>
<p>Lastly, if I can have my way, all of the above will be carried on the wings of an agreed upon <strong>CAAS standard</strong>. Right now, as a user, you need to come up with creative workarounds like the word document that my wife uses to store an &ldquo;initial conversation&rdquo; that she uses to &ldquo;seed&rdquo; the CAAS with context. This is a hack. It is a hack that works, but it is a hack nonetheless. What I want is a <em>transportable behavior profile</em> that contains all the information of how you want the CAAS to behave, what it should know and what of your data it should have access to. Maybe there are even <em>transportable discussion profiles</em>, that capture the state of a investigation, so that it can be easily continued at a later time with a different CAAS. All of that I want of course to be <em>vendor-independent</em>, so that I can utilize different CAAS providers - online or offline. In short: I want the execution (LLM) to be separate from the data (profile) and the data to be transportable.</p>
<p>Ok, that is it for now. The future stays exciting. Thanks for reading.</p>
<p><em>Disclaimer: I am not professionally involved in developing AI, ML, LLM - or anything related to that. I am writing as a user of such technologies.</em></p>
]]></content:encoded></item><item><title>Models, a story of human success</title><link>https://ulrichkautz.com/posts/2023-10-25_models-a-story-of-human-success/</link><pubDate>Wed, 25 Oct 2023 00:00:00 +0100</pubDate><guid>https://ulrichkautz.com/posts/2023-10-25_models-a-story-of-human-success/</guid><category>philosophy</category><category>tools</category><category>best practices</category><description>Models are what enable us to tackle complexiy well beyond our capabitlies. This text is a celebration of that.</description><content:encoded><![CDATA[<p>It is not what you think. I think. I am referring to the abstract concept, not the profession in the fashion industry. Models that simplify, that abstract and approximate. These are the models I am speaking of and they are awesome &ndash; truly! Why? They help us to think way beyond our ken and through that they drive all human intellectual endeavors, all technological innovation and all scientific progress ever made, since we left the trees.</p>
<p>Why, you ask, can models do that? Well, because they enable us to have meaningful discussions about complex topics. With ourselves, in our own mind, or with others. That said, those discussions may still not be easy, but we can at least have them. I know, that does not answer the question why models can do that. I’ll get to that by separating the question into two:</p>
<ol>
<li>What makes discussions about complex topics hard?</li>
<li>How do models make these discussions easier?</li>
</ol>
<p>To get to the first part we need to agree that <a href="https://en.wikipedia.org/wiki/Complexity">complexity means that there are many parts with many connections in between</a>. That means a thing or topic is simpler than another thing or topic, if it has comparatively less parts and connections than the other (I don&rsquo;t know if parts and connections count equally, I will assume it’s about the total sum). With that definition, and our current understanding of cognitive sciences, we already know that the human capacity to hold many things in our brain is limited (see <a href="https://ulrichkautz.com/zettel/working-memory-capacity/">working memory capacity</a>). That alone means: we need to find a way to whittle down the quantity of things that we cram in our head. But it gets worse from there: when discussing any topic of real complexity, there are multiple layers of perspectives, of resolution to it. We need to switch in between them as we think and argue. Again cognitive sciences quantify how poor our abilities are in that regard (see <a href="https://ulrichkautz.com/zettel/memory-decay/">memory decay</a>). While I am sure there are even more reasons, these two alone suffice to make any discussion about complex topics in detail hard or even impossible.</p>
<p>Now that we have established we simply cannot speak about the whole complexity at once: how then can models help us to still do it? Well, the answer to that follows from how we arrive at a model of a thing. We do so, in very basic terms, by removing both parts and connections, until we are left with something that still has the general shape, the general character of the original, but has a sufficiently small amount of parts and connections to fit into our finite faculties. This is the model. A simplified picture of the original, where only the broad strokes, the outlines, survive.</p>
<p>Sure, the process I described may be simple, but simple in the sense that running a marathon is simple: just put one foot in front of the other until you arrive. Simple: yes. Easy: no. To make this easy, or at least easier, we humans came up with a great strategy that begins by finding another thing that is somewhat similar to the thing we actually want to talk about. For example, explaining that good ideas are like seeds that, once planted into a person&rsquo;s mind, can take root, grow and bear fruits - and become seeds again, that this person will then carry forth and plant into another person&rsquo;s mind and so on. Most of us, even ardent city dwellers like myself, understand deep down what seeds are, how they become plants and produce more seeds, which in turn easily explains how ideas propagate and conveys what properties an idea must have to spread better.</p>
<p>These analogies are not models, but they give us a starting point, a first glimpse of what will become a model of an idea. More so: Finding a useful analogy forces us to zoom in on the quintessential properties, these aformentioned broad strokes of the thing that are the real subject which we want to discuss. In that sense analogies and models are also alike: they both serve a specific perspective on the matter, they both leave out any details that are not relevant to that and they both aim not for completeness, but for understanding.</p>
<p>The amazing <a href="https://www.ynharari.com/">Yuval Noah Hararari</a> – the author of <a href="https://www.ynharari.com/book/sapiens-2/">Sapiens</a>, <a href="https://www.ynharari.com/book/homo-deus/">Homo Deus</a> and many more world shaking books (I am a big fan, if you can’t tell) – famously said and keeps repeating that <em>the</em> <a href="https://en.wikipedia.org/wiki/Dunbar%27s_number">human superpower is to invent and believe fictional stories</a>. That this gives us the ability to collaborate on a huge scale and to build societies that are magnitudes of size beyond the scope of our <a href="https://en.wikipedia.org/wiki/Dunbar%27s_number">innate ability to create stable social relationships</a>. Something no other creature on this planet can claim. I wholeheartedly agree with that sentiment and I think that stories are the infrastructure on which another thing travels, that feeds this superpower of ours: the model, the abstract concept, that permits us to tame seemingly endless complexity, that enables us to share meaning and to teach understanding. I like to imagine that the model, the abstract thought, has pre-dated spoken language, has given rise to it. I think <em>that</em> is what makes us different, what triggered our long success story and that may enable us one day to go beyond our lone planet and seize the stars.</p>
<p>The humble model, the key to human success.</p>
<hr>
<p><strong>Limited Warranty</strong>: As a side-effect of reducing the amount of parts and connections your models will be incomplete and will not show every aspect of the thing that they are encoding. Some situations may require multiple overlapping and potentially partially conflicting models. Use wisely and with care. Beware of mathematicians: they often leave behind fully coherent models that are tangential to reality. Ask your local apothecary for alternative treatments.</p>
]]></content:encoded></item><item><title>Scaling End-to-End Responsibility with Platforms</title><link>https://ulrichkautz.com/posts/2023-05-28_scaling-end-to-end-responsibility-with-platforms/</link><pubDate>Sun, 28 May 2023 00:00:00 +0100</pubDate><guid>https://ulrichkautz.com/posts/2023-05-28_scaling-end-to-end-responsibility-with-platforms/</guid><category>platforming</category><category>paltform</category><category>devops</category><category>ybiryi</category><description>The end-to-end responsibility model, and it&amp;rsquo;s smaller sibling YBIRYI, have revolutionized how IT operations are shaped. However, these models fail at scale due to the increased complexity of infrastructure. This leads to increased cognitive strain on individuals and overwhelms them&amp;hellip; unless you utilize platform engineering to standardize and simplify the tech stack down to manageable size again. Read here here what that means and what metrics predict when platforms are required.</description><content:encoded><![CDATA[<p>In my <a href="https://ulrichkautz.com/posts/2023-05-14_platform-engineering_development-at-scale/">previous article</a> I wrote about the benefits of platforms and how platform engineering and DevOps fit together. In that context I thought about end-to-end responsibility. The thing is: it doesn&rsquo;t work at scale. It just gets way too complicated! Well, that is not the whole truth. You can make it work, even in the largest of structures. Here is how:</p>
<h2 id="what-is-end-to-end-responsibility">What is End-to-End Responsibility?</h2>
<p>Ok, let&rsquo;s pause for a moment. Get a coffee or a tea (or whatever beverage you prefer) and settle in for I am going to tell a story.</p>
<p>The story is about two amazing teams. One team is great at developing software. They take the most intricate and complicated requirement and solve them by creating easy to understand and beautiful to behold applications. What they produce is free of annoying bugs and unexpected behaviors. They pride themselves in testing and benchmarking all functionality rigorously.</p>
<p>The other team is brilliant in operating all kinds of software. They know the underlying operating systems and infrastructure services by heart. They have seen hundreds if not thousands of custom applications and have years and years of experience running about everything you can imagine in production.</p>
<p>Both teams should work splendidly together, no? One writes a marvelous application, the other operates it flawlessly. Everyone is happy ever after. Right? <em>Wrong</em>!</p>
<p>What actually happens, and this is a true story, is this: the synthetic load that was used to test and benchmark the application fails to match actual production characteristics, hence the life performance of the application is abysmal. It also has a host of external network dependencies that make it behave erratic as the external service uptime and responsiveness are highly volatile. The application further suffers from memory overflows that result in out-of-memory kills and the garbage collection leads to random freezes. None of which was visible during development or testing, as they only occur in high load situations after sufficient time.</p>
<p>Worse: The operations team fails to provide actionable details about the issues to the developers. Their extensive metrics that measure their infrastructure add only confusion and noise, but do not help to narrow down on the root causes of the application issue. It takes operations hours to roll out new versions and it&rsquo;s rarely clear from which release the logs that are provided to the developers are generated from. The staging and production environments differ from each other, so that code changes that work in one fail in another.</p>
<p>In short: it is a huge mess. This is not a happy place.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/01_not-a-happy-place.webp" alt="Not A Happy Place"></p>
<p>To put a name to the problem that arises: silofication. Knowledge is constrained to the borders of specific departments. Processes end at those very boundaries and do not interconnect. Basically: communication pathways are broken down. As a result traversing those boundaries (like handing over code from development to operations) suffers from a huge bottleneck at best and raging storm of excrement at worst.</p>
<p>It is 2006. Enter Werner Vogel, freshly minted CTO of an ambitious internet bookseller named Amazon. He utters one phrase that shakes up a whole industry and that still echoes nearly twenty years later: <em>You build it, you run it (YBIYRI).</em> As insignificant as that may sound, YBIYRI shaped modern tech organizations as deeply as the advent of cloud computing. The meaning of YBIYRI is pretty straightforward: as the team that builds a piece of software you are also responsible for operating and maintaining it. That&rsquo;s it. However, as simple as that idea is, as large are the consequences. The responsibility of running your own application causes a significant shift in perspective: reliability, security, scalability – all of these things have immediately different priorities assigned, because they directly affect you as the developer that created the code. Not only that: as the author of the application, you have deep insight into any possible arising issues as anyone else could have. Communication pathways are not only re-established but also shortened to zero length, because the people that dig into the code and dig into the operating system log files are the very same!</p>
<p>There is just one little problem: you have a team of excellent software developers that have little experience with operating anything in production. What do you do? Easily: merge the operations team and the software developer team. Have one team that has all the knowledge required to both develop and run the software. Have them both share knowledge and grow together into a new team that operates under a new paradigm. And with a last <em>Puff</em> the earlier mentioned silos are gone. YBYRI. You may also have an inkling what those teams that were staffed by developers and operational engineers were called later on – but this is another story. For now let’s just call such teams <em>owners</em>, as in: teams that own products and that are responsible for them. These owners are very interested in making the deployment of their software very easy. They want to have sensible insight into their application behavior at runtime. They want to be able to roll back changes fast and with ease. The good news is, they can do all of that by being staffed with engineers that focus on operations. Sure, in reality it took a bit more than just merging teams. There is a whole organizational mindset that had to be shifted and I believe the model truly gained significant adoption only after programmable infrastructures became more widespread.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/02_end-to-end-responsible-team.webp" alt="End-to-end responsible teams"></p>
<p>So what is end-to-end responsibility then? I think you could call it YBYRI+ or something like that. While YBYRI proposes development and running of the software is done by the same people under end-to-end responsibility teams go farther in “both” directions: what happens before development and what happens after the software runs in production. On the development side in addition to building the software end-to-end responsibility also requires the team to gather all requirements and then design / architect both the software and the infrastructure. On the other “end” owners also take care of support and gather user feedback. So YBIYRI is a subset of end-to-end responsibility. However, your mileage may vary and I have seen YBIYRI setups that were indistinguishable from what I described here. I have no doubt there are end-to-end responsibility implementations that are more limited (and implementations that are more extensive) than what I describe.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/03_ybyri-vs-end-to-end.webp" alt="YBIYRI vs end-to-end responsibility"></p>
<p>In a now very old <a href="https://hanselminutes.com/339/continuous-delivery-with-jez-humble-and-martin-fowler">podcast with Martin Fowler and Jez Humble</a> I heard a sentence that stuck with me: <strong>the job of developers is to take business ideas and turn them into measurable business outcomes</strong>. To me, a team that starts with such a business idea and makes it happen truly implements end-to-end responsibility.</p>
<h2 id="why-does-end-to-end-responsibility-fail-at-scale">Why does End-to-End Responsibility fail at Scale?</h2>
<p>When you apply the above strategy of creating owner teams that are skilled in developing, running and maintaining the software, then everything will work splendidly – at the start. However, if you are growing, you will eventually run into a wall. That wall manifests itself by massively slowed down development, reliability problems in production, very short retention of employees – and a whole host of other problems that are all bad. Some of these problems may even look very familiar to you, like those you had before you switched to the end-to-end responsibility model.</p>
<p>Why is that?</p>
<p>First I need to clarify one thing: what does <em>at scale</em> mean? I think it is intuitively clear that <em>at scale</em> refers to large systems as opposed to small systems. However, what makes one system large compared to another? Amount of people working on it? Kilowatt hours consumed? Compute resources available? Sure, all of that, to some extent. However, what it comes down to is ultimately one thing: a large system is more <em>complex</em> than a small system. At scale it is complexity that becomes a problem for end-to-end responsibility.</p>
<p>Think of complexity in two dimensions:</p>
<ol>
<li><em>Depth</em>, as in: a single application becomes more complicated through adding functionality. More functionality means more components and more interconnections between components. More knots and bolts = more complex.</li>
<li><em>Breadth</em>, as in: a large quantity of simple, but different applications form a complicated tech stack. Adding more applications that have different architectures, that use different components or use components differently all adds more complexity to whole. Relationships in between applications add further complexity proportional to the amount.</li>
</ol>
<p>You can also think of <em>Depth</em> as the <em>Team-Level perspective</em>: the complexity each member of the team has to engage with when working on their application / service. Likewise <em>Breadth</em> can be thought of as the <em>Organization-Level perspective</em>: the complexity that results from the amount of different tech stack of the different applications / services that the whole organization owns.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/04_complexity-depth-and-breadth.webp" alt="Complexity Depth and Breadth"></p>
<p>With that out of the way, what does <em>end-to-end responsibility at scale</em> mean then? It refers to the challenge your owner teams are facing when they have to handle either a large amount of applications or very complicated applications – or usually both. This challenge relates to the complexity they have to deal with. The total complexity that owners are grappling with results from the earlier mentioned Depth and the Breadths. Think of it like an “area of complexity”, that is the product of multiplying Depths and Breadth. As long as that area is big, it doesn’t matter whether it comes from a wide Breadths or a deep Depths (or both). With scale complexity grows. With rising complexity the challenge grows.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/05_area-of-complexity.webp" alt="Area of complexity"></p>
<p>So what exactly is the problem with high complexity for end-to-end responsibility at scale? What it comes down to is <a href="https://ulrichkautz.com/zettel/cognitive-load/">cognitive load</a>. Complexity is a measure that describes how many parts and how many connections between those parts exist in a system. More parts with more connections means more complex. When you think of a system that you see in the real world (or the virtual world) then your mind creates a <a href="https://ulrichkautz.com/zettel/mental-model/">mental model</a> of that system in your head. This mental model allows you then to reason about the system: “here we can add this feature we talked about” or “this is likely the cause of the issue we are seeing”.</p>
<p>Let’s make this more practical. Imagine you are the current engineer on-call of a team that owns an application. Alarms go off, some metrics turn red, you have to find out what went wrong and then fix it. Let&rsquo;s say your application uses five different infrastructure components. Each of them could have failed and caused the issue. With such a small amount and you easily understand how they interact and relate to each other. It takes you only a few minutes and a couple of log lines to narrow down the issue, identify the faulty component and perform a fix. Nicely done! Now, how do you reckon the story would have played out if there would have been fifty different infrastructure components involved? What about five hundred? What about magnitudes more? I think you can see the problem. The more moving parts are involved, the harder it gets to make sense of them all. We humans are simply <a href="https://ulrichkautz.com/zettel/working-memory-capacity/">limited</a> in that regard. An end-to-end responsible team must be able to model their whole product, including all related processes and components that they own. In summary that means: <strong>end-to-end responsible teams are staffed with humans that can get overwhelmed by exceeding complexity, at which point any thought of responsibility goes right out of the window</strong>.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/06_overwhelming-complexity.webp" alt="Overwhelming complexity"></p>
<p>Look at it also from the organizational perspective: Imagine you have two teams that all are end-to-end responsible for their applications. They all take this very seriously and have designed ideally fitting tech stacks for their individual needs. As both team’s applications are different and both teams are solely responsible for the tech stack architecture, both tech stacks are different as well. Over time your organization grows. You now have fifty teams, with fifty different tech stacks. Oh wait no! That was last year. Now it’s a thousand teams and a thousand tech stacks. How easy is it for moving applications in between teams, given that they were designed and thought of individually? How easy is it to move people in between teams, given that they don&rsquo;t know much about each other&rsquo;s setup? And especially: Who can even begin to make sense of the combined tech stack of all your applications? How can you track security issues across that mess? How can you possibly start to think about efficient resource usage? There are no happy answers to these questions. If the complexity of the whole organization is not fathomable anymore, even at a high level, then it becomes impossible to direct it. Without direction your organization is little more than a headless chicken that runs in circles until it dies. That means: <strong>too many end-to-end responsible teams that are not aligned add more trouble than they add value</strong>.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/07_unaligned-teams.webp" alt="Unaligned teams"></p>
<p>All of the above are the problems that result from end-to-end responsibility adhering teams at scale. Well, the problems arise if your approach is naive and if you apply the model almost blindly on a team level. Of course: you should not.</p>
<h2 id="how-does-end-to-end-responsibility-work-at-scale">How does End-to-End Responsibility work at Scale?</h2>
<p>If exploding complexity is at the heart of the problem of scaling end-to-end responsibility then surely the solution is to reduce it? Right! Easily said. How do you do that exactly?</p>
<p>Consider again the team perspective. Above I argued that complexity results from the amount of moving parts that individual products (applications) are made of. More parts make equals more complex. With that the solution seems trivial: less parts make it less complex? Alright, I buy that for the moment. Let’s say your goal is <em>simplification</em>.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/08_reduce-components.webp" alt="Reduce components"></p>
<p>We also need to look again at the organizational standpoint. Complexity here emerges from the sheer amount of different architectures. Following again the obvious pathway: reduce the amount of architectures. Your goal is <em>standardization</em>.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/09_standardize-components.webp" alt="Standardize components"></p>
<p>So what you are looking for is something that helps you to standardize your tech stack throughout the organization while simplifying the components that owners engage with. A tall order, for sure, but don’t fret there is an answer. You may have guessed it by now: <em>platform engineering</em>.</p>
<p>Right, that may need some more elaboration. There is two parts to that:</p>
<ol>
<li>How does platform engineering standardize and simplify your tech stack?</li>
<li>How can end-to-end responsible teams work upon platforms?</li>
</ol>
<p>The first part is easy to explain. Let’s start with the obvious: Platform engineers build platforms. Now, what are platforms? Platforms are systems that reduce the complexity of underlying systems. I wrote a whole article about that, please <a href="https://ulrichkautz.com/posts/2023-05-14_platform-engineering_development-at-scale/">find it here</a>. In summary: Using many (infrastructure) components directly means that you need to engage with the <em>interface</em> of each individual component. Each component adds some amount of complexity. The sum of the complexity of all the components is then the complexity that is surfaced to you, that you have to understand and handle in order to manage the components. A platform hides away the individual components and their complexity. It instead exposes a much smaller interface to you. Meaning you need to understand way less in order to manage the same resources. This is only possible at by giving up fine-grained control over those resources. This is a good thing, because it frees your resources for doing things that generate value instead. Another consequence is of course that with less choice comes less variety. Standardization. In essence, platforms refine the vast amount of complicated components into a small amount of simple components. By that, <strong>platforms are the foundation that both simplifies and standardizes your tech stack</strong>.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/10-standardize-and-reduce.webp" alt="Standardized and reduced components"></p>
<p>Now to the second part: how end-to-end responsible teams can work with platforms. Let’s have a look at a practical example in which your owner teams work directly with cloud infrastructure resources. Let&rsquo;s say they are using AWS and some <a href="https://ulrichkautz.com/posts/2021-02-21_why-i-like-aws-cdk/">CDK flavor</a> to manage their infrastructure as code. Providers like AWS have a huge range of products by now. Many of those build upon other products they have. For example, you could buy compute resources in the form of virtual servers and then install and maintain a container orchestrator like Kubernetes on it. Or you could directly buy a managed Kubernetes from AWS. Or you could buy a managed orchestration that hides away how it is implemented. That means: if you work directly with a cloud provider like AWS, then you are already building upon a platform. Actually upon multiple platforms that just pretend to be a single one (don’t get me started). The only difference between an AWS provided platform (building cloud infrastructure) and an in-house platform (building on cloud infrastructure) is that providers like AWS have to generalize their solutions to fit a large market, whereas in-house has the opportunity to optimize only for local use-cases. Hence the question of whether end-to-end responsibility adhering teams can work with platforms is entirely moot: they already do! Their responsibility is with the infrastructure components they own. The granularity of those components can differ (EC2 server vs high level orchestration abstraction), but that does not change anything about the end-to-end responsibility model. The more interesting question is whether an optimized and limited platform is better than a generalized and vast one. The answer is a resounding <em>YES</em>! Why? <strong>Using your <em>own</em> platform means that the components are optimized for your use-case</strong>. That means they are simpler. That means they much better decrease complexity than generalized components from a public provider.</p>
<p>However, building and running a platform is not for free. Hence one last question needs to be answered:</p>
<h2 id="when-does-end-to-end-responsibility-require-a-platform-to-work">When does End-to-End responsibility require a Platform to work?</h2>
<p>There are a couple of clear signals that tell you that you really, really need to reduce the complexity people are dealing with in order for them to take on the responsibility for their product. I outlined them with <em>the wall</em> that I described earlier (slowed down development, reliability problems, low employee retention, etc). However, if you are at that point, then you are already failing. If you don’t act, things will get worse – until they stop entirely of course. That makes it almost an easy decision. The more interesting question is how you can predict when you will need a platform way before that happens. If you are able to do that then you can formulate a sound strategy and follow it so you will never even start hemorrhaging employees, face customer backlash due to unreliable services or have to explain to investors why development stalled to a halt.</p>
<p>As I argued throughout this article: the decision of when a platform is required relates strongly to the complexity that individuals within end-to-end responsible teams are facing. The hard part is to get a clear measure of this complexity, so that you can gauge the current state or even begin to make predictions about the future development. To my knowledge there is no one magic metric that will give you a definite, actionable answer. However, from my observations of the years, I can give you at least a couple of proxy metrics that serve as early indicators. Which of them are best applicable depends strongly on the context of your particular situation. In general I would never rely on just one of them.</p>
<p>As end-to-end responsible teams own their infrastructure components, an increased complexity translates into more time that needs to be invested to manage them. Setting up monitoring for more components with more intricate relations can quickly become exponentially harder. Rolling-out changes into systems with more moving parts can add magnitudes of stress and failure potential. As a result, <strong><em>Deployment Frequency</em> will decrease with increased infrastructure complexity</strong>, because each individual deployment is harder and more time consuming. And also because individuals will increasingly eschew to go through the hassle and the perils of roll-out.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/11-graph-deployment-frequency.webp" alt="Graph: deployment frequency"></p>
<p>Not only that, but <strong><em>Lead Time</em> for features to go from ideation to production will increase with increased infrastructure complexity</strong>, for the very same reasons of more time consuming deployments and more time invested into managing the infrastructure.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/12-graph-lead-time.webp" alt="Graph: lead time"></p>
<p>When it takes longer for any change to hit production, then it will take you also longer to roll-out fixes in incident scenarios. That means the <strong><em>Mean Time to Recovery (MTTR)</em> will increase with increased infrastructure complexity</strong>. This one is a doozy, because, unless you are really seeing significant increases in a short time, it will sneak up on you. One or two required recoveries within a few months&rsquo; time rarely ring the alarm bells loud enough.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/13-graph-mean-time-to-recovery.webp" alt="Graph: mean time to recovery"></p>
<p>Recovery is, of course, following incidents that have already happened. Before it gets to that point you should see alarms that do not result in incidents either because they are caught early enough to counter them, or because they subside on their own. Hence the metrics that you should watch like a hawk is the <strong><em>Amount of Oncall Alarms</em> that will increase with increased infrastructure complexity</strong>, because more complicated systems are easier to break, easier to misunderstand and harder to fix even if understood.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/14-graph-oncall-alarms.webp" alt="Graph: oncall alarms"></p>
<p>Underlying this alarm increase is, more often than not, human error, caused by cognitive overload that stems from the inability to model the whole complex system in your mind. Without that big picture it is rather easy to make decisions that do not account for the interplay of all components. A proxy for that is the relation between incidents and roll-out of changes, which is captured in the <strong><em>Change Failure Rate</em> that will increase with increased infrastructure complexity</strong>.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/15-graph-change-failure-rate.webp" alt="Graph: change failure rate"></p>
<p>If you are able to track with some precision where the work of your teams is spent, then you will of course see that <strong><em>Time Spend On Infrastructure Management</em> increases with increased infrastructure complexity</strong>. While some seasonal, temporary cost increase is fine and even continuous expenditure to keep technical debt at bay is expected, at a certain point it becomes counter to the idea of end-to-end responsible teams. After all, they were founded to speed up the time from ideation to production and increase productivity, not keep more people busy with infrastructure concerns.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/16-graph-time-spent-on-infra.webp" alt="Graph: time spent on infra"></p>
<p>Last, but certainly not least, is the obvious: ask the very people that are working in the teams. You need, of course, a comparable metric that you track over a long enough time. Adding questions about time spent in infrastructure in your regular pulse surveys is a good start. Generally <strong><em>Employee Satisfaction and Engagement</em> will decrease with increased infrastructure complexity</strong>, assuming that the majority of end-to-end responsible teams are focused on delivering business value and get frustrated if they are instead bogged down in battling with infrastructure.</p>
<p><img src="https://ulrichkautz.com/img/posts/end-to-end-responsibility/17-graph-employee-satisfaction-and-engagement.webp" alt="Graph: time spent on infra"></p>
<p>Again, you need more than a single metric measured in a single team to get a reliable signal. However, in conjunction with each other – of at least a subset of the metrics – you will certainly see a clear trend emerging way before you are suffering serious consequences. Keep your eyes open and be ready to simplify and standardize the complexity that development is facing. Platforms are an incredibly helpful tool here, if they are widely and wisely deployed.</p>
<h2 id="conclusion">Conclusion</h2>
<p>The end-to-end responsibility model works at any scale – given that you provide the right environment for it to flourish. That means you have to perpetually rein in the complexity that members of end-to-end responsible teams have to engage with. You also need to make sure that no chaos ensues from a too large variety of solutions that result from too many teams creating optimal solutions for only their own domain. Platforms are a great way to address both concerns.</p>
<p>Platforms are also not the end of the story. Well, at least a single platform is not. As you keep growing, so does the complexity of your infrastructure. Over time you will see higher level patterns emerge: platforms upon platforms upon platforms. It’s a greater journey ahead!</p>
<p>As for my next article: I am pleasantly surprised to find myself deeply immersed and thoroughly enjoying an adjacent topic to platform engineering: developer experience. My interest, coming from the platform engineering side, has narrowed down over the years and I became more and more involved in the very intersection of development and platforming. When the rubber hits the road, so to speak. I am now actively exploring topics such as knowledge sharing and general developer tooling, which are other equally interesting problems that you face when engaging in development at scale. Stay tuned, more to come!</p>
]]></content:encoded></item><item><title>Platform Engineering: Development at Scale</title><link>https://ulrichkautz.com/posts/2023-05-14_platform-engineering_development-at-scale/</link><pubDate>Sun, 14 May 2023 00:00:00 +0100</pubDate><guid>https://ulrichkautz.com/posts/2023-05-14_platform-engineering_development-at-scale/</guid><category>platforming</category><category>devops</category><category>software</category><category>development</category><description>Platform Engineering is a trending topic. Good! Developer platforms are the native response to growing organizations that have tech at their heart. It is almost the only practice that allows software engineering at scale.</description><content:encoded><![CDATA[<p>The topic of Platform Engineering has become all the rage in the last year. Good! It is about time. Software development is at the heart of an ever growing number of organizations and platforms are a necessary response to anchor best practices and standardize resource use – which are increasingly hard problems proportional to the complexity that comes with organization and software growth.</p>
<p>Most of the discussions around the topic over the last year and a half have passed by me. I do have a good excuse, for I had and have the privilege to be part of one of the largest infrastructures of the planet that received all my attention instead. Needless to say that I learned a tremendous amount about platforming at scale. This of course changed my perspective since I <a href="https://ulrichkautz.com/posts/2021-03-11_value-of-platforming-engineering/">last wrote about this topic in March ’21</a>.</p>
<p>I recently picked up the ball again and started reading a lot of newly published articles about what people think that platforms are and what platform engineering does. I found that some are arguing that platform engineering is an <a href="https://www.pluralsight.com/blog/teams/platform-engineering-devops-difference-explained">evolution</a> <a href="https://www.profisea.com/devops-news/platform-engineering-devops-evolved/">of</a> <a href="https://devops.com/the-evolution-of-devops-developer-productivity-and-platforms/">DevOps</a>. Even that <a href="https://open.spotify.com/episode/0wU4vwL5YPNU6o8IPiOUAw">platform engineering is the practice while DevOps is the philosophy</a>. That made me a bit twitchy, because building platforms has been at the heart of what I was doing for the last two decades or so – the term DevOps has certainly not been around for that long.</p>
<p>On the other hand, I certainly support pitching the platform model to organizations that already bought into the DevOps paradigm. I can also see where those arguments are coming from and how DevOps and platform engineering intersect. However, I think conflating both terms in such a way limits your thinking unnecessarily. To me <strong>platform engineering is foremost a practice to enable software development at scale</strong>. By that, platforms are a tool. How and why you wield that tool is a question that can have many answers. One answer could be that it fits into your DevOps organization, but that is not the only one – you can gain value out of platform engineering in any case.</p>
<h2 id="what-are-platforms">What are Platforms?</h2>
<p>I want you to think about the platform concept without any preconceived notions about DevOps or anything else for a moment. Consider the following entirely non-technical example from even before the interwebs was around: a travel agency of the olden days. Back when phones had cables and dials – and no displays. You know, shortly after the dinosaurs roamed on earth. It was pretty hard to go on vacation anywhere outside of your own backyard. The same as today you needed to book a flight, find and book a place to stay at the destination, ensure access to local transport and plan activities outside of loafing by the pool. Now imagine doing that pre-internet in a country whose language you do not speak. Imagine even just calling all the airlines directly and asking them for flight times and prices. Yes, a nightmare. Travel agencies are an excellent, if mostly obsolete, example for a user-facing platform. The complexity of booking all the components and thinking of all the things, and then orchestrating everything so that it fits perfectly together, was reduced to a simple conversation with an agent and maybe looking through a couple of catalogs. This is an example of a platform. Not a platform created by platform engineers, but a platform nonetheless. The example shows the first fundamental property of a platform: <strong>a platform reduces the complexity of underlying systems</strong>. Basically: It makes complicated things simple to use.</p>
<p><img src="https://ulrichkautz.com/img/posts/platforms-at-scale/platform-gears.webp" alt="Platform reduces the complexity of underlying systems"></p>
<p>You probably noted that I threw in the term <em>systems.</em> I will also soon use the related term <em>service</em>. Let me quickly explain what these two terms mean in this context: A service is “a single, self-contained unit of functionality”. A service <em>implements</em> the functionality itself. In the above example <em>flying</em> is a service that airlines provide. A system is a collection of components that could be platforms, services or systems themselves. The travel agency above would be a system and a platform. Each airline would be a system as well.</p>
<p>With that out of the way consider another fundamental platform aspect that the above example describes: the travel agency cherry picks functionality (services / systems) from the airlines, the hotels, the local transport and so forth, and offers this choice-set to their own client. More so, the agency re-packages that functionality in a way that their client may not even be aware who provides it while combining it (ideally) seamlessly with other functionality from other providers. This is done with the goal to make booking a vacation an easily accessible experience. In a sentence, <strong>a platform is a higher level system that refines one or more lower level systems</strong>. You can think of a hierarchical structure that has <em>higher</em> and <em>lower</em> levels. The platform is at the top and the other systems are below it. When interacting with the platform you only see the top layer (i.e. the travel agency) and the lower layers are hidden.</p>
<p><img src="https://ulrichkautz.com/img/posts/platforms-at-scale/platform-ice-berg.webp" alt="Platform is a higher level system that refines one or more lower level systems"></p>
<p>By cherry picking functionality another fundamental aspect of platforms reveals itself: <strong>a platform serves a limited set of specialized use-cases</strong>. It has to, because if you could do the same things with a platform as with all the systems beneath it, then the platform would be exactly as complicated as the combined underlying systems and thereby entirely redundant.</p>
<p>In the context of the above example: A travel agency would not be the place to, say, book cargo flights to transport goods from A to B – even though the airlines that the travel agency uses also offer cargo flights.</p>
<p>Lastly – and this is not always fully possible, but always highly recommended: <strong>A platform abstracts the implementation behind an isolated, well-defined interface</strong>. That means that changes of the underlying systems have (ideally) no impact on the exposed interface of the platform itself. Again, using the example of the travel agency, this would mean that if from tomorrow on you would not anymore travel by airplane, but by zeppelin or dragon or something, then the way you book your travel would still be the same: you talk to an agent, tell them where you want to go at what dates and they take it from there. There are some asterisks to that, because it is not always possible to fully isolate the platform interface from underlying systems (i.e. zeppelins and dragons don’t offer 1st class anymore, so you cannot book that anymore). More on that in the benefits topic below.</p>
<p><img src="https://ulrichkautz.com/img/posts/platforms-at-scale/platform-interface.webp" alt="Platform abstracts the implementation behind an isolated, well-defined interface"></p>
<p>As I wrote earlier, platforms can exist entirely outside of the DevOs paradigm. At least the above properties do not require it.</p>
<h2 id="what-is-platform-engineering">What is Platform Engineering?</h2>
<p>While the platform model transcends industries, the term <em>platform engineering</em> is – as far as I know – exclusively used in the wild world of software engineering. So the above example of a pre-internet platform is valid, but it is not descriptive of what platform engineers do. To understand what that is, you have to further narrow down the realm of software platforms: any <em>user-facing</em> platform – from social media to online travel agencies – is usually out of scope. From what I have observed while working on platforms in various sized companies – including an early Platform-as-a-Service (PaaS) – is that platform engineers almost exclusively create <em>developer-facing</em> platforms. To put it in a single sentence: <strong>platform engineers design, build and maintain platforms that facilitate development and delivery of software</strong>.</p>
<p><img src="https://ulrichkautz.com/img/posts/platforms-at-scale/developer-platform.webp" alt="Platform engineers design, build and maintain platforms that facilitate development and delivery of software"></p>
<p>This by no means implies that there is a single type of platform that every platform engineer builds. You’ll find mobile app development platforms, web application development platforms, machine learning data platforms, and much more. Platforms come in all shapes and sizes and each is designed to make a different use-case for the specific context of an organization easier to tackle. In larger structures you will see tiers of platforms forming: higher level platforms that build on lower level platforms. In this context <em>developer-facing</em> can equally refer to the developer of the end-product as well as any other (refinement) step in the value chain – like developers of a higher level platform. Platforms are also almost never static: they change and evolve along with the changing and evolving needs of the business.</p>
<p>So what does that mean in practical terms? As a platform engineer you need to take on two perspectives. First, of course, the perspective of the developer. To do that you need to understand how the developers in your organization work. There may be even multiple contexts, like the day-to-day of the mobile app developer, who faces rather different problems than the web application developer. It is up to you to find out whether there are common denominators. In general you need to have a lot of conversations and ask a lot of questions – and listen! What tools do they use? What languages do they write in? Do they have a local development environment? How do they currently deploy? How long does that take? How are automated tests triggered? What business goals shape all of that? And so forth. Gathering answers to all these questions gives you the <em>internal context</em> of what is being done and why. <strong>A good platform engineer understands the needs, wants and pains of the developers.</strong> This is the first half of the equation.</p>
<p>The other half is being informed about what is going on in the field. Be assured that you are not the first person facing, well, almost any problem. Make use of the wisdom of the domain. Learn how others have tackled the same issue – and have proven their approach right by thousands and thousands of hours of hardening in production. Read about strategies and patterns that aid you in framing the problems and delivering working solutions. This is the <em>external context</em>. <strong>A good platform engineer must</strong> <strong>have knowledge of current industry best practices.</strong> Combining both contexts together is what makes the job interesting.</p>
<p>A warning here: Platforms are a great tool to introduce and propagate standards. However, if this is misused to steamroll and force-feed even the greatest practices without involving the very developers that are affected, then chances are adoption will wither and the rollout will fail. Been there, done that. Big mistake. Tact, common sense and pragmatism are more useful values for platform engineers than adherence to the book, idealism or zeal. The most successful platform rollouts I’ve seen were not the technically most sophisticated or the most optimized solutions, but those that had the best feedback loops to check in with the users (the developers) and make their transition the easiest. <strong>Platform engineers must advocate for the interests of developers</strong>. Without their support and buy-in, all effort is for nil. Besides, it is so much easier to iterate the platform later towards better practices, than attempting to start out in the perfect setup while fighting with the developer&rsquo;s expectations.</p>
<p><img src="https://ulrichkautz.com/img/posts/platforms-at-scale/platform-engineer-talk.webp" alt="Platform engineers must advocate for the interests of developers"></p>
<p>The other perspective that platform engineers need to take on is the infrastructure side. As with any production IT system efficiency of resource use and resilience towards outages are key concerns. Since platforms are multi-tenant systems by design, isolation of tenants – for both security and accounting reasons – needs to have strong guarantees. Scalability and monitoring go hand-in-hand and are essential for any modern platform. All of this needs to be optimized, which often leads to hard coupling of the implementation with the underlying lower (infrastructure) systems. And here is where it becomes hard: you have to balance optimization with the flexibility to exchange whole underlying systems. As a platform engineer you usually work upon cloud infrastructure – whether directly or indirectly. The cloud is constantly improving and changing as well, so you need to be able to adopt new technologies and trends quickly. After all, what does it help if you squeeze out 5% more performance at the same cost, whereas migrating to the next generation gives you 50% more performance for the same price? <strong>As a platform engineer you need to be informed of the latest developments in the underlying infrastructure</strong>, so that you can leverage opportunities when they come along. Then again, this balance shifts towards optimization when your infrastructure costs make up most of your total expenses. This is certainly the case for very large scale operations, where even shaving of fractions of a percent in resource consumption can translate to millions in annual opex.</p>
<p><img src="https://ulrichkautz.com/img/posts/platforms-at-scale/platform-engineer-tinker.webp" alt="Platform engineer you need to be informed of the latest developments in the underlying infrastructure"></p>
<p>By the way: While the role of platform engineering is a new one, the same activity and context was around way before that: I am thinking of web hosting. The value of web hosting was to provide the ability to serve a website that was built by web developers, with very little effort. At least much less effort than is required to maintain your own hosting infrastructure. The people that built those web hosting platforms were not called platform engineers, but they pioneered the field (or maybe I am just nostalgic).</p>
<h2 id="what-is-the-value-of-platforms">What is the Value of Platforms?</h2>
<p>Again, I ask you to suspend your any assumptions about DevOps and platform engineering and just think about what value platforms independently provide.</p>
<p>I’ve already tried to convey what I consider to be the primary value: <strong>Platforms</strong> <strong>simplify access to complex functionality</strong>. However, that is far from all. Platforms rarely only simplify a single system, they more often merge and simplify multiple systems into a new system: the platform. That often involves additional layers of authentication that control access to the involved resources. By that <strong>platforms combine related systems</strong> into a new system with a single interface. This combined interface is simpler than the sum of the individual interfaces and reduces the complexity on the consumer side. In specific cases – especially relating to authentication and authorization – another value arises: <strong>platforms enable compliance</strong>, which may otherwise not be possible or very hard.</p>
<p>Another huge value is that use of the underlying complex systems is aligned. Consider cloud infrastructures like AWS or GCP: You have a multitude of different solution pathways, a huge variety of possible architectures and designs. You can run your code in lambda functions, container runtimes, virtual machines or on bare metal – just to consider a single use-case. <strong>A platform standardizes use of resources</strong>. This strongly reduces complexity for those that maintain the lower levels and often allows you to decrease cost by buying in bulk. It also helps to keep technical debt at bay by reducing the surface (=variety) for entropy to wreak havoc.</p>
<p>Related to that is that <strong>platforms provide a consistent, well-defined interface</strong>. The technological landscape is continuously changing and improving. Having the ability to replace basically all the systems that underlie the platform, while keeping the surface interface the same is invaluable. Why? Because all of the things that use the platform do not need to change! So think thrice before committing the cardinal sin of not <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">separating concerns</a> and exposing implementation details. You will pay for it down the line – promise.</p>
<p>If you forget anything else and just remember one thing, then make it this: <strong>Platforms allow developers to focus on developing</strong>, by reducing the amount of things they need to know to do that.</p>
<h2 id="what-are-the-risks-of-platforms">What are the risks of platforms?</h2>
<p>When talking about platforms, it is easy to dote on the benefits and forget about the drawbacks, because there are some and it is important to recognize that not every situation calls for a platform. For example, when a software is in the early stages and is still heavily changing at high frequency, then defining a platform that serves the fast evolving needs of developing the software is not feasible. Similarly, small organizations with only a few developers are better off using pre-existing platforms than investing into building their own. Also if the software stack is too simple or too diverse, a platform does not add any value.</p>
<p>If the circumstances are right in principle, there is still a fundamental risk in creating a platform: over-optimization / over-fitting. Any platform naturally imposes constraints by being fitted for a set of specific use-cases. This takes away choices which allows developers to focus on the primary task of development (instead of peripheral tasks like deploying). The risk here is that you optimized the platform in the wrong direction. As a result you may have made the wrong things easier and the wrong things harder in the process. Consider Google Glasses that came out in 2013: the device was purely optimized for the tech side of an augmented reality experience, without considering privacy concerns and social tolerance, resulting in a major failure. By the same token a development / release platform that optimizes heavily for release, while making check-in code changes harder is a certain recipe for disaster. To avoid this pitfall, it’s important to integrate feedback loops and roll out iterations gradually rather than going for a <a href="https://ulrichkautz.com/zettel/big-bang-release/">big-bang</a> approach.</p>
<p>Another risk of over-optimization is locking yourself too deeply into a solution that stalls innovation. Yesterday’s great platform can quickly become today’s obstacle. Again, to avoid this the design of your platform should consider changes to the developer-facing interface from the start. Providing a versioned interface makes it possible to describe migration from one version to another. Detaching the interface design itself from the implementation makes it possible to replace the whole implementation.</p>
<h2 id="platform-engineering--devops">Platform Engineering ❤️ DevOps?</h2>
<p>All of the above is about platforms and platform engineering. Now let&rsquo;s have a look at how all of that intersects with DevOps.</p>
<p>First, given that DevOps is perpetually lacking a commonly agreed upon definition, let me clarify that I mean the practices that arise from the three principles that are outlined in the <a href="https://www.goodreads.com/en/book/show/26083308">DevOps Handbook by Jez Humble et al</a>:</p>
<ol>
<li><strong>Optimized Flow</strong>, throughout all processes by identifying the path of flow, where the bottlenecks are and where work-in-progress accumulates.</li>
<li><strong>Feedback Loops</strong>, that act automatically on the signals of pervasive telemetry that is deployed throughout the system.</li>
<li><strong>Continual Learning</strong>, that seeks to perpetually improve the processes and thereby the organization.</li>
</ol>
<p>I certainly don&rsquo;t want to get into a discussion of whether this is the best definition of DevOps or not. I acknowledge that there are other often cited principals. Thus far, I haven&rsquo;t encountered a sensible principle that I could not derive from the ones mentioned above. Take, for instance, <em>end-to-end responsibility</em>, which, in my view, exemplifies a practice that ingrates all three principles at team-level. It requires (and at the same time fosters) a DevOps mindset of the whole organization where such teams are embedded in.</p>
<p>Anyhow, if you follow the first principle and identify how work flows through your organization across product- and process boundaries, then it is only opportune to draw circles around common and especially effortful areas and put them behind platforms. The same goes for ubiquitous work that repeats in many or all steps (again, authentication / authorization is a great example). All of that would fit neatly behind the transparent interface of a platform. Maybe your setup is even simple enough and you can draw a single circle around it and have one super platform that reduces the efforts of the whole process.</p>
<p>The second principle of feedback is equally supported through platforms, because for scalability and reliability reasons, you will have pervasive telemetry already deeply integrated into your platform. Exposing those metrics to each platform user as a signal for their feedback loops (of their specific products) is likely little effort.</p>
<p>Continual Learning may seem a bit harder to argue at first glance, because platforms hide complexity and thereby reduce the opportunities for learning for individuals. However, DevOps is about organizations and Platforms certainly supplement organizational learning: they provide a high level signal for a whole category of processes (i.e. all products that use it in their processes) and they provide a focal point to improve that whole category as well. To an extent platforms are also an implementation of organizational knowledge.</p>
<p>So, yes! Platform engineering fits nicely into DevOps adhering organization – even if it developed independently.</p>
<h2 id="conclusion">Conclusion</h2>
<p>I hope I could make clear that platform engineering is not tightly coupled with DevOps – even if it is a great partner to it. Again, I fully endorse the pitch – and I also want to prevent an unnecessary boxing-in of thinking. To me the platform model has a huge range of applications. I can only see this range growing further in the future – especially since increased tech complexity in all kinds of organizations has become an unstoppable trend.</p>
<p>I am writing another article about the end-to-end responsibility practice I mentioned above. My interest here is how platforms enable that practice even at the largest scale. More in my next article.</p>
]]></content:encoded></item><item><title>Interruptions: The Silent, High-Performance Killer</title><link>https://ulrichkautz.com/posts/2023-04-13_interruptions-the-silent-high-performance-killer/</link><pubDate>Mon, 20 Mar 2023 00:00:00 +0000</pubDate><guid>https://ulrichkautz.com/posts/2023-04-13_interruptions-the-silent-high-performance-killer/</guid><category>attention</category><category>focus</category><category>interruption</category><category>productivity</category><description>Everybody these days wants high performers. Everybody wants to be a high performer. Everybody wants to hire high performers. High performance is commonly defined as: better, faster and more efficient than others. What this definition doesn&amp;rsquo;t tell you, of course, is how to do that. I can&amp;rsquo;t tell you that either, but I can tell you that high quality outcomes and high productivity share a common arch enemy: interruptions</description><content:encoded><![CDATA[<p>Everybody these days wants high performers. Everybody wants to be a high performer. Everybody wants to hire high performers. High-performance is commonly defined as: <em><a href="https://www.merriam-webster.com/dictionary/high%20performance">better, faster and more efficient than others</a></em>. What this definition doesn&rsquo;t tell you, of course, is how to do that. I can&rsquo;t tell you that either, but I can tell you that high quality outcomes and high productivity share a common arch enemy: interruptions. As Aristotle put it so eloquently more than twenty-four centuries ago: <em>The greatest threat to the state is not faction, but distraction.</em></p>
<p>In my <a href="https://ulrichkautz.com/posts/2023-03-20_the-cost-of-interruption/">last article</a>, I shared my introduction into the field of interruption research. This time I want to share some fundamental “why” questions that have been bothering me ever since. I like to understand cause and effect. Given that our understanding of all things relating to the human brain are limited by our current knowledge and insight, there is a lot of room for interpretation. So I will interpret.</p>
<p>Let’s start with the most fundamental “why”-question in that context:</p>
<h2 id="why-are-interruptions-disruptive">Why Are Interruptions Disruptive?</h2>
<p>Imagine yourself in front of a whiteboard. You are thinking about an intricate problem. Maybe a complicated engineering task. Or your upcoming wedding. Or your next tax return. Over the last hour you painstakingly added bits and pieces of information to the board with arrows of relations drawn in between them. A bigger picture finally starts to emerge. You know the solution will present itself anytime now. Then someone in a hat steps up next to you. He smiles politely – and erases half your board in the blink of an eye. Before you can even voice your outrage he quickly fills the empty half with entirely different information that hardly makes any sense to you. While he does that, he even smears the remaining picture that you have so scrupulously drawn over the last hour. Finally, to add insult to injury, he tips his hat and vanishes.</p>
<p><img src="https://ulrichkautz.com/img/posts/interruptions-killer/whiteboard-hat-guy.webp" alt="Whiteboard and Guy in Hat"></p>
<p>Rude! How could he? The whole hour is lost! Why would he do that? Well, he would not. Normally. Social norms would likely prevent anyone, save for borderline sociopaths, from such shenanigans. Hat or no. By the way: the whiteboard metaphor is not from me. I heard it first from the brilliant <a href="https://en.wikipedia.org/wiki/Gloria_Mark">Professor Gloria Mark</a> and it stuck with me. Anyway, what happens when you remove the clearly visible whiteboard from the storyline?</p>
<p>Consider a scenario in which you are equally concentrated on solving whatever you are focused on. Only instead of offloading your contemplations externally, on a whiteboard, you are keeping everything in your head. This is not entirely unheard of. You are doing this all the time. Everybody is. This inner, figurative whiteboard is called a <strong><a href="https://en.wikipedia.org/wiki/Mental_model">Mental Model</a></strong>. When I first read about this, as a software engineer I immediately thought of <em>program state</em>. Whatever the name, it is a representation that your brain creates of the outer world, specifically of the thing that you are focused on. This representation is constantly updated by all the new information and relations you think of and learn about.</p>
<p><img src="https://ulrichkautz.com/img/posts/interruptions-killer/memory-model.webp" alt="Memory Model"></p>
<p>Now, what happens then when you are interrupted? <a href="https://www.researchgate.net/publication/222580634_Memory_for_goals_An_activation-based_model">Altman &amp; Trafton 2002</a> described the <strong>Memory for Goals Model</strong> that is widely cited and referred to when pondering this particular question. The short answer is: pretty much the same will occur in your head as did to the whiteboard when the guy in the hat came along – <em>vandalism</em>. Whether your mental model is just maimed or wholly destroyed depends on many of the factors described in my <a href="https://ulrichkautz.com/posts/2023-03-20_the-cost-of-interruption/">previous article</a>. However, two factors peek out: similarity and complexity (<a href="https://www.researchgate.net/publication228358708_Dealing_with_Interruptions_can_be_Complex_but_does_Interruption_Complexity_Matter_A_Mental_Resources_Approach_to_Quantifying_Disruptions">Cades, Werner, Trafton, Monk 2008</a>). The closer the new, interrupting thing is to what you were already doing, the better it will fit into the existing Mental Model in your head. Ideally, it is not different at all. That means you can keep using the same model – give or take a few pieces. The further away the new thing is from the old, the more different the Mental Model that presents itself. If the two things are entirely different, then the two models will have no overlap at all.</p>
<p>As an example, let me tell you a short story that you may have experienced as well: For the last twenty minutes you have investigated your fridge and your pantry and a lip-smacking meal is starting to form in your mind from what you found. While you are not hangry yet, you are certainly on the verge of really hungry and the prospect of the nice, home-cooked meal makes your mouth water. Then your partner comes in, bright eyed and bushy tailed about a new idea! In the beginning, you listen with half a mind, while still thinking about what goes into the dinner you were about to start making. As your partner’s telling goes on, and is indeed very interesting, your thoughts move ever away from culinary delights and you get drawn into the story. An undetermined time later, you find yourself sitting at the kitchen table with a growling stomach - and order in Szechuan food. While that is delicious, that was not your plan. Your own Mental Model of the dinner has evaporated without you being consciously aware of that. It was replaced by the tale your partner spun – or more precisely: it was replaced by the entirely different, non-overlapping Mental Model that this tale induced in your mind. Also, you can figure yourself what my usual role is in that recurring epic.</p>
<p><img src="https://ulrichkautz.com/img/posts/interruptions-killer/working-memory-capacity.webp" alt="Working Memory Capacity"></p>
<p>From that anecdote I want you to take one thing: Complexity of the interrupting thing matters! Complexity refers here to how many details and relations it contains. The more complex the thing is, the more space it will occupy in your head. The whiteboard metaphor fits yet again: more details and relations drawn require more space. At some point, the whiteboard would simply fill up and the only way to add more would be by first erasing something else. And this is pretty much what happens with the Mental Model as well: If the new, interrupting thing requires more space than there is available then it will push out the old. Your old model collapses – partially or fully. The amount of available space, which is referred to as <strong>Working Memory Capacity</strong>, varies from person to person (<a href="https://www.researchgate.net/publication/303952807_Working_Memory_Capacity_and_Errors_Following_Interruptions">Forgoughi, Malihi, Boehm-Davis 2016</a>) and there is good indication that you can train to grow it (<a href="https://www.apa.org/monitor/sep05/workout">Dingfelder 2005</a>). However, it always will be finite. It also always will be smaller than truly complex problems, hence you will still need to simplify them, so they fit in your head, so you can think about them.</p>
<p>But wait, it gets worse: Even if your old Mental Model survives the interruption mostly intact, it will still suffer from what the scientific literature calls <strong>Memory Decay</strong>. It is as bad as you imagine: the things in your memory rot away over time – unless you keep working with them to keep them fresh in your mind. Here the whiteboard metaphor fails us. The best I can offer up is the image of a news or social media feed: new things are continuously added to the top, ever pushing down the old contents towards the bottom until they leave your field of vision and are gone into the digital aether – unless they are being upvoted by steady interest and stick around. The same happens to the old Mental Model, that you are temporarily not using when working on the new thing. The above mentioned Memory for Goals Model predicts exactly that and many studies found strong evidence that this holds true, <a href="https://www.researchgate.net/publication/23684294_The_Effect_of_Interruption_Duration_and_Demand_on_Resuming_Suspended_Goals">Monk, Trafton 2008</a> makes an especially convincing case.</p>
<p><img src="https://ulrichkautz.com/img/posts/interruptions-killer/memory-decay.webp" alt="Memory Decay"></p>
<p>Once more back to the question: <strong>Why are interruptions disrupting?</strong> The answer is: because interruptions screw with any existing Mental Model by either overtaking its space or moving away from it temporarily, which leads to its decay.</p>
<p>Unlike in the story with the hat guy messing with your whiteboard, the damage done is not obvious to the outside – nor is it always to the inside – but it is there nonetheless.</p>
<p>Now the question becomes: what are the consequences of that damage? Well, there are a few…</p>
<h2 id="why-do-interruptions-hurt-productivity">Why Do Interruptions Hurt Productivity?</h2>
<p>Let’s go back to the drawing board. Excuse me, the metaphorical whiteboard, I mean. Consider for a moment the effort it takes to create that big picture. When you do it the first time the process of writing and drawing on the board costs time, but compared to the big effort of gathering all that information and relations together the drawing effort is small. When the guy in the hat brazenly erased the board and left, and you later had to redraw half of it from scratch, you would likely have been faster than the first time around. You would recall some of the things that were on the board and you would remember the source of where you found others. This means retracing your steps would be quicker than initially finding the pathways. Either way, it still would take you time and effort.</p>
<p><img src="https://ulrichkautz.com/img/posts/interruptions-killer/resumption-lag.webp" alt="Resumption Lag"></p>
<p>The exact same goes for a mental picture. In research papers you find this most often as <strong>Resumption Lag</strong>, rarer as <strong>Reimmersion Time</strong> (<a href="https://www.researchgate.net/publication/317989659_Impact_of_task_switching_and_work_interruptions_on_software_development_processes">Tregubov, Boehm, Rodchenko 2017</a>) or earlier <strong>Reorientation Time</strong> (<a href="https://www.researchgate.net/publication/250131496_Do_Interrupted_Users_Work_Faster_or_Slower_The_Micro-analysis_of_Computerized_Text_Editing_Task">Burmistrov, Leonova 2001</a>). It is the time measured <em>after</em> the interruption has finished and <em>before</em> the interrupted task is resumed again. Meaning: it is the time it takes to <em>rebuild the Mental Model</em>.</p>
<p>You have certainly experienced Resumption Lag many times over. Think back to a time when you were intensely focused on a complicated task and the world around you faded into a distant murmur. Then, suddenly, something comes cutting into your thought process like a knife, ripping you out of your concentration with the same abruptness as a cold bucket of ice water poured on your head would have. Being so deeply immersed into the topic means that you did build an elaborate and, in all likelihood, fragile model in your mind. That model is now shattered into pieces. That certainly hurts in the moment and it will hurt again when whatever disrupted you has been dealt with and you have to pick up all those pieces and rebuild the picture in your mind to continue. This costs time. This is error prone (I&rsquo;ll get back to that in a bit). It is certainly not efficient.</p>
<p>To make it painfully clear, here is some math: consider a 60 minute task. It is interrupted three times. Each time it takes 5 minutes to think back into it. That means the total task time is: 60 + (3 * 5) = 75 minutes. In productivity terms: instead of one task per hour this is only 60 / 75 = 0.8 tasks per hour. A 20% reduction in outcome performance.</p>
<p><img src="https://ulrichkautz.com/img/posts/interruptions-killer/resumption-lag-math.webp" alt="Resumption Lag (Math)"></p>
<p>With that it becomes pretty obvious <strong>how interruptions hurt productivity</strong>: less is getting done in the same time.</p>
<p>How bad is it? <a href="https://www.researchgate.net/publication/46158289_Errors_and_electronic_prescribing_A_controlled_laboratory_study_to_examine_task_complexity_and_interruption_effects">Magrabi, Li, Day, Coiera 2010</a> showed it depends on the complexity of the interrupted task. Interruptions resulting from switching in between tasks from more than one project can eat up <strong>20% of your time</strong>, according to <a href="https://www.researchgate.net/publication/317989659_Impact_of_task_switching_and_work_interruptions_on_software_development_processes">Tregubov, Boehm, Rodchenko 2017</a>. That is a full day out of a five day workweek! <a href="https://www.researchgate.net/publication/225250082_Conversations_Amidst_Computing_A_Study_of_Interruptions_and_Recovery_of_Task_Activity">Iqbal, Horvitz 2007</a> found in their study at Microsoft that an interruption by half an hour of conversation on average leads to a subsequent resumption time of another <strong>half hour to resume the task</strong> (compared to a five minute conversation that results in an average of fifteen minutes of resumption time).</p>
<h2 id="why-do-interruptions-increase-error-rate">Why Do Interruptions Increase Error Rate?</h2>
<p>I’ve already hinted towards the first reason: the Resumption Lag is caused by you having to rebuild the Mental Model from an either decayed or otherwise partially destructed state. As it turns out: nobody is perfect. That means you will make mistakes in the process of rebuilding the model. Once a mistake is made, it will have ripple effects that of course will impact the outcome: it is faulty, flawed, buggy, corrupted. Take your pick. <a href="https://www.researchgate.net/publication/234085167_Momentary_Interruptions_Can_Derail_the_Train_of_Thought">Altman, Trafton 2008</a> showed an up to three times higher error rate resulting from short (five second) interruptions.</p>
<p><img src="https://ulrichkautz.com/img/posts/interruptions-killer/rebuild-error.webp" alt="Rebuild Error"></p>
<p>There is more.</p>
<p>Using again the handy whiteboard metaphor as it can explain another observed mechanism that research has described: If you have ever cleaned up a physical whiteboard after using it you certainly have found out that erasing your drawings does not work perfectly. It&rsquo;s a bit of a pain, to be frank. Working with others in shared office spaces I have often come into a room where someone halfheartedly cleaned the board, leaving behind ghosts and fragments of their musings. I may have been guilty of that as well. Anyway, those remnants of previous artworks can make it hard for you or someone else to separate them from the added layers of your masterwork – and then misunderstandings become mistakes.</p>
<p>Those leftover bits of information are not only an annoyance when you work with physical whiteboards, but they also occur in your Mental Model. The same principle applies: residual fragments from a previous task carry over to the current task and mess with the current Mental Model. Hence the scientific term: <strong>Attention Residue</strong>, the leaking of information from one Mental Model into another.</p>
<p><img src="https://ulrichkautz.com/img/posts/interruptions-killer/attention-residue.webp" alt="Attention Residue"></p>
<p>When talking about any outcome of work, you must consider both tasks: The one that was interrupted <em>and</em> the interrupting task. The Attention Residue affects the latter one: the interrupting task, that barges in. Again, you certainly have experienced that as well. Remember the last time you were working on something interesting, something that moved you ahead in your goals, which was interrupted by a time-sensitive chore that had to be done now. This chore may come from the hat guy, or maybe you kept pushing off a bothersome thing until it became urgent. Either way, you will not be fully motivated to do that interfering task and you will keep thinking about the intriguing thing you were forced to suspend. Recall the last time that happened to you. That is a good example of Attention Residue messing with you. Or at least messing with the outcome of your work.</p>
<p>Leroy (<a href="https://www.researchgate.net/publication/46489122_Why_is_it_so_Hard_to_do_My_Work_The_Challenge_of_Attention_Residue_when_Switching_Between_Work_Tasks">2009</a>, <a href="https://www.researchgate.net/publication/309875392_The_effect_of_regulatory_focus_on_attention_residue_and_performance_during_interruptions">2016</a>), who contributed fundamental research in this area, describes two human needs that underpin the effects of Attention Residue:</p>
<ol>
<li><em>Need for Completion</em>: As long as you do not meet the goal you set out to, you are distracted. This drive also motivates you to finish.</li>
<li><em>Need for Cognitive Closure</em>: Even after meeting your goal, you may still fuss about your solution, thinking of alternatives, which distracts you from the next thing.</li>
</ol>
<p>As long as both of the above needs are not satisfied you will suffer from Attention Residue.</p>
<p>There is also a related effect that has not been named (or I don’t know the name). Think back to the last time you have heard or seen something extreme, as in: something that evokes strong emotions in you. Rather than using yet another horrifying news story, think of something positive: the birth of a niece or nephew or a wedding proposal a close friend of yours received or somesuch. This kind of news persists with you for days. Once embedded, it overlays other things you are thinking about. Within the whiteboard metaphor, I would think of someone writing with a red permanent marker on it. Whatever is then modeled on that whiteboard, there is always that glaring red spot that cannot be erased.</p>
<p><strong>So to the question of why interruptions increase the error rate, the answer is twofold:</strong> First there is Attention Residue, that makes you think of not-the-thing-you-are-doing, which makes you prone to make mistakes. Then there is plain imperfection of human memory that causes mistakes when rebuilding a previously interrupted Mental Model. Together they can wreak havoc on the quality of the outcome.</p>
<p>The amount of error rate increase depends on the context and the task. <a href="https://www.researchgate.net/publication/43345757_Association_of_interruptions_with_increased_risk_and_severity_of_medication_administration_errors">Westbrook, Woods, Rob, Dunsmuir, Day 2010</a> showed the <strong>error rate increases by 12%</strong> in medication administration when interrupted - while the <strong>severity of the mistakes doubled</strong>. In the study <a href="https://www.researchgate.net/publication/221518227_If_not_now_when_The_effects_of_interruption_at_different_moments_within_task_execution">Adamczyk, Bailey 2004</a> it was found that <strong>error rates would increase by 25%</strong> and according to <a href="https://www.researchgate.net/publication/222649582_On_the_need_for_attention-aware_systems_Measuring_effects_of_interruption_on_task_performance_error_rate_and_affective_state">Bailey, Konstan 2006</a> the <strong>error rate can double</strong> as well, depending on the task.</p>
<h2 id="how-can-you-stop-interruptions-from-diminishing-performance">How Can You Stop Interruptions From Diminishing Performance?</h2>
<p>The good news is that there are actually a lot of things that can be done. In my opinion the single most important thing is: <strong>Create awareness</strong>. First for yourself, so that your confidence does not suffer from low performance caused by high interruption amounts. It’s them, not you. Then within the groups you are part of: Make it widely known and clear to anyone that <strong>interruptions are a significant factor in productivity, error rate, quality</strong> – and anything else pertaining to performance – and finding ways to reduce them is in the best interest of all.</p>
<p>With that in mind, I also want to acknowledge that there are as many situations as there are people around. Please consider my answers and suggestions below with an appended <em>if your circumstances allow</em>.</p>
<p>Lastly, some of the measures I will propose to you only make sense in the context of systems / groups / organizations. I will mark them clearly. Everything else can be done by every individual or group alike.</p>
<p>Let’s get to it then:</p>
<h3 id="decrease-amount-frequency-and-duration-of-interruptions">Decrease Amount, Frequency And Duration Of Interruptions</h3>
<p>I know, if it were that easy, we would not be here talking about the topic. Still, there is a vast gulf between being unhappy about “feeling disrupted all the time” and having an informed discussion about the topic, with the knowledge of the underlying mechanisms and resulting consequences (see the article above).</p>
<p>One way to look at this is from the direction of project management and work organization. In other words: how can you make work (time) better predictable? How can you decrease the amount of unplanned work that comes in? Many books have been written on this topic. The <a href="https://en.m.wikipedia.org/wiki/The_Mythical_Man-Month">Mythical Man-Month</a> and <a href="https://www.goodreads.com/en/book/show/2335148">Making Things Happen</a> come to mind as great starting points.</p>
<p><strong>Everyone:</strong></p>
<ul>
<li><em>Track Interruptions</em>: You need to know the extent of the problem. Sometimes it is just perception. More often it is not. It is always quantifiable. How frequent do interruptions occur? How long do they last? At what times are they most likely to happen? The power of raw numbers that showcase the true scale of the issue cannot be overstated. This alone can turn the tide.</li>
<li><em>Be Mindful Of Other People’s Time</em>: “Can I interrupt you for a minute” sounds polite, but it is already an interruption, if maybe a lesser one than the actual item. Do not take anyone&rsquo;s availability for granted. Model the behavior you want to see. Use asynchronous means (like messengers, mail, ..) with sufficient time ahead to arrange for time. Reduce the amount of interruptions you are causing.</li>
<li><em>Set Boundaries On Your Own Time</em>: Do not feel bad about blocking time for concentration. Make that public by sharing your calendar, hanging a sign outside of your door or whatever helps to communicate to others when you do not want to be disturbed. Do not forget to clarify also when you are best available and make an effort to consider other people’s time requirements. Reduce the amount of interruptions and funnel their occurrence (as much as you can) in time that you control.</li>
</ul>
<p><strong>Organizations:</strong></p>
<ul>
<li><em>Culture Of Respect</em>: Values do not spring into being by happenstance. They are forged intentionally. Valuing each other&rsquo;s time is a deliberate decision that requires purposeful design of processes. Take the time to think that through and come up with ideas / guidelines that make people aware. Provide tooling that makes it easy to arrange shared time. This will reduce the amount and frequency of interruptions for everyone.</li>
<li><em>Culture Of Focus</em>: Find long stretches of time and designate them for concentration. Like meeting-free days each week. Communicate in batches, not continuously. Make it public what you do and encourage everyone to join in. Provide guidance and tooling to make that easy. This reduces the probability of interruptions, by making (many of) them planned events. It also decreases the average impact of interruptions, because most of them should happen outside of dedicated concentration time.</li>
</ul>
<p><img src="https://ulrichkautz.com/img/posts/interruptions-killer/decrease-interruptions.webp" alt="Decrease Interruptions"></p>
<h3 id="decrease-task-complexity">Decrease Task Complexity</h3>
<p>The next best thing to reducing interruptions is making your work more resilient to them. The major factor in that is Mental Model complexity, which directly derives from task complexity. In that context, think of complexity as fragility. The more complex your tasks are, the easier they are disturbed, the more costly is the damage to them and the higher the price to rebuild them after the interruption passes (Resumption Lag). You need to have a good understanding of the nature of the tasks that you are engaged in. Combining this with the insight into interruptions, as proposed in the previous topic, will allow you to make good decisions.</p>
<p><strong>Everyone:</strong></p>
<ul>
<li><em><a href="https://en.wikipedia.org/wiki/Divide-and-conquer_algorithm#Divide_and_conquer">Divide And Conquer</a></em>: Decompose a given task into two or more similar, but simpler, subtasks. Each simpler task will require a proportional simpler Mental Model. Simpler models require less mental capacity which makes them more resilient towards interruptions by reducing their cost to rebuild.</li>
<li><em>Separate Planning And Execution</em>: The complexity of a task is often concentrated in understanding the task and formulating a solution. Still, the execution, the doing part, may take much more time. In such circumstances, assuming that interruptions are not distributed exactly equally (e.g. less random phone calls in early morning), deliberately separating the work into two phases can be extremely helpful. Complex things in the “off hours” and simple things during “prime time”. This reduces the cumulative effect interruptions have, as you steer your most fragile work out of their way.</li>
</ul>
<p><strong>Organizations:</strong></p>
<ul>
<li><em>Pre-Process, Process, Post-Process</em>: Separate a single workstream of highly complex tasks into multiple workstreams of simple tasks. Complexity at scale has known solutions since the introduction of manufacturing. With less complex tasks across the board, the impact of interruptions is dampened.</li>
</ul>
<p><img src="https://ulrichkautz.com/img/posts/interruptions-killer/divide-complexity.webp" alt="Divide Complexity"></p>
<h3 id="increase-task-similarity-or-decrease-task-switch-frequency">Increase Task Similarity Or Decrease Task Switch Frequency</h3>
<p>Regardless of whether the amount of interruptions or the task complexity can be reduced, there is another pathway to reduce the cost of interruptions: Order the tasks by the shape of their Mental Model. That means: make sure that you work on similar tasks first. This way switching between tasks has a lower price, as less changes in the Mental Model are required and more parts of the Mental Model will be continuously used, hence less decay.</p>
<p>This is a project management concern. As <a href="https://www.researchgate.net/publication/317989659_Impact_of_task_switching_and_work_interruptions_on_software_development_processes">Tregubov, Boehm, Rodchenko 2017</a> showed: you can easily lose a whole day per week just for task switching</p>
<p><strong>Everyone:</strong></p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/KISS_principle">KISS</a>: Stick with one project that you are working on. Within that aim to switch between tasks that translate into closely related Mental Models. Move on to tasks that are at least somewhat similar. This will minimize Resumption Lag - a lot.</li>
<li><em>Prepare Then Do:</em> Make it your first task to group all of your tasks on your list by similarity. Only then pick up the first actual task from that list. Abraham Lincoln famously said, “<em>Give me six hours to chop down a tree and I will spend the first four sharpening the axe.</em>” This is a variant of that. This will reduce the amount of Mental Model changes in between tasks solidly.</li>
<li><em>Pre-Dedicate Your Time</em>: This is a different way to look at it. Instead of choosing from the list of already existing tasks, make sure that your list is filled only with similar tasks in the first place. For example: Dedicate days to communication, dedicate other days to engineering (or whatever you do) and yet other days to administrative toil. By doing that you limit the range of “task varieties” that make it on your list. Again: Less Resumption Lag for more similar tasks.</li>
</ul>
<p><strong>Organizations:</strong></p>
<ul>
<li><em>Constrain Number Of Workstreams:</em> This is about distribution of work. Make it a project management / planning goal to optimize for similarity of work. Only comparable work goes into the same workstream. Then constrain the amount of such workstreams that individuals or teams work on during each time frame (e.g. sprint, quarter, etc). Maximizing for similarity minimizes Resumption Lag.</li>
</ul>
<p><img src="https://ulrichkautz.com/img/posts/interruptions-killer/increase-similarity.webp" alt="Increase Similarity"></p>
<h3 id="increase-work-experience">Increase (Work) Experience</h3>
<p>You create Mental Models for everything that you do: Working a specific task or driving your car or cooking spaghetti bolognese. Having done something, especially repeatedly, allows you to recall a stored Mental Model for that thing at a much lower cost than creating a new one from scratch. I like to think of this as “higher level (mental) modules”, that I can load and combine. From working with complex systems for half of my life I don’t think this is even limited to repetitive work: having various Mental Models about a certain domain will help with lateral thinking in that space because each model adds perspective.</p>
<p>Mind though: experience <em>does not help to mitigate increasing error rate</em> (<a href="https://www.researchgate.net/publication/43345757_Association_of_interruptions_with_increased_risk_and_severity_of_medication_administration_errors">Westbrook, Woods, Rob, Dunsmuir, Day 2010</a>), it only decreases the impact on productivity by decreasing the Resumption Lag.</p>
<p><strong>Everyone:</strong></p>
<ul>
<li><em>Extend Your Toolbox:</em> Learn more! Try more! Tinker! Each success gives you a new pathway. Each failure tells you where not to go. All of that will add to the bigger picture, allowing you to draw conclusions and make educated guesses even in areas that you have not experienced directly. It also increases your speed of building Mental Models: many components or even whole subsystems are already known to you. That also means less surface for interruptions to act on, and if they do, it will cost you less time to resume.</li>
</ul>
<p><strong>Organizations:</strong></p>
<ul>
<li><em>Culture Of Learning:</em> Tenure comes with deepened and broadened domain knowledge - if you foster that, by providing incentives to learn. Time to grow and self-develop should be built into the organization of work. Your goal here is to establish a self-reinforcing feedback loop of self-improvement, so that everyone will have better and more Mental Models accessible. Interruptions will lose much of their punch.</li>
<li><em>Blameless Culture:</em> Learning requires experimenting. Experimenting means taking risks and making mistakes. Likely a lot of mistakes. If that has negative consequences for the person that made the mistake – experimenting will seize. In fact it will never start in the first place under such conditions. Experience will stall at low levels and interruptions will have a major impact on the already low productivity. Don’t go there, but instead encourage experimentation. Share learnings – of failures and successes alike. Again: better and more Mental Models for the win.</li>
</ul>
<p><img src="https://ulrichkautz.com/img/posts/interruptions-killer/increase-experience.webp" alt="Increase Experience"></p>
<h3 id="heighten-pressure-focus-on-the-negative">Heighten Pressure, focus on the Negative</h3>
<p>This one I found a bit surprising. <a href="https://www.researchgate.net/publication/46489122_Why_is_it_so_Hard_to_do_My_Work_The_Challenge_of_Attention_Residue_when_Switching_Between_Work_Tasks">Leroy 2009</a> investigated the question of how time pressure relates to Attention Residue. Her research revealed that more time pressure helps you to reduce the Attention Residue. Having “all the time in the world” allows you also to overthink and keep thinking of alternative solutions way after you solved the problem. In <a href="https://www.researchgate.net/publication/309875392_The_effect_of_regulatory_focus_on_attention_residue_and_performance_during_interruptions">Leroy, Schmidt 2016</a> the question was asked whether aiming to achieve a positive outcome or attempting to prevent a negative outcome helps with moving on from previous tasks. It turns out a negative framing (“What bad thing will happen if I don’t get this done?”) works much better. I figure this relates to the evolutionarily caused <a href="https://en.wikipedia.org/wiki/Negativity_bias">Negativity Bias</a>.</p>
<p><strong>Everyone:</strong></p>
<ul>
<li><em>Religiously Timebox</em> (i.e. predesignate a fixed amount of time for) your tasks. Attention Residue comes from the inability to disconnect your thoughts from a past activity. Having a clear boundary will help you to cut the ties to previous thoughts and move on.</li>
<li><em>Start With Unfavorable Outcomes</em>: When beginning a new task, remind yourself of what you will lose if you don’t do this. This will make it easier for you to detach from the previous task with reduced Attention Residue. From my other readings I must warn you to approach this with caution. Do not overdo it (e.g. foster a negative mindset). If you do, it will cause stress. Stress will quickly overshadow any positive gains. Use with care!</li>
<li><em>Crystal Clear Definition Of Done</em>: The more ambiguity in the goal definition, the more room for you to doubt your solution. Be entirely clear about what is to be achieved and how you measure whether that is the case. Err on the side of greatest possible obviousness, if in doubt.</li>
</ul>
<p><strong>Organizations:</strong></p>
<ul>
<li><em>Foster Confidence</em>: The last thing you want is everyone questioning their sanity and their solutions. People get stuck in loops from which they cannot move on. Certainly not the most productive state. Bolster confidence by providing positive feedback on executed solutions. Make it easy to move on. Help mitigate Attention Residue.</li>
<li><em>Communicate Clearly</em>: Leave no room for misinterpretation. Don’t let anyone waste time questioning their understanding of the task, which would make it that much harder to identify success. Done must be highly obvious and it must be unambiguously clear that no alternative solutions are required or intended.</li>
</ul>
<h3 id="the-right-tooling">The right Tooling</h3>
<p>As an engineer, this is of course my go-to solution for, well, anything. <a href="https://www.researchgate.net/publication/262929168_Mitigating_errors_caused_by_interruptions_during_medication_verification_and_administration_Interventions_in_a_simulated_ambulatory_chemotherapy_setting">Pracash, Koczmara, Savage, Trip, Stewart 2013</a> found (in the medical space) that having supplemental tooling to execute a task can reduce the interruption-caused error rate by half. This means: Understand the task, then make sure you have the right tools to do it in place. Or build them, if they don’t exist.</p>
<p><strong>Everyone:</strong></p>
<ul>
<li><em>Integrate Quality Assurance</em>: Assume you are making mistakes – because you are making mistakes. You want to arrange it so that whatever you did is automatically verified. Like spell-checking when you write a text. In software engineering this means having automatically triggered software testing integrated in your continuous deployment / integration pipeline. I am sure there are comparative and highly specialized solutions in other fields.</li>
<li><em>Automate Everything</em>: Automation is usually associated with productivity. However, working mainly with reliability topics professionally I can assure you that error reduction is the silent hero here. Automating a process means that <em>you</em> are now out of the equation. Your state of mind, whether distracted or focussed, is of no relevance anymore towards the outcome of the process. This does not help you reduce a few errors here and there as much as it helps you to eliminate whole <em>classes of errors</em>. I cannot overstate how much automation plays a role in reliability concerns.</li>
</ul>
<h2 id="conclusion">Conclusion</h2>
<p>You have now created Mental Models of Mental Models in your head. You are welcome for the recursion!</p>
<p>Thanks for following along. I hope you now have a much better understanding of the underlying causes and mechanisms that make even seemingly innocuous interruptions so painful for your own performance. Maybe I even surprised you with one or two insights that will help you to take control of your own time and mental resources again. The Information Age that we are living in comes with many intricate pitfalls and masked dangers that ride on the trail of the vast amount of new opportunities. If I could ask you one thing, then it is this: <strong>spread the word</strong>! Help to build awareness. While interruptions are a problem as old as humanity itself, technology magnified the size and frequency to an unprecedented level. Dealing with this in a sane way requires cultural change – or we are at peril to lose a battle that we don’t even know we are fighting, likely because we are so distracted through the many interruptions that hinder us from thinking clearly.</p>
<p>This article will not be the end of my research journey, but merely a segue to the closely related Wild West of attention research. Stay tuned.</p>
<p><img src="https://ulrichkautz.com/img/posts/interruptions-killer/tip-my-hat.webp" alt="Tip my Hat"></p>
<p><em>A note on why I chose to present error rate and productivity as separate proxies for performance: Productivity seems to change the outcome linearly whereas error rate can have an exponential effect. By that I mean: productivity impact is predictable and within a limited range of outcome. Not so for error rate. The range of outcome is in between that of reduced productivity (added time of fixing the mistakes and doing it again) and incalculable catastrophe (consider potential crippling reputation costs or something like the failure in the <a href="https://en.wikipedia.org/wiki/Mars_Climate_Orbiter#Cause_of_failure">Mars Climate Orbiter from 1999</a>).</em></p>
<h2 id="sources">Sources</h2>
<ul>
<li>Why are attentions disruptive? Why do interruptions decrease productivity? <em>Mental Model, Memory Decay, Resumption Lag</em>
<ul>
<li><a href="https://www.researchgate.net/publication/250131496_Do_Interrupted_Users_Work_Faster_or_Slower_The_Micro-analysis_of_Computerized_Text_Editing_Task">Burmistrov, Leonova 2001</a>: Interruptions add Reorientation Time =&gt; Resumption Lag</li>
<li><a href="https://www.apa.org/monitor/sep05/workout">Dingfelder 2005</a>: What influences Working Memory Capacity and how to improve it</li>
<li><a href="https://www.researchgate.net/publication/225250082_Conversations_Amidst_Computing_A_Study_of_Interruptions_and_Recovery_of_Task_Activity">Iqbal, Horvitz 2007</a>: Length of interruption directly correlates with Resumption Time =&gt; Memory Decay
<ul>
<li>5 min conversation =&gt; avg 15 min after resuming task</li>
<li>15-30 min conversation =&gt; avg 30 min after resuming task</li>
</ul>
</li>
<li><a href="https://www.researchgate.net/publication/228358708_Dealing_with_Interruptions_can_be_Complex_but_does_Interruption_Complexity_Matter_A_Mental_Resources_Approach_to_Quantifying_Disruptions">Cades, Werner, Trafton, Monk 2008</a>: Complexity of interrupting task increases resumption lag =&gt; Complexity requires space</li>
<li><a href="https://www.researchgate.net/publication/23684294_The_Effect_of_Interruption_Duration_and_Demand_on_Resuming_Suspended_Goals">Monk, Trafton 2008</a>: Longer and more demanding interruptions increase resumption lag =&gt; Memory Decay</li>
<li><a href="https://www.researchgate.net/publication/46158289_Errors_and_electronic_prescribing_A_controlled_laboratory_study_to_examine_task_complexity_and_interruption_effects">Magrabi, Li, Day, Coiera 2010</a>: Resumption Lag strongly correlated to complexity of interrupted task =&gt; Memory Decay &amp; Rebuild complexity (com</li>
<li><a href="https://www.researchgate.net/publication/317989659_Impact_of_task_switching_and_work_interruptions_on_software_development_processes">Tregubov, Boehm, Rodchenko 2017</a>: More than one project =&gt; Switching between tasks between projects =&gt; 17% of time goes into switching (Resumption Lag)</li>
</ul>
</li>
<li>Why do interruptions increase error rate? <em>Attention Residue, Rebuilding Errors</em>
<ul>
<li><a href="https://www.researchgate.net/publication/221518227_If_not_now_when_The_effects_of_interruption_at_different_moments_within_task_execution">Adamczyk, Bailey 2004</a>: Interruption causes increased error rate (25%), increased completion time (27%) and doubles the annoyance</li>
<li><a href="https://www.researchgate.net/publication/222649582_On_the_need_for_attention-aware_systems_Measuring_effects_of_interruption_on_task_performance_error_rate_and_affective_state">Bailey, Konstan 2006</a>: Error rate doubles when interrupted during primary task</li>
<li><a href="https://www.researchgate.net/publication/234085167_Momentary_Interruptions_Can_Derail_the_Train_of_Thought">Altman, Trafton 2008</a>: Shows short interruption strongly increase error rate (5s =&gt; 3x higher, 3s =&gt; 2x higher)</li>
<li><a href="https://www.researchgate.net/publication/46489122_Why_is_it_so_Hard_to_do_My_Work_The_Challenge_of_Attention_Residue_when_Switching_Between_Work_Tasks">Leroy 2009</a>: Attention Residue is caused by focus on previous activity that interferes with current activity. Need for Completion. Need for Closure.
<ul>
<li>40+% better performance in ideal conditions (able to finish + time pressure)</li>
</ul>
</li>
<li><a href="https://www.researchgate.net/publication/43345757_Association_of_interruptions_with_increased_risk_and_severity_of_medication_administration_errors">Westbrook, Woods, Rob, Dunsmuir, Day 2010</a>: interruptions in medication administration =&gt; 12% increase when interrupted &amp; severity doubled
<ul>
<li>No mitigation through nurses experience level</li>
</ul>
</li>
<li><a href="https://www.researchgate.net/publication/269714937_Do_Interruptions_Affect_Quality_of_Work">Foroughi, Werner, Nelson, Boehm-Davis 2013:</a> Interruptions decrease outcome quality, measured in rated essays =&gt; creative work badly impacted
<ul>
<li>17% worse scores for interrupted vs not</li>
<li>11% less words</li>
</ul>
</li>
<li><a href="https://www.researchgate.net/publication/262929168_Mitigating_errors_caused_by_interruptions_during_medication_verification_and_administration_Interventions_in_a_simulated_ambulatory_chemotherapy_setting">Pracash, Koczmara, Savage, Trip, Stewart 2013</a>: Appropriate tooling can cut down error rate by half</li>
<li><a href="https://www.researchgate.net/publication/309875392_The_effect_of_regulatory_focus_on_attention_residue_and_performance_during_interruptions">Leroy, Schmidt 2016</a>: Regulatory Focus Theory =&gt; when focused on avoiding negative outcome Attention Residue lower than when focused on achieving positive outcome</li>
<li><a href="https://www.researchgate.net/publication/303952807_Working_Memory_Capacity_and_Errors_Following_Interruptions">Forgoughi, Malihi, Boehm-Davis 2016</a>: The higher Working Memory Capacity, the lower error rate following interruptions</li>
</ul>
</li>
</ul>
<hr>
<p>If you want to join a discussion, please visit the <a href="https://www.linkedin.com/pulse/interruptions-silent-high-performance-killer-ulrich-kautz">cross-published version on LinkedIn</a>.</p>
]]></content:encoded></item><item><title>The Cost of Interruptions</title><link>https://ulrichkautz.com/posts/2023-03-20_the-cost-of-interruption/</link><pubDate>Mon, 20 Mar 2023 00:00:00 +0000</pubDate><guid>https://ulrichkautz.com/posts/2023-03-20_the-cost-of-interruption/</guid><category>attention</category><category>focus</category><category>interruption</category><category>productivity</category><description>Interruptions have a price tag. They impede both productivity and well-being. Just what exactly is the cost and how do you calculate it? Good questions! Read on here.</description><content:encoded><![CDATA[<p>Did you know that a 4-5 second interruption of your work increases the amount of errors you are making <em>threefold</em>? But I am getting ahead of myself. Let me rewind.</p>
<p>I became interested in the topic of focus over the last year. It started out with attempts to organize myself better (a recurring theme in my life). This journey led me down a new rabbit hole, which I did not frequent before: the domicile of a hare called <em>focus</em>. As far as rabbits and their holes go: this is a big one. It also contains a plentitude of adjacent cavities to sink your time into. To name a few of those topics: attention, communication, conscientiousness, interruption, flow, performance, sleep - and that is cutting it short. Frankly, I don&rsquo;t know the scope yet myself.</p>
<p>In that context I recently came across a very interesting paper with the prosaic title: <em><a href="https://www.researchgate.net/publication/336837187_Pardon_the_Interruption_An_Integrative_Review_and_Future_Research_Agenda_for_Research_on_Work_Interruptions">Pardon the Interruption: An Integrative Review and Future Research Agenda for Research on Work Interruptions (Puranik, Koopman, Vough 2019)</a></em>. As the field of attention and focus research is comparatively young, there is still a lot of fundamental work to be done. This paper pertains to the <em>interruptions research</em> field and is aiming to build said fundamentals: as a meta study of about 250 other papers it proposes shared definitions and processes that pull together the sometimes vastly different approaches in the sources. This helps the reader – me – also to get a birds eye view of the field – while providing a plethora of sources to further get lost in.</p>
<p><em>Disclaimer: This blog is my own reflection and part of my process of synthesizing what I learned. It contains only my own opinions. I am not speaking for anyone else. I also may be wrong. I refer you to the (linked),original paper(s) for your own studies.</em></p>
<h2 id="what-makes-interruptions-interesting">What makes interruptions interesting?</h2>
<p>I personally don’t like them. Not a fan. The old adage of <em>know thy enemy</em> applies here: to get them under control in my life, my work, I must first understand them properly.</p>
<p>More so: In my profession you rarely work fully alone. Teams of four to twenty’ish people are the common configuration, in my experience. Not having a clear understanding of how interruptions influence your productivity or well-being is a big problem. The question of <em>how to communicate within a team</em> strongly relates to this: finding the right balance between sharing information, helping each other and having sufficient time to get concentrated work done is a tricky task. Arming myself with the data, with the latest understanding will help finding better solutions to organize teams I work with in the future.</p>
<p>Also, I find this topic oddly fascinating – I don’t really need more reason than that.</p>
<h2 id="what-are-interruptions">What are interruptions?</h2>
<p>A question you likely would not ask – because it is pretty damn clear what an interruption is: you know it when you see it. However, it turns out that it is <em>not</em> clearly defined – alas not to the extent that everybody studying the phenomenon speaks about the same thing.</p>
<p>When studying anything the question of how to gather relevant data points arises. Consider you are working on something finicky. You are deeply into it, keeping ten threads of thought in your mind (if barely) and you are close to finishing it. Then the phone rings. It’s your boss&rsquo;s boss calling. You have to pick up and suspend what you are doing. You lose your threads. That finish line you saw earlier may be lost for the day. This is, quite obviously, an interruption. Now consider a slightly different situation: Same build up, finicky task, many threads etc. Then the phone rings again. This time it’s not yours, but from the person next to you. They pick up the phone and start talking. Loudly. Laughing. Gesturing. Annoying. Your concentration is lost. The threads are gone. Another obvious interruption!</p>
<p>However, obvious to whom? Obvious to you, experiencing both of those scenarios? Sure. But not obvious to an observer, a scientist, who measures the effect of interruptions sitting somewhere behind you. Nor is it obvious to an automated system that counts the amount of phone calls, emails or chat messages that you receive to gauge the impact on your productivity. Hence some researchers defined interruption only as things that changed your behavioral performance (you visibly stopped working on a thing) where others included the suspension of your attentional focus (you kept doing a thing, but your mind was pulled away).</p>
<p>Puranik et al propose to do the latter. Their definition is: <em>Work interruptions are unexpected suspension of an ongoing task</em>. This definition intentionally does not specify that the interruptions need to be observable or that it must “happen directly to you”. Both phone cases above fit into it. The task is considered equally suspended, whether only your mind (invisibly) or also your body (visibly) stopped doing it.</p>
<p>By the way, the word <em>unexpected</em> is also important. A planned thing, like a scheduled phone call, does not count as an interruption - even if it disrupts your work. While that may also have an (negative) impact, the field of study here would be about work organization/planning, not work interruptions.</p>
<h2 id="how-do-you-measure-the-impact-of-interruptions">How do you measure the impact of interruptions?</h2>
<p>That is of course the big question. The paper makes clear that most studies do not even use the same dimensions or otherwise agree on the same measures. Hence they propose a new model, fetchingly named:</p>
<p><strong><em>Integrative Process-Based Model of Work Interruptions</em>.</strong></p>
<p>This model comprehensively describes the factors known to this field of research that play a role when speaking about the impact of interruptions. Understanding these factors is the first step to both predict the likely outcome and intentionally mold the outcome. Ath the very least you want to make informed decisions with known trade-offs.</p>
<p>The paper is so well written, that even someone new to the field can easily follow it. However, for my own purposes a complex model is not nimble enough. I need something easier to handle. What I am looking for is more shaped like a formula:</p>
<p><em>Cost of interruption = A * B + C</em></p>
<p>Something like that tells me at a glance whether a thing is relevant to the outcome or not – assuming I know what A, B and C are.</p>
<p>The model consists of a large number of details and reasons that lead to the outcome interruptions have. Puranik et al then groups these factors together under shared topics. These topics already come very close to the terms of an equation: this is what I am looking for! Well, not quite, but with a bit of tinkering it will be close enough.</p>
<p>Following I will go through the topics. Or rather: through slightly changed grouping of factors into topics that lends themselves better for my purposes. Later then, I will make each topic a term in my equation.</p>
<p>Here we go:</p>
<h3 id="t-the-task-that-is-interrupted-or-is-interrupting">(T) The Task that is interrupted or is interrupting</h3>
<p>This topic is about the thing that is interrupted: The task. Or the tasks.</p>
<p>First, there is the <em>interrupted task</em>, which was going on until now. How <strong>complex</strong> was it? As in: How much mental energy was bound up in it? How many “threads of thought” were held? How long did it take to “get into” the task in the first place? Also the <strong>timing</strong> is of importance: Did the interruption occur in between two steps of a long chain of steps? Were these steps independent or building upon each other? Or did the disruption happen in the middle of step? The <strong>stage of completion</strong> is of course relevant as well. Is the whole thing almost done, or just started? While not in the paper, hence not part of the visited studies, I would also add <strong>accessibility</strong>, as in an interesting measure: The time and effort it takes to start or restart the task would be multiplied for every interruption.</p>
<p>An <em>interrupting task</em> does not always need to be part of an interruption. Or it may depend on perspective (would you call a conversation that interrupts a task also a task?). Again, <strong>complexity</strong> plays a big role: how much mental resources does it cost to “load” that new task into working memory? Also <strong>similarity</strong> to the previous task: is that just a variant of the same, or something entirely different that requires a mental reset of sorts? Lastly, <strong>centrality</strong> to the “core work” plays a role. Like: is this something that you are normally doing, or something outside of your comfort zone?</p>
<h3 id="i-the-occurring-interruption-itself">(I) The occurring Interruption itself</h3>
<p>This topic is concerned with the actual interruption that forced itself into your attention.</p>
<p>What <strong>kind</strong> of interruption, with what kind of <strong>immediacy</strong> is it? It can be fully-asynchronous like email or semi-asynchronous like chat or optional synchronous like phone or mandatory synchronous like face to face. At what <strong>frequency</strong> does the interruption occur? Once in a blue moon? Ten times an hour? Is this an exceptional or a habitual event? How long was the <strong>duration</strong> of the interruption? 5 seconds? 5 minutes? 5 hours?</p>
<h3 id="e-the-context-or-environment-the-interruption-happens-in">(E) The Context or Environment the interruption happens in</h3>
<p>This topic is concerned with the external conditions in which the task was executed in and then the interruption occurred in. It speaks somewhat to what extent interruptions can be expected.</p>
<p>Consider the <strong>collocation</strong>: are we talking open space offices with everyone talking to everyone, or closed offices where people have to knock, or home office? Also the <strong>organizational culture</strong> plays a huge role: is it a reactive, chaotic, multitasking environment, that expects you often to switch from task to task – or is everything planned out years ahead, with no deviation from the path feasible/needed, everyone knowing exactly what to do? Then the degree of <strong>collaboration</strong> factors in: is the work mostly done alone, or does it require multiple people forming (temporary) teams and working at it together?</p>
<h3 id="m-the-mental-factors--mediators">(M) The Mental Factors / Mediators</h3>
<p>This topic is about effects that interact with your finite mental resources and your perception of positivity (or negativity).</p>
<p>If you are interested in systems theory, you may find this factor curious, because it seems to convert the whole process into a self-reinforcing feedback loop. This makes the whole system “stateful” and non-deterministic regarding the input.</p>
<p>First, there is the <em>Cognitive Pathway</em>, which pertains to innate abilities and how they “hold up” under the stress caused by the other factors. The <strong>memory decay</strong> effect works on the suspended task and makes it hard to resume later because your brain clears out the “mental threads” you had in your mind when working on something, when you move on to something else. Also, <strong>division of mental resources</strong> does not fare well with your hominid brain: it causes conflict, which causes stress, which causes all kinds of nastiness. Interesting tasks that are interrupted also result in <strong>attention residue</strong>, which means your thoughts keep lingering on the interrupted thing, hence making it harder to do the new thing (not great for either outcome). Last, but not least: prospective memory theory predicts you will <strong>forget to get back</strong> to the thing that you were doing. Especially when the interruptions keep coming.</p>
<p>Next is the <em>Self-Regulatory Pathway</em>, that is related to motivational or energetic effects. Starting with action regulatory theory, that describes the <strong>frustration</strong> caused by slow goal progress, which greatly dissuades further progression (example: leaders that are bogged down in mail handling, which is not perceived as making progress, measurably scale down their efforts to, well, lead). Interruptions are principally perceived as goal hampering, hence adding to that frustration. All that, <strong>ego depletion</strong> theory tells us, empties the limited self-regulatory resources you have, which makes it hard or impossible to deal with other items that require the same resources, like anxiety, that otherwise may have been easily managed. The <strong>mental exhaustion</strong> ultimately leads to low job satisfaction and is a high-probability pathway to burn-out.</p>
<p>Lastly, there is the <em>Affective Pathway</em>, that is concerned with emotional impact. Simply put: the interrupting thing can be <strong>good or bad</strong>. Being interrupted by a call that confirms a big client signed up due to previous or ongoing efforts is vastly different from an email from a project manager that adds more items to an already impossible timeline. Also, relevant is the <strong>base anxiety level</strong>, which has been correlated to the amount and frequency of incoming interruptions.</p>
<h3 id="p-the-persons-involved-in-the-task-or-the-interruption">(P) The Person(s) involved in the Task or the Interruption</h3>
<p>This topic deals with people – like you, the person that was interrupted.</p>
<p>We are all individuals. The way we deal with interruptions, stress and multitasking is on a spectrum. <strong>Chronemic preferences</strong> play a role. A polychronic person does not mind juggling multiple things at once with little stress, whereas a monochronic person is able to focus deeply on a single task. The extent of your ability to <strong>screen external stimuli</strong> plays a role: do even slight noises pull you out of concentration or can you work next to a jackhammer? Big 5’s <strong>conscientiousness</strong> is relevant as well. Where others would have given up long ago, someone very diligent can come back again and again to an interrupted task to eventually finish it. The size of your <strong>working buffer</strong> – the capacity to juggle short term memory – relates to when overload increases the decay speed. Also <strong>self-control</strong> is necessary to fight off frustration and stay motivated in the face of adversity. Lastly, <strong>tenure and experience</strong> allow you to be more relaxed in high-stress situations that would thwart someone more junior. What the papers seemingly were not concerned with is neurodiversity. I wonder whether that is a factor.</p>
<p>If the interruption is caused by, or transmitted through, another person, they also play a role in the outcome. While this is not widely researched, it seems at least clear that <strong>interruptions from superiors</strong> are more distracting than from peers.</p>
<h3 id="o-the-range-of-measured-outcome">(O) The range of measured Outcome</h3>
<p>And now finally to the other side of the equation. The paper separates the outcome into two broad domains: <strong>well-being</strong> and <strong>performance</strong>. While it is left to the reviewed papers to detail specific results, the measures that are commonly used are introduced.</p>
<p>A simple performance metric is <strong>completion time</strong>, which directly correlates to productivity: faster completion equals more productive – and vice versa. The <strong>task resumption time</strong>, that describes the extra time added for picking up a suspended task again, adds on overhead, which increases the total time, lowering productivity. Then there is the<strong>error-rate</strong>, that measures the frequency of mistakes when performing a task. This either impacts the quality of the outcome or adds time to fixing those mistakes. The <strong>work quality</strong> itself is also a measure of performance that is also altered by interruptions.</p>
<p>For well-being there is a range of more subjective metrics, most of which are also impacting performance. For example, <strong>job satisfaction</strong> is certainly affected by interruptions. A low level of satisfaction results in a different work attitude, than a high one would. <strong>Stress</strong> is the most common outcome of interruptions that affect planned tasks, as it hinders progression of goals. This goes hand-in-hand with heightened levels of <strong>anxiety</strong>, which do not help level-headed goal execution either. In the long term stressful interruptions can also cause <strong>emotional exhaustion</strong> which is strongly correlated with burn-out. Lastly, the paper cites that actual <strong>physical distress</strong> is not off the table as an outcome.</p>
<p>By the way: All of the performance metrics are directly observable, or at least their effect is. Well-being is not as easy to gauge from the outside and is often measured through self-reporting or interviews or through its indirect impact on performance.</p>
<h2 id="what-is-the-impact-of-interruptions">What is the impact of interruptions?</h2>
<p>You probably noted the letters that I put in parentheses before each above topic headline. These name the terms of the equation that the model comes down to in my understanding:</p>
<div class="right-justify">
<p><img src="https://ulrichkautz.com/img/posts/tiempo.png#small-width" alt="T x I x E x M x P = O" title="T x I x E x M x P = O"></p>
</div>
<p>Yes, I intentionally ordered the letters so that it forms the Spanish word for time (or weather). Even though I do not speak Spanish (my wife does), it helps me to remember.</p>
<p>I am going to call this a <a href="https://en.m.wikipedia.org/wiki/Lazy_loading">lazy</a> approximation. A simple equation with complex terms. The complexity of each of these terms I layed out above. Chances are the continuous research, that is going on, will add more knowledge and nuance. It likely will change, add or replace many of the factors in the terms. However the topics, aka the terms, may be more stable. The equation itself may hold true for longer.</p>
<p>Either way, the question was what the impact of interruptions is. I cannot tell you, yet - or at least not in any precision. However, having the concept that underlies the model in such an explicit fashion available makes it much easier for me to think about it:</p>
<h3 id="scoping-the-outcome">Scoping the outcome</h3>
<p>The equation I ultimately want would deal with numbers. I am not there yet. I am far from any meaningful calculation. Before I can think about that, I first need to get a handle on the scope, which will give me the possible range the formula operates in. At least approximate – that is all I need.</p>
<p>Beginning with the outcome <strong>(O)</strong>: Mind, the outcome was separated into well-being and performance. For simplicity’s sake I am not going to differentiate and lump sum everything together as <em>performance</em>. So, what could the possible result here be? That is actually pretty simple. Given an interruption, one of three things could happen: <em>Things get worse, things stay the same or things get better</em>.</p>
<p>Expressing this in numbers I would use positive, decimal numbers (R&gt;=0)):</p>
<ul>
<li><strong>Values below 0.0</strong>: nonsensical. (Undoing things that were already performed?)</li>
<li><strong>Value of exactly 0.0:</strong> interruptions cause performance to go to zero. Nothing is getting done.</li>
<li><strong>Value below 1.0:</strong> interruptions decrease the performance.</li>
<li><strong>Value of exactly 1.0:</strong> interruptions have no effect whatsoever.</li>
<li><strong>Value above 1.0:</strong> interruptions increase the performance.</li>
</ul>
<p>Going forward when I write <em>the outcome gets worse</em> then I mean that the performance value is influenced to decrease towards 0.0 – and vice versa for _better _means that the performance value is nudged to increase.</p>
<h3 id="scoping-the-terms">Scoping the terms</h3>
<p>To better understand the following, imagine you are looking at a specific role that is offered from a specific organization. I propose that by asking pointed questions you can guesstimate how “interruptive” this role will be and thereby how well you will be able to perform in it – and how your well-being will be impacted. I am not promising that I already have the right questions, but this is fine for now. From what I read so far – they may be close anyway.</p>
<p>Mind also that the terms “worsen” and “improve” will be used in regards to performance – this is not a value judgment. Some functions / roles mandate certain things that cannot be changed. These things have consequences. This is about understanding and predicting these consequences.</p>
<p>Now let&rsquo;s get to it.</p>
<p>Consider <strong>(T)</strong> – the Task – and ask: <em>“In this role, how complex are the tasks that need doing and of how many steps do they consist of?”</em> Think of a spectrum. On the left side is written <em>“multiple, very complicated, dependent steps”</em> and on the right side is written <em>“a single trivial step”</em>. Now order the answer you got for that specific role in that specific organization on that spectrum. The closer the answer is to the left, the closer it is to 0.0. The closer the answer is to the right, the closer it is to 1.0. Resulting the value for (T) either worsens (closer to 0.0) or improves (closer to 1.0) the performance.</p>
<p>Next up <strong>(I)</strong> – the interruption – with the questions: <em>“In this role, how urgent and how frequently do you need to communicate and in what way?”</em>. The spectrum here ranges from the left end (=0.0) <em>“urgent, constant, face-to-face communication”</em> to the right end (=1.0) <em>“pro forma, rare, email communication” .</em> Again, you will find whether (I) for that role worsens or improves the performance in general.</p>
<p>Looking at <strong>(E)</strong> – the Environment – the question is threefold: <em>“In this role, how do you collaborate, where do you work and on how many concurrent things?”</em>. The spectrum is ranging from the left side <em>“in changing groups in large, open work spaces on many things”</em> to the right side <em>“alone, in isolated space, on a single thing”</em>. Find where the role fits on this spectrum.</p>
<p>Now for **(M) **– the Mediators – is not that easy. Actually, I don’t think that this term has to do with the role or the organization, but only with the individual – and maybe with happenstance. I also think that (M) is not static, but due to change. For example through coaching (and maybe through training) towards improvement – or through workload and stress towards worsening. If that is the case then an organization would be advised to treat this the same way as technical debt: continuously invest into improvement to keep the status quo. However, that is far from a well thought out opinion. Let me get back to you on that (in a follow up article). As an individual, it may help consider the factors that are mentioned (above) and evaluate yourself. If you are scoring low (as in: lower performance) you may want to look for roles that do not additionally worsen performance – especially given that performance also includes well-being!</p>
<p>Lastly comes <strong>(P)</strong>. It has a component that is dependent on the organization: the interrupting person. The question, which likely would not get an honest answer, would be: <em>“Is this role micromanaged?”</em>. Well, if that gets an answer then a <em>“yes”</em> worsens performance whereas an <em>“no”</em> improves it. Other than that, it is again more up to the individual to score themselves – and for organizations to filter for the traits that help them.</p>
<h3 id="gauging-the-impact">Gauging the impact</h3>
<p>Now that I walked through all the terms in the equation on both sides, I think there is some immediate practical application: I can now guesstimate what outcome I should expect in terms of well-being and impact on my performance for any role role I come across. At least for three out of five terms in the equation, with the rest mainly pertaining to myself.</p>
<p>I also think any organization should reflect on these terms and truly consider whether their current configuration matches with their goals. I would not be surprised if that is not often the case – especially in the knowledge worker realm, where interruptions seem to be one of the main culprits for productivity loss (getting ahead of myself again).</p>
<p>In any case, I have a much deeper appreciation of the factors that play a role and the questions that I need to ask. While I don’t have any ability to provide specific predictions (like: do X and performance increases by 12%), the landscape of possibilities is much clearer to me.</p>
<h2 id="what-comes-next">What comes next?</h2>
<p>The error rate of factor three, that I cited in the beginning, comes from a study (<a href="https://www.researchgate.net/publication/234085167_Momentary_Interruptions_Can_Derail_the_Train_of_Thought">Altmann, Trafton, Hambrick 2013</a>) that investigated specifically short interruptions – of three or five seconds in length – that disrupted short tasks (also in the seconds range). There are many more studies, 247 of which are linked in the paper from 2019 that caused this blog article. Many, many more studies came out since then. I just started digging into them and can already foresee that I will not squeeze all my learnings into a single post.</p>
<p>For me, the journey to learn about this topic has just begun. I am already reading a lot of papers and hope to post a new article soon. Most of them are like the one cited above, that is they are concerned with a highly specific experiment. The hard part, well the interesting part, is to accumulate multiple of such studies and find generalizations. In case you are wondering why some engineer is interested in this topic: I think we all should. I think this is a very interesting topic of our time. Also everybody needs a hobby.</p>
<p>One thought regarding the outcome: The paper only classifies the result into performance and well-being. I think a classification of short-term and long-term would be more useful, which mostly would map with the provided categories but would frame it in a perspective that would lend itself better for use (in business etc). Even better would be both (long term / short term performance / well-being).</p>
<p>Stay tuned, next up some more numbers. I am most interested in everything that has a practical consequence. I am glad there is so much material and that others do the leg-work that I can now comfortably consume.</p>
<hr>
<p>If you want to join a discussion, please visit the <a href="https://www.linkedin.com/pulse/cost-interruptions-ulrich-kautz/">cross-published version on LinkedIn</a>.</p>
]]></content:encoded></item><item><title>WireGuard VPN setup in Terraform CDK for Road Warriors</title><link>https://ulrichkautz.com/posts/2021-12-05_roadwarrior-wireguard-vpn-in-terraform-cdk/</link><pubDate>Sun, 05 Dec 2021 00:00:00 +0000</pubDate><guid>https://ulrichkautz.com/posts/2021-12-05_roadwarrior-wireguard-vpn-in-terraform-cdk/</guid><category>wireguard</category><category>vpn</category><category>roadwarrior</category><category>road warrior</category><description>Terraform CDK is the next generation of the multi-cloud provider Infrastructure-as-Code tooling from Hashicorp. It&amp;rsquo;s not fully mature, in my opinion, but on it&amp;rsquo;s way and already usable. This article explores the current state with the use-case of a &amp;ldquo;Road Warrior&amp;rdquo; VPN setup, that is based on WireGuard and that can be easily deployed into multiple clouds (and used with my Mac).</description><content:encoded><![CDATA[<p>I&rsquo;ve been working a lot with CDK over the last months, although almost exclusively with the one from <a href="https://github.com/aws/aws-cdk">AWS</a>. I think it is again time to look into what <a href="https://www.terraform.io/docs/cdktf/index.html">Terraform has cooking</a>, so to speak.</p>
<p>Yeah I know, <a href="https://github.com/aws/aws-cdk/releases/tag/v2.0.0">AWS CDK version 2.0</a> has just been released and I should probably write about that.. Tho, while I appreciate the merging of the gazillion <code>@aws-cdk/*</code> libraries into one, there was nothing new that really peaked out to me, that made me want to write about. Then again, I have not really spend a lot of time looking into it. <a href="https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html">Only that it&rsquo;s not at all hard to migrate</a> - which I am thankful for of course.</p>
<p><strong>TL;DR</strong>: <a href="#wireguard-as-vpn-with-terraform-cdk">skip ahead to practical part</a></p>
<h2 id="use-case-road-warrior-vpn">Use-case: Road Warrior VPN</h2>
<p>I&rsquo;ve recently moved - for the first time in my life - outside of my country of birth (Germany). It&rsquo;s a longer story. To cut it short: I can&rsquo;t complain about being bored.</p>
<p>One of the things that came up a bit unexpected for me was limited access to some of the services I got used to using in Germany. Services, that - as I now found out - do geofencing, which means: they restrict access to their services from specific geographic regions.</p>
<p>In addition, I find myself in possibly insecure - or at least untrustworthy - networks, through which my internet access is routed. Networks, whose maintainers possibly log or otherwise spy on my internet traffic. Sure, about everything goes through encrypted transport and there is no malicious attempt - as far as I know - but I don&rsquo;t appreciate the sentiment for whatever reason. It makes my toes itch.</p>
<p>So, I am in need of a VPN solution, that can both move my apparent geographic location to where I want it to be - at least until I switched some services to different providers. In addition it would make me feel better to know all traffic leaving or entering my machine flows through a secure network, that also makes my internet use opaque to the outside.</p>
<p>All of that I want to have on-demand. I probably won&rsquo;t need it 24/7. But maybe. We&rsquo;ll see.</p>
<h2 id="just-use-some-vpn-as-a-service">Just use some VPN-as-a-service?</h2>
<p>There are a great many out there. I know. I see their advertising everywhere. Or maybe I am just caught up in some weird ad-targeting loop. Who knows? From what I gather VPN-as-a-service is a very high-margin market - if likely in a <a href="https://en.wikipedia.org/wiki/Blue_Ocean_Strategy#Blue_ocean_vs._red_ocean">deeply dark red ocean</a>. Hence everyone is primarily competing by pushing out more ads than the competition, hence I see the ads everywhere. Just a hunch.</p>
<p>Anyway. I&rsquo;ve never tried any of them, nor would I. I don&rsquo;t trust them on principle. I know, that sounds a bit paranoid, but when I need to use a VPN (for the reason I layed out above - or any other that I can think of), then I am especially not in a mood to inject an unknown person in the middle of my network. Someone, that is specialized in VPN hosting and has specialized tooling to monitor VPN networks - aka my internet traffic. That is just counter intuitive to me.</p>
<p>Sure, setting up my own VPN on some cloud provider: they also see my network traffic coming through, they also can profile me - or whatever my paranoia thinks those as-a-service are doing. But somehow I deem that far less likely. Mainly because VPN is not the primary use-case for cloud infras. Far from it. Hence cloud-infra provider will likely have a far more generalized tooling / monitoring / network analysis. In short: I suspect they don&rsquo;t care. I might be wrong, of course. I am likely wrong about the VPN provider: they probably don&rsquo;t care about my doings either. It would be bad for their business, if they do.</p>
<p>Or maybe I just needed to cook up a reason to play around with some tech I am interested in. We might never know.</p>
<h2 id="wireguard---an-incredibly-simple-to-use-vpn">WireGuard - an incredibly simple to use VPN</h2>
<p>I&rsquo;ve read often about <a href="https://www.wireguard.com/">Wireguard</a> since it was added to the <a href="https://arstechnica.com/gadgets/2020/03/wireguard-vpn-makes-it-to-1-0-0-and-into-the-next-linux-kernel/">mainline Linux kernel in early 2020</a> and was always intrigued. Sadly, no actual use-case has crossed my professional path. Sure, I played around with it a bit, but without actual needing it - there are just so many other things to play around with that do interfere.</p>
<p>Anyway, that is water under the bridge, for now I have an actual use-case! Let me tell you, after some first practical experience: WireGuard is indeed incredibly easy to use, compared to other VPNs I&rsquo;ve used before.</p>
<p>If you ever had the great displeasure of connecting <a href="https://en.wikipedia.org/wiki/IPsec">IPSec-based VPNs</a> in between devices from multiple vendors, you have a reference for what I mean by: ouch. Granted, it must be something like ten years back for me, so maybe that things have changed and IPsec is now easy pie - although I&rsquo;ve never heard anything along those lines.</p>
<p>The other comparison I have is good ol&rsquo; <a href="https://openvpn.net/">OpenVPN</a>. I don&rsquo;t think I have ever had some it-just-works experience with it, but I can distinctly remember thinking to myself: <em>at least it&rsquo;s not <a href="https://openswan.org/">OpenSwan</a> again</em> (no offense intended - for someone with more of a neck for this kind of thing, I am sure it&rsquo;s a great solution). However, OpenVPN can become rather cumbersome, rather fast as well. There are just so many settings to fiddle with, so many configurations to tune, so many ways things can go wrong.</p>
<p>None of that with WireGuard. It&rsquo;s unbelievable simple. The configuration files are so short you would not believe that they are complete. Alas I did not in the beginning (and searched and searched to figure out what was missing, but nothing was - I am still a bit stunned). Well, at least for the kind of setup that I need - and really, this is all that interest me at this point.</p>
<p>However, this article is not about WireGuard. At least not in depth. I am simply not enough of a network engineer, as you might have deduced, to provide anything of value here. It&rsquo;s about Terraform CDK. So let&rsquo;s get to it:</p>
<h2 id="terraform---one-ring-tool-to-rule-manage-them-all">Terraform - one <del>ring</del> tool to <del>rule</del> manage them all</h2>
<p><a href="https://en.wikipedia.org/wiki/Terraform_(software)">Terraform</a> is around for a quite a while. Since 2014 to be exact - so forever, in internet terms. It&rsquo;s one of the first generalized <a href="https://ulrichkautz.com/zettel/infrastructure-as-code/">Infrastructure-as-Code</a> (IaC) frameworks and also the biggest gorilla in the room.</p>
<p>That is mainly (imo) because Terraform is fully multi-cloud: You can manage resources in about any cloud infrastructure there is. Actually more so. You can manage your own private cloud infrastructure, if you want.</p>
<p>Actually there is still more: You can manage about any programmable service, anything that provides some kind of API. Well, as long as there is a <a href="https://registry.terraform.io/browse/providers">Terraform provider</a>, of course. But there are some many by now: I count 35 official, 166 &ldquo;verified&rdquo; and 1447 community maintained ones at the time of writing - that is 1648 in total.</p>
<p>If that is not enough: You can also <a href="https://www.terraform.io/docs/plugin/framework/index.html">develop your own Terraform provider</a>, in case your service - or one you want to use - is missing from the list.</p>
<p>You get the gist. You can manage &amp; instrument about any kind of infrastructure. Whether you want to maintain your compute instances on <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs">AWS</a>, <a href="https://registry.terraform.io/providers/hashicorp/google/latest/docs">GCP</a> or <a href="https://registry.terraform.io/providers/digitalocean/digitalocean/latest/docs">DigitalOcean</a> or manage your organization in <a href="https://registry.terraform.io/providers/integrations/github/latest/docs">Github</a> or your <a href="https://registry.terraform.io/providers/F5Networks/bigip/latest/docs">F5 Big-IP</a> load balancer in your data-center: Terraform has your back.</p>
<h3 id="terraform-old-school---hcl">Terraform old school - HCL</h3>
<p>All that management is done by writing a huge amount of configuration files in so called <a href="https://www.terraform.io/docs/language/syntax/configuration.html">Terraform HCL</a> (HashiCorp Configuration Language), that looks like this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-hcl" data-lang="hcl"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">resource</span> <span style="color:#b44">&#34;aws_instance&#34; &#34;web&#34;</span> {
</span></span><span style="display:flex;"><span>  ami           <span style="color:#666">=</span> <span style="color:#b44">&#34;ami-123123&#34;</span>
</span></span><span style="display:flex;"><span>  instance_type <span style="color:#666">=</span> <span style="color:#b44">&#34;t3.micro&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>  tags <span style="color:#666">=</span> {
</span></span><span style="display:flex;"><span>    Name <span style="color:#666">=</span> <span style="color:#b44">&#34;HelloWorld&#34;</span>
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>HCL, in very short, you can imagine like YAML or JSON with additional programming-language elements, like variables and simplistic loops. There is a <a href="https://github.com/hashicorp/hcl/blob/main/hclsyntax/spec.md">full specification</a>, if you are interested, that states HCL is one language, that is made up of three sub-languages: A structural language (think YAML/JSON), an expression language (think <a href="https://earthly.dev/blog/awk-examples/"><code>awk</code>-like programming</a>) and a template language (think <a href="https://mustache.github.io/">mustache</a> or so).</p>
<h3 id="terraform-new-school---cdk">Terraform new school - CDK</h3>
<p>The new, cool thing in the IaC world are Cloud Development Kits - or CDK for short. Also, since Terraform HCL became <a href="https://github.com/hashicorp/terraform/releases/tag/v1.0.0">stable in June of this year</a> after only seven years, it&rsquo;s high time to replace it! I&rsquo;ve <a href="https://ulrichkautz.com/posts/2021-02-21_why-i-like-aws-cdk/">written about AWS CDK in the past</a> and <a href="https://ulrichkautz.com/posts/2021-06-09_application-plaform-as-code/#iac--iac">detailed the properties of CDK frameworks</a>, so I will only provide a short summary of Terraform CDK here.</p>
<p>Terraform CDK allows you to use common, high-level programming languages - like Typescript, Python, Go, Java and so on - to write Infrastructure as Code. The advantages - in the very shortest way - are:</p>
<ul>
<li><em>Modularization</em>: Packaging high-level infrastructure description and configuration in the respective packaging of your favorite programming language (NPM package, Go library, etc)</li>
<li><em><a href="https://ulrichkautz.com/zettel/automated-testing/">Testing</a></em>: Write unit and snapshot tests, so to make your infrastructure operation long term maintainable</li>
<li><em>High Level</em>: Use control structures, loops, variables and all the powerful things your language of choice comes with</li>
<li><em>Ecosystem</em>: Use all the best practices, packages/libraries, linters, etc - that come with using a mature programming language</li>
</ul>
<p>Since I never was a big fan of HCL, Terraform going CDK is really amazing to me.</p>
<h2 id="wireguard-as-vpn-with-terraform-cdk">WireGuard as VPN with Terraform CDK</h2>
<p>Ok, now let me show you what I cooked up and how to use it.</p>
<p>The code can be found on GitHub: <a href="https://github.com/ukautz/roadwarrior-vpn">https://github.com/ukautz/roadwarrior-vpn</a></p>
<p>If you want to use the tooling, please keep in mind:</p>
<ul>
<li><strong>Running the VPN will cost money, that is on you (traffic costs might be added as well)</strong></li>
<li>You will need either a <a href="https://www.digitalocean.com/">DigitalOcean</a> or a <a href="https://www.hetzner.com/cloud">Hetzner Cloud</a> account (or modify the tooling to use with your cloud provider of choice - PRs are welcome)</li>
<li>You will need Git to clone the above repository</li>
<li>You will need <code>make</code> (should be pre-installed on Mac/Linux)</li>
<li>You will need a recent&rsquo;ish <a href="https://nodejs.org/">NodeJS SDK</a> installed - basically <code>npm</code> and <code>npx</code> need to be executable</li>
<li>You need to have the <a href="https://www.wireguard.com/install/">WireGuard command line tooling</a> installed, so that <code>wg</code> is executable
<ul>
<li>Also, on Mac I am using the free, official <a href="https://apps.apple.com/us/app/wireguard/id1451685025">WireGuard client GUI</a></li>
</ul>
</li>
</ul>
<h3 id="setup-and-configure">Setup and configure</h3>
<p>The first step is to clone the Git repository into a local folder. As always I will showcase the examples on the command line (maybe some GUI screeners - this time).</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span><span style="color:#080;font-style:italic"># go to your project directory - or wherever you want the code to be</span>
</span></span><span style="display:flex;"><span>$ <span style="color:#a2f">cd</span> ~/MyProjects
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic"># download the repo</span>
</span></span><span style="display:flex;"><span>$ git clone https://github.com/ukautz/roadwarrior-vpn
</span></span><span style="display:flex;"><span>$ <span style="color:#a2f">cd</span> roadwarrior-vpn
</span></span></code></pre></div><p>Now, you need to configure the appropriate token.</p>
<p><strong>DigitalOcean</strong></p>
<p>First <a href="https://docs.digitalocean.com/reference/api/create-personal-access-token/">create a <strong>Personal Access Token</strong> in the web console</a>, then:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>$ <span style="color:#a2f">export</span> <span style="color:#b8860b">CDKTF_CONTEXT_provider</span><span style="color:#666">=</span>digitalocean
</span></span><span style="display:flex;"><span>$ <span style="color:#a2f">export</span> <span style="color:#b8860b">CDKTF_CONTEXT_digitalOceanToken</span><span style="color:#666">=</span><span style="color:#b44">&#34;your-token&#34;</span>
</span></span></code></pre></div><p><strong>Hetzner Cloud</strong></p>
<p><a href="https://docs.hetzner.cloud/#getting-started">Create an <strong>API Token</strong> in the Hetzner Cloud Console</a>, then:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>$ <span style="color:#a2f">export</span> <span style="color:#b8860b">CDKTF_CONTEXT_provider</span><span style="color:#666">=</span>hetzner
</span></span><span style="display:flex;"><span>$ <span style="color:#a2f">export</span> <span style="color:#b8860b">CDKTF_CONTEXT_hcloudToken</span><span style="color:#666">=</span><span style="color:#b44">&#34;your-token&#34;</span>
</span></span></code></pre></div><p><strong>Hint</strong>: If you plan using the VPN on a regular basis, consider persiting those environment variables in <a href="https://direnv.net/">direnv</a> or <a href="https://direnv.net/#related-projects">akin</a>.</p>
<h3 id="start-the-vpn">Start the VPN</h3>
<p>To start the VPN, you just need to run a single make command - wait a minute, though. The first execution creates a key pair for the server and a key pair for your local machine (the client), that you can find in the <code>keys/</code> folder.</p>
<p>This is not organization-level security, but should be sufficient for the Road Warrior use-case.</p>
<p>Before you execute the command, let me explain what it will do:</p>
<ol>
<li>First run setup:
<ul>
<li>Create a key pair for the VPN server and the client (your machine) - unless they already exist in the <code>keys/</code> folder</li>
<li>Resolve NPM package dependencies</li>
<li>Resolve Terraform CDK provider dependencies</li>
</ul>
</li>
<li>Upload your local public SSH key (<code>~/.ssh/id_ecdsa.pub</code> - if you want to use a different one, specify the path via <code>CDKTF_CONTEXT_sshKeyPath=/path/to/key.pub</code>) so you can access the VPN server via SSH as well</li>
<li>Create a VPN server - or however the cloud provider calls the VM; the smallest, cheapest size available will be used (at the time of writing, no guarantees)
<ul>
<li>The server will be created in a German location - that&rsquo;s my use-case after all. See <a href="https://github.com/ukautz/roadwarrior-vpn/blob/main/stack/main.ts#L26">here</a> and <a href="https://github.com/ukautz/roadwarrior-vpn/blob/main/stack/main.ts#L40">here</a> to change that (see <a href="https://docs.digitalocean.com/products/platform/availability-matrix/#available-datacenters">Digital Ocean data centers</a>, <a href="https://docs.hetzner.cloud/#network-zones">Hetzner locations</a>)</li>
</ul>
</li>
<li>The VPN server is setup: <code>wireguard</code> is installed and configured, including the private server key and your public client key that were created locally</li>
</ol>
<p>This is how it should look like (depending on which cloud provider you used):</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span><span style="color:#080;font-style:italic"># start VPN for the first time</span>
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">#   type in `yes` when asked to deploy the VPN server</span>
</span></span><span style="display:flex;"><span>$ make up
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>added <span style="color:#666">349</span> packages, and audited <span style="color:#666">399</span> packages in 1s
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#666">28</span> packages are looking <span style="color:#a2f;font-weight:bold">for</span> funding
</span></span><span style="display:flex;"><span>  run <span style="color:#b44">`</span>npm fund<span style="color:#b44">`</span> <span style="color:#a2f;font-weight:bold">for</span> details
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>found <span style="color:#666">0</span> vulnerabilities
</span></span><span style="display:flex;"><span>Generated typescript constructs in the output directory: .gen
</span></span><span style="display:flex;"><span>Deploying Stack: VpnStack
</span></span><span style="display:flex;"><span>Resources
</span></span><span style="display:flex;"><span> ✔ CLOUDINIT_CONFIG     WireguardCloudInit  cloudinit_config.WireguardCloudInit
</span></span><span style="display:flex;"><span> ✔ HCLOUD_SERVER        VpnServer           hcloud_server.VpnServer
</span></span><span style="display:flex;"><span> ✔ HCLOUD_SSH_KEY       SshKey              hcloud_ssh_key.SshKey
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>Summary: <span style="color:#666">3</span> created, <span style="color:#666">0</span> updated, <span style="color:#666">0</span> destroyed.
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>Output: client-vpn-address <span style="color:#666">=</span> 192.168.6.10/24
</span></span><span style="display:flex;"><span>        server-id <span style="color:#666">=</span> <span style="color:#666">123123123</span>
</span></span><span style="display:flex;"><span>        server-ip <span style="color:#666">=</span> 123.123.123.123
</span></span><span style="display:flex;"><span>        server-status <span style="color:#666">=</span> running
</span></span><span style="display:flex;"><span>        server-vpn-network <span style="color:#666">=</span> 192.168.6.1/24
</span></span><span style="display:flex;"><span>        server-vpn-port <span style="color:#666">=</span> <span style="color:#666">51397</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>Use private key <span style="color:#a2f;font-weight:bold">for</span> client: <span style="color:#b8860b">mDj4yZdqDJBVo3hxF53Xv0aADGjiF0HJxxxppXl9sF8</span><span style="color:#666">=</span>
</span></span><span style="display:flex;"><span>Use public key <span style="color:#a2f;font-weight:bold">for</span> server:  <span style="color:#b8860b">YwOMtZ0HnjcOEfKnTzSkZXvwXV5KJIcXGpfWl10KQlI</span><span style="color:#666">=</span>
</span></span></code></pre></div><p>Well, you will of course have a different <code>server-ip</code> and unique private and public keys. Make note of the output, you will need it in the next step.</p>
<h3 id="connect-to-vpn">Connect to VPN</h3>
<p>To connect to your just started VPN server, you need to create a configuration file, that should look like the following (<strong>MIND to change the values according to your output of the previous <code>make up</code>!</strong>):</p>
<pre tabindex="0"><code class="language-conf" data-lang="conf">[Interface]
PrivateKey = mDj4yZdqDJBVo3hxF53Xv0aADGjiF0HJxxxppXl9sF8=
Address = 192.168.6.10/24
DNS = 1.1.1.1, 8.8.8.8

[Peer]
PublicKey = YwOMtZ0HnjcOEfKnTzSkZXvwXV5KJIcXGpfWl10KQlI=
AllowedIPs = 0.0.0.0/0
Endpoint = 123.123.123.123:51397
</code></pre><p>Let&rsquo;s walk quickly through that:</p>
<ul>
<li><code>[Interface]</code> introduces the section that contains your CLIENT SIDE interface (on your machine)</li>
<li><code>PrivateKey</code> is your client&rsquo;s private key (the public key was already installed on the server via Terraform)</li>
<li><code>Address</code> is your client&rsquo;s IP within the VPN (is associated with your public key on server side)</li>
<li><code>DNS</code> is a list of DNS servers your CLIENT will be using (feel free to change - those are CloudFront and Google)</li>
<li><code>[Peer]</code> introduces the section that contains SERVER SIDE configuration</li>
<li><code>PublicKey</code> is the public key of the VPN server</li>
<li><code>AllowedIPs</code> are the networks (CIDRs) that you want to use a VPN for (<code>0.0.0.0/0</code> means <em>all networks</em> =&gt; <em>all traffic</em>)</li>
<li><code>Endpoint</code> is the public IP of the VPN server</li>
</ul>
<p>That&rsquo;s it! That is the whole configuration you need! And, to me unfathomably, the server side configuration is equally small. Since your SSH key is installed with the server, you can login and have a look in <code>/etc/wireguard/wg0.conf</code>, if you are interested.</p>
<p>Of course, if you setup more sophisticated topologies, the configuration size grows - but it will always be a far cry from the complexity and size of anything IPSec or even OpenVPN. I love it!</p>
<p>You can verify that you are indeed behind a VPN, e.g. by:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>$ curl ifconfig.me
</span></span></code></pre></div><p>That should print out your VPN server&rsquo;s public IP address.</p>
<h4 id="on-a-mac-with-the-gui">On a Mac with the GUI</h4>
<p>If you are on the Mac - and also use the GUI - you can do it from there:</p>
<p>Manage Tunnels:</p>
<p><img src="https://ulrichkautz.com/img/posts/roadwarrior-wireguard-vpn-in-terraform-cdk.gui-manage-tunnels.png" alt="Manage Tunnels"></p>
<p>Add Empty Tunnel:</p>
<p><img src="https://ulrichkautz.com/img/posts/roadwarrior-wireguard-vpn-in-terraform-cdk.add-empty-tunnel.png?limited-width" alt="Add Empty Tunnel"></p>
<p>Then add the following config (changed to your values):</p>
<p><img src="https://ulrichkautz.com/img/posts/roadwarrior-wireguard-vpn-in-terraform-cdk.add-config.png?limited-width" alt="Add Config"></p>
<h3 id="stop-the-vpn">Stop the VPN</h3>
<p>To shut the VPN server down, and thereby stop the whole VPN, I recommend to first disconnect from it (if you are connected), then you can just execute. Again, depending on which provider you use, the output may vary slightly. It should be &ldquo;like&rdquo; this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span><span style="color:#080;font-style:italic"># Type in `yes` when asked to destroy the existing resources</span>
</span></span><span style="display:flex;"><span>$ make down
</span></span><span style="display:flex;"><span>Destroying Stack: VpnStack
</span></span><span style="display:flex;"><span>Resources
</span></span><span style="display:flex;"><span> ✔ CLOUDINIT_CONFIG     WireguardCloudInit  cloudinit_config.WireguardCloudInit
</span></span><span style="display:flex;"><span> ✔ DIGITALOCEAN_DROPLET VpnServer           digitalocean_droplet.VpnServer
</span></span><span style="display:flex;"><span> ✔ DIGITALOCEAN_SSH_KEY SshKey              digitalocean_ssh_key.SshKey
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>Summary: <span style="color:#666">3</span> destroyed.
</span></span></code></pre></div><p><strong>Note</strong>: Make sure you have the respective <code>CDKTF_CONTEXT_provider</code> and token environment variables (still) exported - as described above. They are needed.</p>
<h3 id="digging-into-it">Digging into it</h3>
<p>If you are interested about the underlying Terraform CDK implementation, here some highlights:</p>
<h4 id="are-all-terraform-hcl-providers-available-for-terraform-cdk">Are all Terraform HCL providers available for Terraform CDK?</h4>
<p>This is an important question. One that kind of came up immediately for me, because this is really the primary selling argument to use Terraform in the first place: The sheer amount of supported infrastructure.</p>
<p>In short, the answer is a clear and resounding: <strong>Yes</strong>.</p>
<p>For a bit longer answer: The <code>cfktf</code> CLI provides the immensly powerful <a href="https://www.terraform.io/docs/cdktf/cli-reference/commands.html#get"><code>get</code> command</a>, that both downloads the Terraform (HCL) providers <em>and</em> generates CDK constructs - in the language you are using - for you. These constructs are generated directly from the HCL, that means: Any Terraform provider is supported, not only the official ones.</p>
<p>For a long explanation and excellent tutorial, have a look in the <a href="https://www.terraform.io/docs/cdktf/concepts/providers-and-resources.html#import-providers">documentation</a>.</p>
<h4 id="modularized-server-configuration-via-cloud-init">Modularized server configuration via Cloud Init</h4>
<p>Modularization and encapsulation is one of the huge advantages that CDK-style frameworks offer, due to using what the high-level language, they are based on, already provides: functions, classes, packages/libraries. Sure, &ldquo;classical&rdquo; Terraform has a <a href="https://www.terraform.io/docs/language/modules/develop/index.html">module concept</a>, but if you ever worked with that - and then compare it to the ease and flexibility simple functions and classes grant you&hellip;</p>
<p>To give you an example: I encapsulated the <a href="https://cloudinit.readthedocs.io/en/latest/">cloud-init</a> configuration in a dedicated <a href="https://ulrichkautz.com/posts/2021-06-09_application-plaform-as-code/#kinds-of-constructs">Level 2</a> <a href="https://github.com/ukautz/roadwarrior-vpn/blob/main/stack/lib/wireguard-cloud-init.ts">CDK construct</a>, which inherits from the the <a href="https://registry.terraform.io/providers/hashicorp/cloudinit/latest/docs/data-sources/cloudinit_config"><code>cloudinit_config</code></a> directive which you might know already if you used Terraform HCL. An instance of it is then passed to the respective server constructs in <a href="https://github.com/ukautz/roadwarrior-vpn/blob/main/stack/lib/digitalocean-stack.ts#L39-L42">DigitalOcean</a> or <a href="https://github.com/ukautz/roadwarrior-vpn/blob/main/stack/lib/hetzner-stack.ts#L39-L42">Hetzner Cloud</a>.</p>
<p>Side note: A surprise here was that DigitalOcean does not support base64, gzipped cloud-init files. So I needed to introduce a <a href="https://github.com/ukautz/roadwarrior-vpn/blob/main/stack/lib/wireguard-cloud-init.ts#L14">parameter</a> to allow plain, uncompressed user data.</p>
<h4 id="dedicated-stack-per-cloud-provider">Dedicated stack per cloud provider</h4>
<p>When you deploy the VPN infra, you can control which provider is being used by setting the <code>CDKTF_CONTEXT_provider</code> variable to <code>hetzner</code> or <code>digitalocean</code>. Ideally, I would like to write the CDK code in such a way, that I just create &ldquo;a server&rdquo;. Under the hood, that should use some kind of <a href="https://refactoring.guru/design-patterns/adapter">adapter</a> implementation that the selected provider supplies. Like so:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdktf <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#34;cdktf&#34;</span>;
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// --%&lt;--
</span></span></span><span style="display:flex;"><span>cdktf.setProvider(<span style="color:#b44">&#34;hetzner&#34;</span>);
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">new</span> cdktf.Server(...);
</span></span></code></pre></div><p>That is <strong>not</strong> how it works. In the same that Terraform (HCL) has providers, that offer their own resources, Terraform CDK needs you to use the specific constructs, offered by the providers. That means the code looks much more like this (if not exactly):</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> hetzner <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#34;./gen/provider/hetzner&#34;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> digitalocean <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#34;./gen/provider/digitalocean&#34;</span>;
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// --%&lt;--
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">new</span> hetzner.Server(...);
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">new</span> digitalocean.Droplet(...);
</span></span></code></pre></div><p>All providers come with their own resources. If those resources &ldquo;look the same&rdquo;, then they do so incidentally. In the case of the server/VM DigitalOcean calls their construct <code>Droplet</code>, whereas Hetzner goes with <code>Server</code>. Both, btw, call their SSH key construct actually <code>SshKey</code>.</p>
<p>This is why I needed to create a dedicated <a href="https://github.com/hashicorp/terraform-cdk/blob/main/docs/working-with-cdk-for-terraform/app-stacks-concept.md">Terraform CDK stack</a> for each cloud provider in use:</p>
<ul>
<li><a href="https://github.com/ukautz/roadwarrior-vpn/blob/main/stack/lib/digitalocean-stack.ts">DigitalOcean Stack</a></li>
<li><a href="https://github.com/ukautz/roadwarrior-vpn/blob/main/stack/lib/hetzner-stack.ts">Hetzner Cloud Stack</a></li>
</ul>
<p>If you look them over, you&rsquo;ll find they do look suspiciously alike - but, as written above, they only &ldquo;look alike&rdquo;. The actual constructs in use are vastly different under the hood - as are their HCL &ldquo;origins&rdquo;.</p>
<p>Maybe in the future, there will be a &ldquo;Terraform Hosting CDK&rdquo; (or so) framework, that provides a semantic closer to my first code example and allows you to define infrastructure independent of the provider. Just switching out the credentials used would then switch the provider. Kind of how multi-cloud was pitched to me, back in the days. Or maybe I misunderstood.</p>
<p>Anyway, such a framework could only ever provide the &ldquo;smallest common denominator&rdquo; of functionality that all the supported cloud providers offer - so I am not sure whether it would be of any use.. Well, it&rsquo;s a dream.</p>
<h4 id="terraform-cdk-vs-parameter">Terraform CDK vs parameter</h4>
<p>Not unlike when I started to dig into AWS CDK, the &ldquo;parameter situation&rdquo; in Terraform CDK is somewhat unclear to me.</p>
<p>When you worked with Terraform HCL, you probably came across <a href="https://www.terraform.io/docs/language/values/variables.html">input variables</a>. You could use them via environment variables or command line parameters at runtime, e.g.:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>$ <span style="color:#a2f">export</span> <span style="color:#b8860b">TF_VAR_some_var</span><span style="color:#666">=</span>foo
</span></span><span style="display:flex;"><span>$ terraform apply -var<span style="color:#666">=</span><span style="color:#b44">&#34;other_var=bar&#34;</span>
</span></span></code></pre></div><p>These variables are still around in the CDK as <a href="https://github.com/hashicorp/terraform-cdk/blob/main/docs/working-with-cdk-for-terraform/terraform-variables.md"><code>TerraformVariable</code> constructs</a>. However, they are of limited use - and not only because the <code>cdktf deploy</code> command (basically equivalent to <code>terraform apply</code>) does not have a <code>-var</code> parameters anymore (nor does it care about <code>TF_VAR_anything</code>).</p>
<p>The situation is somewhat similar in AWS CDK, that has it&rsquo;s origin in CloudFormation. With CloudFormation you used <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html">parameters</a>, that then could be used on the command line (similar to the <code>-var</code> above):</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-shell" data-lang="shell"><span style="display:flex;"><span>$ aws cloudformation deploy --parameter-overrides <span style="color:#b8860b">SomeParam</span><span style="color:#666">=</span>Foo
</span></span></code></pre></div><p>While those parameters are also available in AWS CDK as <a href="https://docs.aws.amazon.com/cdk/latest/guide/parameters.html"><code>CfnParameter</code> constructs</a>, they are of limited use, because they are interpolated at synthesis time. That means: They are available when the CloudFormation is actually executed (i.e. deployed), but their value cannot be used e.g. in control structures. To be clear, you <strong>cannot</strong> do the following:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span> someParam <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> CfnParameter(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#34;SomeParam&#34;</span>, {<span style="color:#a2f;font-weight:bold">type</span><span style="color:#666">:</span> <span style="color:#b44">&#34;String&#34;</span>, ..});
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">if</span> (someParam <span style="color:#666">===</span> <span style="color:#b44">&#34;Foo&#34;</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// do something
</span></span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Within that above <code>if</code> condition the <code>someParam</code> value would be something like <code>${TOKEN[0]}</code>. The same goes for <code>TerraformVariable</code> constructs. Their value is &ldquo;not available at code execution time&rdquo;. Hence: they are of limited use.</p>
<p>So what do you do instead?</p>
<p>Again, going back to AWS CDK, which is quite mature and people put some thinking into it, already. AWS CDK recommends to use <a href="https://docs.aws.amazon.com/cdk/v2/guide/context.html">Context</a> instead. Context can be provided in multiple ways:</p>
<ul>
<li>When executing <code>cdk deploy</code> - or alike - as parameter like <code>--context someName=Foo</code></li>
<li>In <code>cdk.json</code> file (<code>{&quot;context&quot;: {&quot;someName&quot;: &quot;foo&quot;}}</code>)</li>
<li>In <code>cdk.context.json</code> file (<code>{&quot;someName&quot;: &quot;foo&quot;}</code>)</li>
<li>User-wide in <code>~/.cdk.json</code> file (also <code>{&quot;context&quot;: {&quot;someName&quot;: &quot;foo&quot;}}</code>)</li>
</ul>
<p>Once it is provided, it can be easily used in the code:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdk <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#34;aws-cdk-lib&#34;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">export</span> <span style="color:#a2f;font-weight:bold">class</span> SomeStack <span style="color:#a2f;font-weight:bold">extends</span> cdk.Stack {
</span></span><span style="display:flex;"><span>  <span style="color:#a2f;font-weight:bold">constructor</span>(scope: <span style="color:#0b0;font-weight:bold">Construct</span>, id: <span style="color:#0b0;font-weight:bold">string</span>, props?: <span style="color:#0b0;font-weight:bold">cdk.StackProps</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">super</span>(scope, id, props);
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">if</span> (<span style="color:#a2f;font-weight:bold">this</span>.node.tryGetContext(<span style="color:#b44">&#34;someName&#34;</span>) <span style="color:#666">===</span> <span style="color:#b44">&#34;Foo&#34;</span>) {
</span></span><span style="display:flex;"><span>      <span style="color:#080;font-style:italic">// do something
</span></span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Since both AWS CDK and Terraform CDK are build on the <a href="https://github.com/aws/constructs">Constructs package</a>, the <code>this.node.tryGetContext</code> accessor is actually also usable in Terraform CDK. However, the ways to provide context in Terraform CDK are far more limited. Currently, you can set context <em>only</em> in <code>context</code> within the <code>cdktf.json</code> file.</p>
<p>Theoretically, you could also set a JSON encoded value to the <a href="https://github.com/hashicorp/terraform-cdk/blob/f0ffd602ca77d529e34d08e5b8a3c368bc74e810/packages/cdktf/lib/app.ts#L9"><code>CDKTF_CONTEXT_JSON</code> environment variable</a> - but that is overloaded <a href="https://github.com/hashicorp/terraform-cdk/blob/2d58c1256b6e58ce9d89fefc0b8f961e8073b21d/packages/%40cdktf/provider-generator/lib/config.ts#L242-L268">when the <code>cdktf.json</code> file is read</a>. So: no, you can&rsquo;t.</p>
<p>To address that issue I went ahead and wrote an experimental solution that allows you to provide context in additional ways. You may have noted the above instruction to use <code>CDKTF_CONTEXT_&lt;name&gt;=&lt;value&gt;</code> or modify the <code>provider.json</code> file. Both of these variants are part of the experimental solution. I&rsquo;ve <a href="https://github.com/ukautz/roadwarrior-vpn/blob/main/stack/lib/core/app.ts#L4-L54">extended the Terraform CDK <code>App</code> construct</a> so that it automatically loads:</p>
<ul>
<li>A JSON encoded file that is specified in <code>CDKTF_RUNTIME_CONTEXT_FILE</code> environment variable</li>
<li>JSON encoded string that is specified in <code>CDKTF_RUNTIME_CONTEXT</code> environment variable</li>
<li>Any environment variable of the form <code>CDKTF_CONTEXT_&lt;name&gt;=&lt;value&gt;</code></li>
</ul>
<p>Check out the implementation <a href="https://github.com/ukautz/roadwarrior-vpn/blob/main/stack/lib/core/app.ts">here</a> and the especially the usage in the <a href="https://github.com/ukautz/roadwarrior-vpn/blob/main/stack/main.ts">main.ts file</a>.</p>
<p>Whether this experiment pans out, we&rsquo;ll see. For this particular use-case it seems to be working well enough. It allows me to be extremly upfront about all dependencies - aka input parameters - by having them all declared in <code>main.ts</code>. That is very important to me. I could also imagine how this would work in a typical staging scenario, in which I deploy the same stack into multiple stages / environments (like testing, staging, qa, production, you-name-it).</p>
<p>Alternatively, you can always use <code>process.env[&quot;VAR&quot;]</code> directly - although it was considered bad practice within AWS CDK.</p>
<h4 id="testing">Testing</h4>
<p>I did look into unit and snapshot testing in this stint, but not in overly depth.</p>
<p>Have a look into the <a href="https://github.com/ukautz/roadwarrior-vpn/tree/main/stack/__tests__">tests folder</a>. If you are familiar using the <a href="https://jestjs.io/">Jest testing framework</a> - that is also used when <a href="https://docs.aws.amazon.com/cdk/v2/guide/testing.html">writing AWS CDK tests</a> - you should have an easy time understanding.</p>
<p>Especially interesting might be how write <a href="https://github.com/ukautz/roadwarrior-vpn/blob/main/stack/__tests__/digitalocean-stack-test.ts">tests for stacks (<code>synth</code>)</a> is slightly different than writing <a href="https://github.com/ukautz/roadwarrior-vpn/blob/main/stack/__tests__/wireguard-cloud-init-test.ts">tests for (other) constructs (<code>synthScope</code>)</a>.</p>
<h3 id="extend-for-a-different-cloud-provider">Extend for a different cloud provider</h3>
<p>The implementation fulfills my use-case. I likely won&rsquo;t extend on it. If you are interested to provide an implementation for a different cloud provider, feel free to offer a PR. I am sure to look it over and happy to merge it (please mind some testing).</p>
<h2 id="fin">Fin</h2>
<p>That&rsquo;s it. Hope this helps someone with the same problem I had - or at least furthers the interest in Terraform CDK.</p>
]]></content:encoded></item><item><title>Finally A Personal Knowledge Management Tooling That Works</title><link>https://ulrichkautz.com/posts/2021-11-24_personal-knowledge-management-that-works/</link><pubDate>Thu, 25 Nov 2021 00:00:00 +0000</pubDate><guid>https://ulrichkautz.com/posts/2021-11-24_personal-knowledge-management-that-works/</guid><category>personal knowledge management</category><category>personal knowledge database</category><category>personal information management</category><category>second brain</category><description>I was interested in the topic of personal knowledge management since I first used a computer for learning. So far I could not find a solution that really worked well for me. Until now. I found my second brain. If you are a knowledge worker as well, are not gifted with a perfect memory and therefore need a tooling to help you manage the knowledge you learn - read on in the blog post.</description><content:encoded><![CDATA[<p>In my profession - as in <a href="https://en.wikipedia.org/wiki/Knowledge_worker">many, many others</a> as well - knowledge is very valuable. Growing knowledge, as in <a href="https://en.wikipedia.org/wiki/Continual_improvement_process">continuous</a> <a href="https://en.wikipedia.org/wiki/Lifelong_learning">learning</a>, is the common response. I don&rsquo;t want to make that sound like a chore! For it is not! I love to learn. I love to read. I love to explore and experiment. There are few things that are more fun, in my opinion.</p>
<p>However, a part of that process is actually a chore, or at least not easy. That part is storing the learned knowledge in a way, that it is easily accessible in the future. Well, if you have perfect memory you can stop reading here, and forget you ever found this blog (pun intended). My memory is terrible. I often deal with <a href="https://en.wikipedia.org/wiki/Complex_system">complex systems</a>, that have highly detailed information. I also engage with a broad range of <a href="https://en.wikipedia.org/wiki/Domain_knowledge">knowledge domains</a>. In short: I am in dire need of an artificial crutch, that helps me organize all the interesting nuggets of knowledge that I come across.</p>
<p>Now we are getting to the crux of this post. Such a tooling, to manage my own personal knowledge, has been a pet peeve of mine since I first used a computer as a tool for learning. I never found a good software that really fits my needs. What I came across in the past either had bad usability (makes me sad), was only available for some of my devices (a no-go), or forced me to give up ownership over the content (not helpful). Thanks, but no thanks.</p>
<p>For a long time I was bouncing in between tools. Creating data graves as I went. While I certainly did not research the topic continuously, I occasionally looked around and sometimes even put some time into research - without real success, to my great chagrin. Recently, I had some bigger life changes, which also left me with some time on my hand. So I took the opportunity and studied a lot. Hence my urge to find a tooling to preserve that new knowledge surfaced again - and I think I found something that actually checks all the boxes for me this time! Read on if you are interested.</p>
<h2 id="what-is-personal-knowledge">What is personal knowledge?</h2>
<p>I think I need to clarify what I mean with personal knowledge, or my solution for personal knowledge management may not make sense to you.</p>
<p>On the Wikipedia page about <a href="https://en.wikipedia.org/wiki/Personal_knowledge_base">personal knowledge base (PKB)</a> I found the following paragraph, that deeply resonates with me:</p>
<blockquote>
<p>[&hellip;] It differs from a traditional database in that it contains <strong>subjective material particular to the owner</strong>, that others may not agree with nor care about. Importantly, a PKB consists <strong>primarily of knowledge, rather than information</strong>; in other words, it is not a collection of documents or other sources an individual has encountered, but rather an <strong>expression of the distilled knowledge the owner has extracted</strong> from those sources. [&hellip;]</p>
</blockquote>
<p>So in short: <strong>Personal knowledge is distilled information, that makes sense to the owner who extracted it from other sources</strong>.</p>
<p>It is, in a way, a personal shorthand. Information, retained in such a way, that when <strong>I</strong> read it again, it will make sense to me - but maybe not to someone else (or maybe it will, I frankly don&rsquo;t care - however, I do for my blog posts).</p>
<h2 id="what-is-personal-knowledge-management">What is personal knowledge management?</h2>
<p>With the above understanding of <em>personal knowledge</em>, the <em>management</em> part means that there needs to be a process to build that knowledge and then make it usable. In practice that means there needs to be a tooling, that implements or at least supplements that process.</p>
<p><strong>For the process</strong>, I started out with the <a href="https://en.wikipedia.org/wiki/Zettelkasten">Zettelkasten</a> (German for: <em>note box</em>) method, which is in (very) short: an organization system with a prescribed method how to record and interlink knowledge that is written on notes (either analog or digital). I won&rsquo;t go into much detail how that exactly works, as there are awesome tutorials to be found:</p>
<ul>
<li><a href="https://zettelkasten.de/posts/overview/">https://zettelkasten.de/posts/overview/</a></li>
<li><a href="https://zenkit.com/en/blog/a-beginners-guide-to-the-zettelkasten-method/">https://zenkit.com/en/blog/a-beginners-guide-to-the-zettelkasten-method/</a></li>
<li><a href="https://www.levelupfun.com/articles/writing-to-understand-the-zettelkasten-system-of-smart-notes">https://www.levelupfun.com/articles/writing-to-understand-the-zettelkasten-system-of-smart-notes</a></li>
<li><a href="https://www.google.com/search?q=zettelkasten%20getting%20started">search yourself</a></li>
</ul>
<p>Also, I am not really following Zettelkasten (anymore). It didn&rsquo;t work out for me, alas when trying to adhere strongly to it. For now I am using a &ldquo;dirty derivate&rdquo;, that is something in between Zettelkasten and a Wiki. If you roughly know how Wikipedia works, you are fine for the rest of this article. So far that system works out for me. Maybe I will come back to a more formalized method in the future. Maybe I will document my method and make it formalized. Maybe neither.</p>
<p>There are also two other documented methodologies I came across. None of them spoke to me, so, aside from superficial research and reading, I haven&rsquo;t tried them out:</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Getting_Things_Done">GTD - Getting Things Done</a></li>
<li><a href="https://fortelabs.co/blog/para/">P.A.R.A.</a> - seems to be bundled with proprietary software</li>
</ul>
<p>Anyway. Whatever methods works out for you is the right one. I recomend to start with Zettelkasten and iterate from there, but that&rsquo;s just because that was my journey.</p>
<h2 id="what-is-a-personal-knowledge-management-tool">What is a personal knowledge management tool?</h2>
<p>Within the realm of software engineering, you usually start to answer a question about the properties a software needs to have by interviewing the intended users and extracting their requirements. The intended user is me, so that is easily done. However, I think I can put the requirements in a form that is much more universal and will make sense to you as well.</p>
<p>Here we go then. In my opinion, any personal knowledge management tool needs to address four topics:</p>
<ol>
<li><strong>Storing personal knowledge</strong>, so that the knowledge can endure and grow over a long time</li>
<li><strong>Accessing personal knowledge</strong>, so that the knowledge is available when needed</li>
<li><strong>Browsing personal knowledge</strong>, so that the knowledge can be navigated and consumed easily</li>
<li><strong>Editing personal knowledge</strong>, so that building and maintaining the knowledge is easy</li>
</ol>
<p>The order of the topics is of little consequence. This is just the way I thought of them. Let&rsquo;s have a deeper look:</p>
<h3 id="storing-personal-knowledge">Storing personal knowledge</h3>
<p>Storage is cheap these days. Every service, it seems to me, throws a gigazillion bytes of free storage at you. For personal knowledge management you actually don&rsquo;t need much - comparatively speaking. We are talking mainly text files here. Maybe some odd diagrams, images or other, small binary formats. This won&rsquo;t need terrabytes, not even gigabytes, even for very large knowledge databases.</p>
<p>Consider <a href="https://keep.google.com/">Google Keep</a>, <a href="https://www.icloud.com/notes">Apple Notes</a>, <a href="https://www.onenote.com/">Microsoft OneNote</a>, <a href="https://evernote.com/">Evernote</a> and other &ldquo;notes-as-a-service&rdquo; offers. At a first glance, they seem to offer at least part of what a personal knowledge management tool would need. Also they are either free or available for a small coin. However, they - and all tools like them - are categorically unusable, in my opinion, for a simple reason: <strong>Storage is about ownership.</strong></p>
<p>What does that mean? Any tool like the above allows you to store data within. However, getting the data out, so that you can put it into another tool, is a whole different story. Even if you can get it out - through begging, legal threats or dark magic - the data also needs to be in a format, so that the new tooling can understand it.</p>
<p>I think this is a very important point, so please allow me elaborate on that: Think of any software that you are using right now (that goes for anything, also outside of knowledge management). Chances are high that it won&rsquo;t be around in five years - or if that, then what about ten years? Or twenty? We&rsquo;re talking about your personal knowledge database here, that - ideally - is around as long as you are around.</p>
<p>There are a million reasons, why the software won&rsquo;t be around: Maybe a competitor buys up the vendor, discontinues the software. Maybe the vendor decides to pivot and discontinues the software themselves. Maybe the vendor is a SaaS that suffers a fatal data-breach and is wiped of the map. Maybe the software is open source and the lone contributer gives up coding in favor of ice-skating. And so forth. I think you get the gist: Software is short-lived. Data is not. Software is just an interface. Data is the knowledge. <strong>Own your data, or lose your knowledge.</strong></p>
<p>Excuse my ranting. I have been burned in the past. I usually don&rsquo;t mind about storing data with the vendor. I use a lot of tools that are exclusively online and that do create data. However, for this specific use-case of a personal knowledge database, it&rsquo;s immensely frustrating if you find your data unusable or inaccessible, after collecting it for a good while.</p>
<p><strong>Requirements:</strong></p>
<ul>
<li>I can access the raw data representation of my knowledge</li>
<li>My knowledge is preserved in an <a href="https://en.wikipedia.org/wiki/Open_format">open format</a></li>
</ul>
<h3 id="accessing-personal-knowledge">Accessing personal knowledge</h3>
<p>Access is, of course, key. If I cannot access my knowledge, it has no use to me.</p>
<p>These days, using multiple devices is commonplace. Also switching devices is far from unheard of. And I am not only talking about getting the next model. I was using Android phones - until about two years ago, now I am using an iPhone. I might switch back next year. I was using exclusively Linux on my Deskop, until six months ago, now I am using a Mac. I might switch back again sometime. Maybe AR and VR becomes actually a part of our lives soon. Who knows what OS will power that?</p>
<p>While I would really like not to be bound to a specific vendor, hardware or subscription - at the very least: my personal knowledge needs to be <strong>accessible from all devices that I am currently using</strong>. Possibly more: I might need &ldquo;some&rdquo; access to my knowledge, even without my devices at hand. Let&rsquo;s call that a nice-to-have.</p>
<p>Access from multiple devices also means that the data must be synchronized somehow in between the devices. Otherwise it becomes very hard to maintain at best and suffers actual data-corruption at worst. Wrong knowledge may be worse than no knowledge.</p>
<p><strong>Requirements:</strong></p>
<ul>
<li>My knowledge is accessible from all my devices</li>
<li>My knowledge is synchronized between all my devices</li>
</ul>
<p><strong>Nice to have:</strong></p>
<ul>
<li>My knowledge accessible without my devices (but then protected with authorization?)</li>
</ul>
<h3 id="browsing-personal-knowledge">Browsing personal knowledge</h3>
<p>Assuming the knowledge is stored and accessible, then another important question arises: How can I navigate it, how can I interrogate my personal knowledge database in a convenient way? This must be really easy and intuitive, or all of the above is for naught.</p>
<p>To get to the requirements, let me spell out what I need to be able to do with the tooling. Basically: What are my <a href="https://en.wikipedia.org/wiki/User_story">user stories</a>(&lsquo;ish) that describe how I will interact with the tooling when I am browsing my knowledge? Here we go:</p>
<ol>
<li>I have something that I want to add and need to know whether it&rsquo;s already there (i.e. extend or create)</li>
<li>I have a specific thing / term / word in mind, that I want to look up</li>
<li>I have a broad issue / topic / subject in mind and want more info about it i.e. I want to see what I collected about that</li>
<li>I already found something and now want to dig deeper</li>
<li>I already found something, it&rsquo;s not what I wanted, but close / related</li>
</ol>
<p>Ok, that makes it easy to formulate the requirements. The first two come down to a base full text search. The third requires the knowledge to be categorized; actually things could be in multiple categories, so I&rsquo;m gonna call that: taggable. Once they are that, they can be listed by tag - and tags can be listed as well. For the last two there need to be navigable links, like good ol&rsquo; hyperlinks in the interwebs.</p>
<p><strong>Requirements:</strong></p>
<ul>
<li>I can search my knowledge (full text)</li>
<li>I can view all my knowledge in a topic (aka tag)</li>
<li>I can follow links in between my knowledge</li>
</ul>
<h3 id="editing-personal-knowledge">Editing personal knowledge</h3>
<p>Last, because it references all topics, we need to talk about input of knowledge. Input is adding of new knowledge and of course also correcting or extending existing knowledge. Also deleting of wrong or re-factored knowledge contents must be possible. Let&rsquo;s just extend that to the standard <a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> (create, read, update, delete) operations.</p>
<p>Looking at the previous topic about browsing, there is also linking and tagging that needs to be possile. It is equally important that I can create relations in between the knowledge. Aside from being required for navigation a lot of <em>information is in the connection itself</em>.</p>
<p>And finally, I want to be able to group knowledge. This is differnt from linking. More like categorizing</p>
<p>And all of the above needs to be doable in an easy way. Easy, I guess, is relative. What is easy to you, might be hard for me and vice versa. Hence we both might judge it differently. You will see below when I present the solution I found, that works pretty well for me.</p>
<p><strong>Requirements:</strong></p>
<ul>
<li>I can create, read, update and delete (CRUD) my knowledge</li>
<li>I can tag my knowledge</li>
<li>I can create links in between my knowledge</li>
</ul>
<h2 id="what-is-the-solution-then">What is the solution then?</h2>
<p>Having all the requirements spelled out, is the hard part. At least for me it becomes much clearer what a solution needs to look like.</p>
<p>So without further ado: I am using <a href="https://obsidian.md/">Obsidian</a>, which styles itself as a second brain and is basically a text editor with <a href="https://en.wikipedia.org/wiki/Markdown">Markdown</a> syntax highlighting and rendering support. It provides a text search and various visualizations of the contents.</p>
<p>There are native apps for the usual mobile and desktop operating systems (Android, iPhone, Linux, Mac, Windows).</p>
<p>It&rsquo;s free for personal use. On top of that, it has a large amount of <a href="https://obsidian.md/plugins">community provided plugins</a>, that add more visualization, help integrate with 3rd party and much more.</p>
<p>To be clear: <em>I am in no way, shape or form involved with the developers or company. I am just speaking from my own experience over the last three or so months.</em></p>
<p>If that peaked your interest, here are the most noteworthy getting started guides and tutorials I came across:</p>
<ul>
<li><a href="https://www.marclittlemore.com/beginners-guide-note-taking-obsidian/">Marc Littlemore: A beginner&rsquo;s guide to note taking using Obsidian</a> - a quick overview, good intro</li>
<li><a href="https://theproductiveengineer.net/the-beginners-guide-to-obsidian-notes-step-by-step/">Productive Engineer: Beginners Guide to Obsidian</a> - visual explanation of the user interface</li>
<li><a href="https://www.youtube.com/results?search_query=obsidian+zettelkasten">Youtube for audio-visual learners</a> - especially the ones from Martin Adams are very detailed</li>
</ul>
<p>Or you just get started, as I mostly did, and see where that leads you. It&rsquo;s quite intuitive.</p>
<p>Also, because I came up with that requirement list and feel now obligated to do the visual check:</p>
<table>
	<thead>
			<tr>
					<th>Requirement</th>
					<th>Fulfilled</th>
					<th>Solution</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>access to raw data</td>
					<td>✔</td>
					<td>Stores files on local disk</td>
			</tr>
			<tr>
					<td>open format</td>
					<td>✔</td>
					<td><a href="https://en.wikipedia.org/wiki/Markdown">Markdown</a></td>
			</tr>
			<tr>
					<td>access from all devices</td>
					<td>✔</td>
					<td>iOS &amp; MacOS App (as well as Android, Windows, Linux)</td>
			</tr>
			<tr>
					<td>synchronized betwee devices</td>
					<td>✔</td>
					<td><a href="https://help.obsidian.md/Obsidian/iOS+app">iCloud</a> or <a href="https://github.com/denolehov/obsidian-git">Git(hub)</a> or <a href="https://help.obsidian.md/Licenses+%26+add-on+services/Obsidian+Sync">paid</a> sync</td>
			</tr>
			<tr>
					<td>full text search</td>
					<td>✔</td>
					<td><a href="https://help.obsidian.md/Plugins/Search">search text files</a></td>
			</tr>
			<tr>
					<td>add tags</td>
					<td>✔</td>
					<td><a href="https://help.obsidian.md/How+to/Working+with+tags">front matter</a></td>
			</tr>
			<tr>
					<td>view tagged</td>
					<td>✔</td>
					<td><a href="https://github.com/aidurber/tag-page-preview">community plugin</a></td>
			</tr>
			<tr>
					<td>knowledge links</td>
					<td>✔</td>
					<td><a href="https://help.obsidian.md/How+to/Internal+link">internal link</a> format</td>
			</tr>
			<tr>
					<td>CRUD</td>
					<td>✔</td>
					<td>text editor</td>
			</tr>
	</tbody>
</table>
<p>As you can tell I am really happy with Obsidian (so far). Especially the easy access to my files in a format that I can re-use is appreciated. Even if Obsidian should not work out for any reason, I will still have all my knowledge stored in universally usable Markdown files. That gives me confidence that I will not create another data grave again and motivates me to put in the time to document what I learn.</p>
<h3 id="the-power-of-open-formats-easteregg">The power of open formats (Easteregg)</h3>
<p>Apropos universally usable. You might have noted that the nice-to-have about <em>access without any of my devices</em> did not show up in the above table. And yes, Obsidian cannot help much here. However, I am using iCloud to sync my files between my phone and laptop. I <em>also</em> use the <a href="https://github.com/denolehov/obsidian-git">Git plugin</a> to automatically create regular backups to a (private) Github repository. Hence, I can access my knowledge without my devices, as long as I have Github access.</p>
<p>Even more so. This blog you are reading, is published via <a href="https://gohugo.io/">Hugo</a>, which is an open source static site generator that can be easily used for blogging. Coincidently, my blog pages are generated from Markdown documents that I write.</p>
<p>So I figured: why not make (some part of) my knowledge database available to me and potentially others through my personal homepage? This way I can can link to entries from other publications and especially have it accessible from anywhere. It might also do good for my <em>*cough*</em> otherwise non-existing SEO efforts.</p>
<p>So I thought and so I did. Here you can find an excerpt of my personal knowledge database: <a href="https://ulrichkautz.com/zettel">https://ulrichkautz.com/zettel</a>.</p>
<p>And here is the tooling that exports (and slightly converts) the Markdown files from my local Obsidian directory to my local Hugo contents directory: <a href="https://github.com/ukautz/obsidian-meets-hugo">https://github.com/ukautz/obsidian-meets-hugo</a>.</p>
<p>I really am happy how I can just re-use my knowledge database, now that I truly own the data that makes it up.</p>
<h3 id="alternatives-to-obsidian">Alternatives to Obsidian</h3>
<p>While researching the matter I also came across other tools, which did not fit my needs as nicely as Obsidian did. However, I might get back to them in the future and they might work for you now:</p>
<ul>
<li><a href="https://joplinapp.org/">Joplin</a> - Open Source, sync via Dropbox / OneDrive / Self-hosted / <a href="https://joplinapp.org/plans/">as-a-service</a>, Markdown, very active community - not for me, because not using Dropbox/OneDrive and dislike SQLite local storage</li>
<li><a href="https://github.com/Zettlr/Zettlr">Zettlr</a> - Open Source, only desktop, Markdown, active community - not for me, because no mobile support (nor sync tooling)</li>
<li><a href="https://1writerapp.com/">1Writer</a> - Paid, Markdown, Mac-only, sync via Dropbox / WebDAV, beautifully simple - not for me since not using Dropbox</li>
<li><strong>Update (2024-01-18)</strong> <a href="https://acreom.com/">Acreom</a> - Limited free for personal use, looks fantastic, desktop &amp; mobile &amp; web, focus on developers and tasks, many integrations with typical OSS &amp; tooling - not for me since I currently work in proprietary environment</li>
</ul>
<p>And some mentions that I looked into, but that are unusable for me as a personal knowledge management tooling due to the data being not or only very hard to extract:</p>
<ul>
<li><a href="https://www.icloud.com/notes">Apple Notes</a> - Same use-case as Google Keep for me</li>
<li><a href="https://evernote.com/">Evernote</a> - Used in the past for same as Keep</li>
<li><a href="https://keep.google.com/">Google Keep</a> - I use if for shopping lists, cooking recipes, ..</li>
<li><a href="https://www.onenote.com/">Microsoft OneNote</a> - Used at work for meeting notes and such</li>
<li><a href="https://www.notion.so/">Notion</a> - good usability</li>
<li><a href="https://roamresearch.com/">Roam</a> - looks nice, pay-to-try</li>
<li><a href="https://simplenote.com/">SimpleNote</a> - web only</li>
</ul>
<h2 id="fin">Fin</h2>
<p>Hope this helps someone else to setup their own personal knowledge management. That&rsquo;s it for now. Cheers from London.</p>
]]></content:encoded></item><item><title>Application Platform as Code</title><link>https://ulrichkautz.com/posts/2021-06-09_application-plaform-as-code/</link><pubDate>Wed, 09 Jun 2021 00:00:00 +0100</pubDate><guid>https://ulrichkautz.com/posts/2021-06-09_application-plaform-as-code/</guid><category>iac</category><category>infrastructure as code</category><category>paas</category><category>platform as a service</category><description>An experiment with Infrastructure as Code and Application Platforms that investigates how both these things can work together, including a prototype library written in Typescript for AWS CDK.</description><content:encoded><![CDATA[<p>To my delight the topic of platforming doesn&rsquo;t seem to let me go. In that context, I recently looked into what&rsquo;s going on in <a href="https://landscape.cncf.io/card-mode?category=scheduling-orchestration&amp;grouping=category">container orchestration</a> these days. Again, I should say.</p>
<p>I&rsquo;ve worked quite a lot with AWS <a href="https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html">EKS</a> and <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html">ECS</a> lately, but it is always interesting to see what&rsquo;s new out there, or just see what other people are doing. As an engineer, you always run at risk to dive too deep into a specific tooling or vendor - or both. Well, it&rsquo;s not really a risk. You know: it&rsquo;s a specialization. And quite fun. It certainly pays well. While Kubernetes tickled me to go down that road again - as I did with other toolings in the past - I am more interested in a different thing, in which container orchestration plays a role, but not the only one.</p>
<p>That different thing I can best describe as an <em>application platform</em>, in lack of a better naming. This term is already in use in multiple contexts. In this article I do have something specific in mind. So for the scope of this article, an application platform consists of:</p>
<ol>
<li><strong>An application runtime</strong>, that is an environment in which applications, that may be addressable, can be started in</li>
<li><strong>An ecosystem of components</strong>, access to one I mean; whatever the applications require, like databases or data lakes or whatnot, so they can do what they do</li>
<li><strong>An interface</strong> to instrument all the above, that means lifecycle management of applications and code deployment of application versions and that can be used by 3rd parties</li>
</ol>
<p>As one image tells more than a thousand words, here is a diagram. That must help even more. You decide:</p>
<p><img src="https://ulrichkautz.com/img/posts/application-platform.high-level.png#float-right,limited-width" alt="Application Platform"></p>
<h2 id="an-old-friend">An Old Friend</h2>
<p>This pattern is not new at all. I think it keeps following me around. Or am I chasing it? Either way. The first time I engaged with it was at the beginning of my career in tech. I was working in web hosting, mail hosting and related services.</p>
<p>Looking back at that time, the early 2000s, I can&rsquo;t help but seeing the same pattern. Sure, nobody was speaking about application platforms back when. Certainly not me. It was plain web hosting, marketed under poetic names like <em>&ldquo;Web XXL: 123 domains, 10 GB Storage, PHP and MySQL - only $1.99&rdquo;</em>. Fun times. Either way, the shoe fits:</p>
<ul>
<li>a (specialized) runtime (here: PHP, before that CGI, later other scripting languages)</li>
<li>the right ecosystem (MySQL and so forth)</li>
<li>an interface - well multiple - for deployment (FTP 😳) and lifecycle management (some website in essence)</li>
</ul>
<p>I would call that a specialized application platform nowadays.</p>
<p>In the 2010s the <a href="https://en.wikipedia.org/wiki/Infrastructure_as_a_service">IaaS</a> vs <a href="https://en.wikipedia.org/wiki/Platform_as_a_service">PaaS</a> vs <a href="https://en.wikipedia.org/wiki/Software_as_a_service">SaaS</a> framing became a thing. PaaS is another implementation of the application platform pattern. Compared to earlier approaches, PaaS increased the range of offered runtime specializations vastly. They rethought usability, with new developer focused CLI based lifecycle management and deployment tooling. And of course: everything now had an API. Either way, still the same pattern.</p>
<p>Towards the end of the last decade, I left public hosting - by then called public PaaS - and entered private company country. What I didn&rsquo;t leave, what stuck around was the pattern of course. Again there are developers, which need to run their applications. Resulting from that, an ecosystem providing peripherals for those applications is required. And of course some kind of interface to deploy code and manage lifecycle must be available as well. From what I can tell, every tech company out their has their variant of that. Assuming they have enough application developers around to merit any kind of standardization. There must be thousands of variants and implementations.</p>
<h2 id="an-experiment">An Experiment</h2>
<p>Ok, so where does Infrastructure as Code (IaC) comes in then? Well, it&rsquo;s a topic that I am deeply engaged with currently. As I am with application platforms. So here we are. I also have a hunch, this could mean less time with enormous YAML files in the future. So it&rsquo;s worth looking deeper into!</p>
<p>It makes great sense from where I am standing. That is: environments, in which many developers collaborate and work with (cloud) infrastructure directly. So everybody is using IaC already, meaning introducing external things (like an open source PaaS or such, that &ldquo;leave the IaC ecosystem&rdquo;) is not ideal. Having an application platform managed from the same code that also defines all (the other) resources seems a good idea. If just to have one less context switch.</p>
<p>I also figure that there is a minor paradigm shift ahead. Right now, IaC is used to provision and manage (cloud) infrastructure resources. Those are mostly primitive resources. I mean things like a virtual machine of certain proportions, tcp load balancers, a DNS zone with records. The kind of stuff APIs of the infrastructure provider have in stock (<a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html">1</a>, <a href="https://registry.terraform.io/search/providers">2</a>). In the future, I imagine, IaC will be mainly used to provision and manage high level patterns. Or maybe not mainly, but also. Either way, how that could look like with whole application platforms, is my question.</p>
<p>Before getting into the details here some assumptions I am making - based on my own situation, but also from what I am reading and seeing others do:</p>
<ol>
<li><em>Resources can be managed via IaC</em>: This experiment is limited to (cloud) infrastructures, that provide APIs for which an IaC implementation is available.</li>
<li><em>IaC is best practice</em>: Describing infrastructure in code is the (current) best way to run and maintain infrastructure.</li>
<li><em>People are familiar with IaC</em>: Many engineers in the field are already knowledgeable with IaC. Both the general concept and specific implementations. This came as a byproduct / consequence of DevOps et al.</li>
</ol>
<p>To boil down the the idea under investigation into a single sentence:</p>
<blockquote>
<p><em>Can a useful, production grade application platform be build using <strong>only</strong> Infrastructure as Code?</em></p>
</blockquote>
<h3 id="iac--iac">IaC ≠ IaC</h3>
<p>To clarify what I mean, I need to elaborate a bit on the state of IaC, as I see it. If you follow my blog you might have read my <a href="https://ulrichkautz.com/posts/2021-02-21_why-i-like-aws-cdk/">recent article</a> in which I dove deeper into what&rsquo;s going on with IaC lately. In short my findings: Where IaC used to be writing ginormous YAML files (or akin), it progressed to writing actually unit-testable code in a high level languages like Typescript, Python, etc - with all that comes with that in terms of modularization, actual control statements, arbitrary code execution and so forth.</p>
<p>So when I am speaking about IaC in this article, I am referring to this latest iteration. Like <a href="https://github.com/aws/aws-cdk">AWS CDK</a> or <a href="https://www.pulumi.com/">Pulumi</a> or - coming soon - <a href="https://github.com/hashicorp/terraform-cdk">Terraform CDK</a>. Basically any IaC framework, that provides the following properties:</p>
<ul>
<li><strong>Constructs</strong>, that is infrastructure resources as complex types (=construct) in the respective higher level language</li>
<li><strong>Composition</strong> of constructs from other constructs</li>
<li><strong>Modularization</strong> of re-usable code</li>
</ul>
<h4 id="kinds-of-constructs">Kinds of Constructs</h4>
<p>One more tidbit, that helps in discussion and framing of thought is to agree on names for the different &ldquo;kinds&rdquo; of constructs there are. <a href="https://docs.aws.amazon.com/cdk/latest/guide/constructs.html">Amazon came up with a grouping / naming scheme</a>, that I&rsquo;d like to rephrase a bit to make it independent of a (their) specific implementation:</p>
<div class="spaced-list">
<ul>
<li><strong>Level 1 Constructs (L1)</strong>: Low level infrastructure constructs, which have the interface that is defined by the infrastructure provider. To use them you must be deeply familiar with the resources offered by a particular infrastructure (provider). It exposes all possible functionality at the price of high complexity - and often awkwardness, given that this interface was not designed for immediate high level programming language usage.
<ul>
<li><em>Example</em>: <a href="https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.CfnBucket.html">(S3) <code>CfnBucket</code></a> matching the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html">S3 Bucket CloudFormation YAML</a>.</li>
</ul>
</li>
<li><strong>Level 2 Constructs (L2)</strong>: Higher level infrastructure constructs, that have a convenient interface, easy to use in higher level language with the least amount of boilerplate, good sensible defaults and easy to combine with other infrastructure constructs. L2 is kind of an &ldquo;adapter layer&rdquo;, hiding away the grizzly L1, which was not designed for usage in higher level languages.
<ul>
<li><em>Example 1</em>: <a href="https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html">(S3) <code>Bucket</code></a>, in a higher level than before.</li>
<li><em>Example 2</em>: <a href="https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr_assets.DockerImageAsset.html"><code>DockerImageAsset</code></a> that represents a Docker (container) image.</li>
</ul>
</li>
<li><strong>Level 3 Constructs (L3)</strong>: Logical infrastructure constructs, that are composed of L2 (or L1 or both or other L3 etc) infrastructure constructs to implement complex patterns. That can be as easy as wrapping two L1/2 constructs together or any complicated pattern composed of any number of things:
<ul>
<li><em>Example 1</em>: Simple <a href="https://docs.aws.amazon.com/solutions/latest/constructs/aws-s3-lambda.html">Lambda with an S3 bucket together</a>)</li>
<li><em>Example 2</em>: Complex <a href="https://github.com/ukautz/aws-cdk-static-website">static website hosting consisting of CloudFront, S3 and Route53 constructs</a></li>
</ul>
</li>
</ul>
</div>
<p>At the risk of repeating myself: While I was using only AWS CDK in the examples above, the L1-3 grouping is by no means only applicable to this framework. Any IaC framework that provides L1 and/or L2 constructs and allows you to (easily!) construct L3 constructs from them suffices:</p>
<ul>
<li>Terraform CDK allows you do use any <a href="https://registry.terraform.io/browse/providers">existing &ldquo;regular&rdquo; Terraform provider</a>, or rather compile the HCL definitions of those providers into constructs in your respective language (say Typescript). If you have a look at some <a href="https://github.com/hashicorp/terraform-cdk/tree/main/examples/typescript">usage examples</a> you might agree they look like L1 constructs (that is: they have a powerful, but awkward, low-level interface). This of course means L3 could be constructed from them with ease.</li>
<li>Pulumi&rsquo;s constructs I&rsquo;d probably consider more L2 than L1, but then again. Look at <a href="https://www.pulumi.com/docs/reference/pkg/aws/s3/bucket/">their API</a> and judge for yourself</li>
</ul>
<h3 id="preparation">Preparation</h3>
<p>Before going into any implementation, let&rsquo;s check against the requirements from the top. That should elaborate on what is missing, what needs to be implemented so that an application platform in pure AWS CDK can be created.</p>
<h4 id="requirement-an-application-runtime">Requirement: An Application Runtime</h4>
<p>For an application runtime, we need to define what an application is. Again, a general purpose runtime that runs truly everything is out of the question. Let&rsquo;s keep it simple - but not too far from the real world - this is an experiment after all.</p>
<div class="gimmic check todo"></div>
<p><strong>Application</strong>: I started this article with container orchestration and I think that is a good starting point here as well. Let&rsquo;s say an application is encapsulated in a container. Docker, to make it specific. That comes with a few standard concerns when using containers: exposed port, environment variables, resource sizing, etc. Also, as that is simply standard by now, there should be some resource based auto-scaling available. That is already not bad. If an application is supposed to be everything (within reason) that we can box into a container and that can have an exposed network port, then about every HTTP service would already &ldquo;work&rdquo;. Let&rsquo;s go with that.</p>
<div class="gimmic check todo"></div>
<p><strong>Runtime</strong>: The container based definition makes it also quite easy regarding the runtime. AWS offers two kind of container orchestrations: EKS (managed Kubernetes) and ECS (managed, proprietary container orchestrator). Both would do for an experiment. Sure, I could run Nomad or something on EC2 instances, tho I gonna stick with the managed services.</p>
<h4 id="requirement-an-ecosystem-of-components">Requirement: An Ecosystem of Components</h4>
<div class="gimmic check ok"></div>
<p>We already got that, luckily. When using AWS CDK, we can use all the resources AWS provides, as long as the implementation of the previous Application and Runtime definitions do not interfere with that. In short: As long as I don&rsquo;t screw it up, we have a huge ecosystem available.</p>
<h4 id="requirement-an-interface">Requirement: An Interface</h4>
<p>That is also already in place. AWS CDK itself is that interface, both for deployment and for lifecycle management.</p>
<div class="gimmic check ok"></div>
<p><strong>Lifecycle management</strong>: That is kind of obvious I guess. As the AWS resources are defined from AWS CDK that also manages their lifecycle. Done.</p>
<div class="gimmic check ok"></div>
<p><strong>Deployment</strong>: As we agreed that basically anything dockerized is an application, the <a href="https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr_assets.DockerImageAsset.html"><code>DockerImageAsset</code></a> from the <a href="https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ecr_assets-readme.html">aws_ecr_assets</a> library can be easily used to reference a local <code>Dockerfile</code> and then build and upload that during deployment. Good enough for my experiment.</p>
<h3 id="drafting-an-outline">Drafting an Outline</h3>
<p>Ok, with the outcome from the above, we&rsquo;re left with needing that Runtime and Application available as (L3) constructs in AWS CDK. With that goal, I like to start with a quick draft of (pseudo-)Typescript code, to outline what needs to be created. I&rsquo;ll try to keep the Typescript and AWS CDK boilerplate low, sometimes only hint to it, to make it readable for anyone. The most interesting part will be the interfaces, that is the configuration properties of the constructs. These describe functionality the L3 implementations will need to provide.</p>
<p>First in plain English. What am I expecting to end up with when running <code>cdk deploy</code>? Something in between a user story and acceptance criteria, if you will:</p>
<div class="box-note spacer-end">
<ul>
<li>A compute environment, that can run docker images, is created (e.g. container orchestrator) -&gt; <strong>Application Runtime</strong></li>
<li>A container image is created from a defined directory <code>/path/to</code> that contains a <code>Dockerfile</code> -&gt; <strong>Interface (Deployment)</strong></li>
<li>A service runs, that uses the uploaded docker image, with all requested resources (cpu, memory) -&gt; <strong>Interface (Lifecycle)</strong></li>
<li>The running service is addressable (<code>https://my-app.public.domain/</code>) -&gt; <strong>Application Runtime</strong></li>
<li>A SQL database is running, that the service can use -&gt; <strong>Ecosystem</strong></li>
</ul>
</div>
<p>This is very superficial of course. That makes the sample code also shorter and better to understand. I hope:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#080;font-style:italic">// here would be import of all the things, then:
</span></span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">class</span> Stack <span style="color:#a2f;font-weight:bold">extends</span> cdk.Stack {
</span></span><span style="display:flex;"><span>  <span style="color:#a2f;font-weight:bold">constructor</span>(scope: <span style="color:#0b0;font-weight:bold">cdk.Construct</span>, id: <span style="color:#0b0;font-weight:bold">string</span>, props?: <span style="color:#0b0;font-weight:bold">cdk.StackProps</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">super</span>(scope, id, props);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// create the runtime, within which the application will run
</span></span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">const</span> runtime <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> Runtime(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;RuntimeCluster&#39;</span>, {
</span></span><span style="display:flex;"><span>      
</span></span><span style="display:flex;"><span>      <span style="color:#080;font-style:italic">// make the suffix, the namespace the same for all things running inside
</span></span></span><span style="display:flex;"><span>      domain<span style="color:#666">:</span> <span style="color:#b44">&#39;public.domain&#39;</span>,
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>      <span style="color:#080;font-style:italic">// + AWS specific options, like VPC? Availability Zones? Timeouts? etc
</span></span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// create the actual application
</span></span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">const</span> application <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> Application(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;RuntimeApplication&#39;</span>, {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>      <span style="color:#080;font-style:italic">// reference the runtime to run in - application and clusters should
</span></span></span><span style="display:flex;"><span>      <span style="color:#080;font-style:italic">// also be creatable in independent stacks, even entirely independent
</span></span></span><span style="display:flex;"><span>      <span style="color:#080;font-style:italic">// CDK apps... problem for later
</span></span></span><span style="display:flex;"><span>      runtime: <span style="color:#0b0;font-weight:bold">runtime</span>,
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>      <span style="color:#080;font-style:italic">// so we can speak about it
</span></span></span><span style="display:flex;"><span>      <span style="color:#080;font-style:italic">//  Someone: the hamster is down!
</span></span></span><span style="display:flex;"><span>      <span style="color:#080;font-style:italic">//  Someone Else: oh no, not the hamster!
</span></span></span><span style="display:flex;"><span>      <span style="color:#080;font-style:italic">// true story
</span></span></span><span style="display:flex;"><span>      name<span style="color:#666">:</span> <span style="color:#b44">&#39;my-app&#39;</span>,
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>      <span style="color:#080;font-style:italic">// that path in which that Dockerfile is
</span></span></span><span style="display:flex;"><span>      code<span style="color:#666">:</span> <span style="color:#b44">&#39;/path/to&#39;</span>,
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>      <span style="color:#080;font-style:italic">// the resources - unsure yet what the ideal structure would be
</span></span></span><span style="display:flex;"><span>      resources<span style="color:#666">:</span> <span style="color:#b44">&#39;cpu 1, memory: 512&#39;</span>,
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// this is very pseudo - look here for an actual AWS CDK example:
</span></span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">//  https://docs.aws.amazon.com/cdk/api/latest/docs/aws-rds-readme.html
</span></span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">const</span> database <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> Database(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;Database&#39;</span>, {
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>      <span style="color:#080;font-style:italic">// dummy properities, showcasing a SQL database being provisioned
</span></span></span><span style="display:flex;"><span>      engine<span style="color:#666">:</span> <span style="color:#b44">&#39;mysql&#39;</span>,
</span></span><span style="display:flex;"><span>      resources<span style="color:#666">:</span> <span style="color:#b44">&#39;cpu: 1, memory: 1024, storage: 10&#39;</span>,
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// the application should be able to access things in the ecosystem
</span></span></span><span style="display:flex;"><span>    database.grantAccess(application);
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>That looks usable, as in: Not too much boilerplate, I can imagine maintaining that. So I believe for now the interfaces are sensible enough. I guess they contain all the information that is required to satisfy the above acceptance criteria.</p>
<p>There are a couple of things that come to mind:</p>
<ul>
<li><em>Use as an Application Platform</em>: To make that happen, I would likely deploy the Runtime once or more (stages?) per AWS account, then everyone with access to that account can deploy Applications there. So there must be an easy way to reference a deployed Runtime from the Stack that defines the Application.</li>
<li><em>Cost</em>: There are a couple of ways to shape the costs. Like dedicated load balancer per application vs shared and such. NATting can also increase cost. Thinking of cheap development environments vs reliable production. Lots of room for tuning configuration.</li>
<li><em>Access management</em>: As showcased in the bottom of the draft, there needs to be a &ldquo;natural&rdquo; way to integrate with the ecosystem. Also in between services.</li>
<li><em>Scaling conditions</em>: These services should be able to scale, based on load. The conditions in which that happens should be describable in the interface.</li>
<li><em>Persistent vs Scheduled Executions</em>: To simplify, there will be things that run all the time, like web service, and things that are scheduled at some times, like reporting or such. Both should work. Maybe split Application into two related constructs?</li>
</ul>
<p>I am sure you can think of more, and so will I in the implementation.</p>
<h2 id="prototype">Prototype</h2>
<p>So I wrote something: <a href="https://github.com/ukautz/aws-cdk-app-runtime">https://github.com/ukautz/aws-cdk-app-runtime</a></p>
<p>It&rsquo;s not the minimalistic Proof-of-Concept (PoC) I imagined initially. Since I am doing this in my own time, I often end up in such excursions looking into multiple topics that interest me. In this case, among other things: <a href="https://doc.traefik.io/traefik/">Traefik</a>. I wanted to put that to use for a while and see how it runs. Now I did and therefore the traffic routing of my PoC became more opinionated. Ok, before jumping too much into details, let me show you some code and then elaborate a bit on how I can imagine it can be used.</p>
<h3 id="show-me-the-code">Show me the code</h3>
<p>To compare against the above draft outline, here the respective actual code that implements the user story:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdk <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { DatabaseInstance, DatabaseInstanceEngine, MysqlEngineVersion } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/aws-rds&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { Port } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/aws-ec2&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { Cluster, Service, Resources } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@ukautz/aws-cdk-app-runtime&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> path <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;path&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">export</span> <span style="color:#a2f;font-weight:bold">class</span> MinimalStack <span style="color:#a2f;font-weight:bold">extends</span> cdk.Stack {
</span></span><span style="display:flex;"><span>  <span style="color:#a2f;font-weight:bold">constructor</span>(scope: <span style="color:#0b0;font-weight:bold">cdk.Construct</span>, id: <span style="color:#0b0;font-weight:bold">string</span>, props?: <span style="color:#0b0;font-weight:bold">cdk.StackProps</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">super</span>(scope, id, props);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">const</span> publicDomain <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">this</span>.node.tryGetContext(<span style="color:#b44">&#39;publicDomain&#39;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">if</span> (<span style="color:#666">!</span>publicDomain) {
</span></span><span style="display:flex;"><span>      <span style="color:#a2f;font-weight:bold">throw</span> <span style="color:#a2f;font-weight:bold">new</span> <span style="color:#a2f">Error</span>(<span style="color:#b44">&#39;missing publicDomain in context&#39;</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">const</span> cluster <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> Cluster(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;Cluster&#39;</span>, {
</span></span><span style="display:flex;"><span>      publicDomain,
</span></span><span style="display:flex;"><span>      privateDomain: <span style="color:#0b0;font-weight:bold">this.node.tryGetContext</span>(<span style="color:#b44">&#39;privateDomain&#39;</span>) <span style="color:#666">??</span> <span style="color:#b44">&#39;service.local&#39;</span>,
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">const</span> service <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> Service(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;WebApp&#39;</span>, {
</span></span><span style="display:flex;"><span>      cluster,
</span></span><span style="display:flex;"><span>      image<span style="color:#666">:</span> <span style="color:#b44">&#39;path:&#39;</span> <span style="color:#666">+</span> path.join(__dirname, <span style="color:#b44">&#39;..&#39;</span>),
</span></span><span style="display:flex;"><span>      name<span style="color:#666">:</span> <span style="color:#b44">&#39;my-app&#39;</span>,
</span></span><span style="display:flex;"><span>      <span style="color:#a2f;font-weight:bold">public</span><span style="color:#666">:</span> <span style="color:#a2f;font-weight:bold">true</span>,
</span></span><span style="display:flex;"><span>      resources: <span style="color:#0b0;font-weight:bold">Resources.fromString</span>(<span style="color:#b44">&#39;cpu: 256, memory: 512, min: 2, max: 10, target_cpu: 50&#39;</span>),
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">const</span> database <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> DatabaseInstance(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;Database&#39;</span>, {
</span></span><span style="display:flex;"><span>      engine: <span style="color:#0b0;font-weight:bold">DatabaseInstanceEngine.mysql</span>({
</span></span><span style="display:flex;"><span>        version: <span style="color:#0b0;font-weight:bold">MysqlEngineVersion.VER_8_0_23</span>,
</span></span><span style="display:flex;"><span>      }),
</span></span><span style="display:flex;"><span>      vpc: <span style="color:#0b0;font-weight:bold">cluster.vpc</span>,
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>    database.connections.allowFrom(service, Port.tcp(<span style="color:#666">3306</span>));
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>I think that doesn&rsquo;t look too different from the outline. Especially in terms of simplicity (aside from that database <em>cough</em>), it seems to be not to cumbersome.</p>
<p>The resource and scaling claims <code>cpu: 256, memory: 512, min: 2, max: 10, target_cpu: 50</code> from the draft I liked and came back to it. It reads like this: <em>256 CPU shares (with 1024 being &ldquo;one full CPU&rdquo;), 512 MiB of memory, run at least 2 and at most 10 instances. Scale based on CPU consumption, keep it around 50%</em>.</p>
<p>There is internal form, shaped by complex types, that would look <a href="https://github.com/ukautz/aws-cdk-app-runtime/blob/v1.108.0-alpha1/lib/util/resources.ts#L6-L26">like this</a>:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>  cpu: <span style="color:#0b0;font-weight:bold">256</span>,
</span></span><span style="display:flex;"><span>  memory: <span style="color:#0b0;font-weight:bold">512</span>,
</span></span><span style="display:flex;"><span>  scaling<span style="color:#666">:</span> {
</span></span><span style="display:flex;"><span>    mode<span style="color:#666">:</span> <span style="color:#b44">&#39;scaling&#39;</span>,
</span></span><span style="display:flex;"><span>    minCapacity: <span style="color:#0b0;font-weight:bold">2</span>,
</span></span><span style="display:flex;"><span>    maxCapacity: <span style="color:#0b0;font-weight:bold">10</span>,
</span></span><span style="display:flex;"><span>    thresholds<span style="color:#666">:</span> [{ resource<span style="color:#666">:</span> <span style="color:#b44">&#39;cpu&#39;</span>, target: <span style="color:#0b0;font-weight:bold">50</span> }],
</span></span><span style="display:flex;"><span>  },
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>The string form can be easily provided as a <code>--context</code> parameter to execution, so I mostly use that, especially when test deploying services from the command line. Check the <a href="https://github.com/ukautz/aws-cdk-app-runtime/blob/v1.108.0-alpha1/test/util/resources.test.ts#L140-L203">tests for examples</a>.</p>
<p>If you want to see more code, there is an <a href="https://github.com/ukautz/aws-cdk-app-runtime/tree/main/example">example in the library</a>, which implements a simplistic uptime / status tooling for HTTP URLs. It consists of one scheduled service, that queries the URLs and persists metrics in a DynamoDB database, showing of how to integrate with other AWS constructs. This database is then queried by a web application, that can render those metrics in graphs or provide them via a REST JSON API. To show off public / private access, this web app is not accessible from the outside, but made available by yet another service: a proxy app.</p>
<h3 id="big-picture">Big Picture</h3>
<p><img src="https://ulrichkautz.com/img/posts/application-runtime.aws-overview.png#float-right,limited-width" alt="Routing Decision"></p>
<p>A rough picture of the implementation.</p>
<p>The core of the Runtime, the <strong>Cluster</strong>, is implemented using <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html">AWS ECS (Fargate)</a>. So there run the docker images that are stored in <a href="https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html">ECR</a> during deploying with <a href="https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html#bootstrapping-templates">AWS CDK</a>.</p>
<p>There is no good reason why I didn&rsquo;t go with with EKS. Might do that next. Also using managed EKS or even running any custom orchestrator on EC2 instances should be doable. I might have tried <a href="https://docs.aws.amazon.com/apprunner/latest/dg/what-is-apprunner.html">AppRunner</a>, but that is still <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/aws-apprunner-readme.html">only Level 1</a> at the time of writing. We&rsquo;ll see.</p>
<p><strong>Services</strong> are continuously running applications. They can be addressed under a shared public domain <code>https://some-service.public.domain/</code> and/or, only from within the VPC, via a shared private domain <code>http://some-service.private.domain/</code>. The public domain is routed to an <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html">ALB</a> (<code>*.public.domain</code>), which routes all requests to a service that runs <a href="https://doc.traefik.io/traefik/v2.4/">Traefik</a>, which routes the traffic to instances of the named service. Internal routing is done via <a href="https://docs.aws.amazon.com/cloud-map/latest/dg/what-is-cloud-map.html">Cloud Map</a> (service discovery in AWS orchestration).  Provided resources, CPU and memory, can be set. Services can run in fixed amounts or scale based on resource consumption.</p>
<p><strong>Scheduled Tasks</strong> are applications that are executed at specified intervals (crontab, rate). They can access Services, but not vice versa. Runs only as long as execution lasts. Provided resources, CPU and memory, can be set. Concurrency for execution can be configured.</p>
<p>Everybody can access things in the AWS ecosystem.</p>
<h3 id="real-world-applicable">Real world applicable?</h3>
<p>Yes, I think the approach is sound in principle and integrates nicely with the ecosystem. Not necessarily my experimental implementation, mind you. Since I used my private AWS account, I tried to keep costs low - aside from rare times of simple load testing. So I made decisions, which complicated things, but allowed me to run everything cheaper.</p>
<p>However, if you are using IaC already strongly, I think this approach should be of real interest to you. As with everything, there are advantages and disadvantages. Read on and decide for yourself.</p>
<h4 id="use-as-application-platform">Use as Application Platform</h4>
<p>This interests me most, of course. In short: When using AWS CDK anyway, this approach seems a good idea. Modularization of higher level patterns into (Level 3) constructs, that standardize &amp; simplify re-use, I mean. Even embedding (if only minimal configured) custom services - like I did with Traefik here - seems not to hard. Integration with other resources from the ecosystem (AWS) is nicely solved, e.g. through interfaces like <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.IConnectable.html">IConnectable</a> or <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-iam.IGrantable.html">IGrantable</a>.</p>
<p>One requirement in that context is to account for separate maintainers / owners of the runtime (the cluster with routing and all) and the installed services (the business applications). Context is of course to provide standardized infrastructure, a platform, to a lot of developers, which share requirements (company, same market, programming framework, many things). It seems that can be solved, if tho it feels a bit hack. See below for how I did that.</p>
<p>I also don&rsquo;t see conflict with using it in a multi tenant / team situation. There could be one or multiple concurrent Cluster installed per AWS account, or across accounts. It depends then more on the connection of the networking, how the VPCs are setup, peered, routed, filtered etc. Security groups can be used additionally. No conflict with multi region either.</p>
<p>A negative experience was the deployment to ECS Fargate. Same as with &ldquo;regular&rdquo; ECS, to my experience. It is annoyingly slow, especially for the high frequent deployments I did, when tinkering with my proof of concept. Although, I understand that&rsquo;s done for availability and rollbacks&rsquo; sake, it still wasn&rsquo;t enjoyable to wait so long.</p>
<p>There are of course also limits of this approach. The interfaces of the constructs must be sufficiently simple to be useful and maintainable. That constraints the possible applications and can / will make implementations opinionated for specific use-cases. I have a gazillion Kubernetes manifests in mind here..</p>
<h5 id="regarding-the-separation-of-runtime-and-applications">Regarding the separation of runtime and applications</h5>
<p>I went with <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html">SSM parameters</a> as the transport / storage. It then works like that:</p>
<ul>
<li><strong>Cluster Stack</strong>, maintained by platformers, deploys the runtime and stashes all relevant information of the deployed Cluster (the &ldquo;cluster specs&rdquo;) in SSM with a well known prefix (<code>/&lt;prefix&gt;/&lt;parameter..&gt;</code>)</li>
<li><strong>Application Stack(s)</strong>, maintained by developers, reads the stored parameters from SSM and has all the information required to deploy their applications into the runtime.</li>
</ul>
<p>This satisfies the requirements for the moment. The &ldquo;Systems Manager Parameter Store&rdquo; seems a good choice, just going by the name ;) Whether it actually is, I guess time will tell.</p>
<p>I did not consider access constraints for those SSM parameters for the moment - but that could be done via IAM of course.</p>
<p>Either way, here is how you use it:</p>
<blockquote>
<p>CDK application deploying the cluster</p>
</blockquote>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdk <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { Cluster, ClusterSpecs } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@ukautz/aws-cdk-app-runtime&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// define stack
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">class</span> ClusterStack <span style="color:#a2f;font-weight:bold">extends</span> cdk.Stack {
</span></span><span style="display:flex;"><span>  <span style="color:#a2f;font-weight:bold">constructor</span>(scope: <span style="color:#0b0;font-weight:bold">cdk.Construct</span>, id: <span style="color:#0b0;font-weight:bold">string</span>, props?: <span style="color:#0b0;font-weight:bold">cdk.StackProps</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">super</span>(scope, id, props);
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// create the cluster in this stack
</span></span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">const</span> cluster <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> Cluster(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;Cluster&#39;</span>, {
</span></span><span style="display:flex;"><span>      publicDomain<span style="color:#666">:</span> <span style="color:#b44">&#39;public.domain&#39;</span>,
</span></span><span style="display:flex;"><span>      privateDomain<span style="color:#666">:</span> <span style="color:#b44">&#39;private.domain&#39;</span>,
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// write the specs (properties) of the cluster to SSM
</span></span></span><span style="display:flex;"><span>    ClusterSpecs.toSsm(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;/namespace/&#39;</span>, cluster.specs);
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// create stack
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span> app <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> cdk.App();
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">new</span> ClusterStack(app, <span style="color:#b44">&#39;Cluster&#39;</span>, {
</span></span><span style="display:flex;"><span>  env<span style="color:#666">:</span> {
</span></span><span style="display:flex;"><span>    account: <span style="color:#0b0;font-weight:bold">process.env.CDK_DEFAULT_ACCOUNT</span>,
</span></span><span style="display:flex;"><span>    region: <span style="color:#0b0;font-weight:bold">process.env.CDK_DEFAULT_REGION</span>,
</span></span><span style="display:flex;"><span>  },
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><blockquote>
<p>CDK application deploying a set of services and scheduled tasks in the cluster</p>
</blockquote>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdk <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { Service, ClusterSpecs} <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@ukautz/aws-cdk-app-runtime&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// define stack
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">class</span> ApplicationsStack <span style="color:#a2f;font-weight:bold">extends</span> cdk.Stack {
</span></span><span style="display:flex;"><span>  <span style="color:#a2f;font-weight:bold">constructor</span>(scope: <span style="color:#0b0;font-weight:bold">cdk.Construct</span>, id: <span style="color:#0b0;font-weight:bold">string</span>, props?: <span style="color:#0b0;font-weight:bold">cdk.StackProps</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">super</span>(scope, id, props);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// load from cluster stored specs from SSM
</span></span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">const</span> clusterSpecs <span style="color:#666">=</span> ClusterSpecs.fromSsm(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;/namespace/&#39;</span>);
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// create some services in existing cluster
</span></span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">new</span> Service(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;Foo&#39;</span>, {
</span></span><span style="display:flex;"><span>      cluster: <span style="color:#0b0;font-weight:bold">clusterSpecs</span>,
</span></span><span style="display:flex;"><span>      image<span style="color:#666">:</span> <span style="color:#b44">&#39;path:&#39;</span> <span style="color:#666">+</span> path.join(__dirname, <span style="color:#b44">&#39;..&#39;</span>, <span style="color:#b44">&#39;foo&#39;</span>),
</span></span><span style="display:flex;"><span>      name<span style="color:#666">:</span> <span style="color:#b44">&#39;foo&#39;</span>,
</span></span><span style="display:flex;"><span>      <span style="color:#a2f;font-weight:bold">public</span><span style="color:#666">:</span> <span style="color:#a2f;font-weight:bold">true</span>,
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// create some other services in existing cluster
</span></span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">new</span> Service(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;Bar&#39;</span>, {
</span></span><span style="display:flex;"><span>      cluster: <span style="color:#0b0;font-weight:bold">clusterSpecs</span>,
</span></span><span style="display:flex;"><span>      image<span style="color:#666">:</span> <span style="color:#b44">&#39;path:&#39;</span> <span style="color:#666">+</span> path.join(__dirname, <span style="color:#b44">&#39;..&#39;</span>, <span style="color:#b44">&#39;foo&#39;</span>),
</span></span><span style="display:flex;"><span>      name<span style="color:#666">:</span> <span style="color:#b44">&#39;foo&#39;</span>,
</span></span><span style="display:flex;"><span>      <span style="color:#a2f;font-weight:bold">public</span><span style="color:#666">:</span> <span style="color:#a2f;font-weight:bold">true</span>,
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// create stack
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span> app <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> cdk.App();
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">new</span> ApplicationsStack(app, <span style="color:#b44">&#39;Cluster&#39;</span>, {
</span></span><span style="display:flex;"><span>  env<span style="color:#666">:</span> {
</span></span><span style="display:flex;"><span>    account: <span style="color:#0b0;font-weight:bold">process.env.CDK_DEFAULT_ACCOUNT</span>, <span style="color:#080;font-style:italic">// &lt;&lt; for ssm, reading from which
</span></span></span><span style="display:flex;"><span>    region: <span style="color:#0b0;font-weight:bold">process.env.CDK_DEFAULT_REGION</span>,   <span style="color:#080;font-style:italic">// &lt;&lt; account &amp; where?
</span></span></span><span style="display:flex;"><span>  },
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><h4 id="routing">Routing</h4>
<p><img src="https://ulrichkautz.com/img/posts/application-runtime.routing.png#float-right,limited-width" alt="Routing Decision"></p>
<p>There are many approaches to expose the running services. In AWS you usually use a <a href="https://docs.aws.amazon.com/elasticloadbalancing/index.html">load balancer (ALB, ELB, ..)</a> to expose services, that run on multiple instances (ere: in ECS). One initial decision was whether to dedicate such load balancer resources per service or use a shared routing layer. The shared could be a SPOF, bottleneck, etc and adds latency. I still went with it. For $$ reasons, but also Traefik.</p>
<p>All public services are then addressable by their public service address <code>name.public.domain</code>. Internally, that means:</p>
<ul>
<li><code>*.public.domain</code> is routed via Route53 to an ALB</li>
<li>The ALB routes all traffic to an ECS Service running Traefik</li>
<li>Traefik routes - based on the prefix (<code>name</code>) of the public domain (<code>name.public.domain</code>) - to ECS tasks (i.e. the running container instances of the service)</li>
</ul>
<p>One nugget: The Cluster has a parameter for a secret request header + value. Intended use case: behind CloudFront.</p>
<p>For private traffic routing, when addresses like <code>http://name.private.domain/</code> are accessed from within the VPC, the implementation looks different. I wanted to see how Cloud Map works for service discovery. It works. Instead of an ALB (which could / should? be used in between) the address name resolution returns in turn each IP (<a href="https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-servicediscovery.RoutingPolicy.html#weighted">random aka WEIGHTED</a>) of the instances (tasks) of the service. Unsure if that will work like a round robin(&lsquo;ish) - or not. Experimental, is my excuse.</p>
<p>Related to this is the outgoing traffic. Per default, all egress is permitted (could be modified, I didn&rsquo;t have that use-case). The standard / best-practices in AWS here is to use <a href="https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html">NAT gateways</a>. This is done per default in my implementation, but can be modified to use <a href="https://docs.aws.amazon.com/vpc/latest/userguide/VPC_NAT_Instance.html">NAT instances</a> instead. That can make the whole setup way cheaper, but also adds SPOFs! See a <a href="https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-comparison.html">comparison here</a>.</p>
<h2 id="outro">Outro</h2>
<p>That was fun. Anyway, this is just a PoC, an experiment for now. I would be exited to do the same with Terraform CDK. Once it&rsquo;s stable enough. Also Application Runtime as Code is just one pattern expressed in (L3) constructs. There are others. <em>Would a higher level framework make sense?</em> Well, it would be certainly very interesting to look into.</p>
]]></content:encoded></item><item><title>On the Value of Platform Engineering</title><link>https://ulrichkautz.com/posts/2021-03-11_value-of-platforming-engineering/</link><pubDate>Thu, 11 Mar 2021 00:00:00 +0000</pubDate><guid>https://ulrichkautz.com/posts/2021-03-11_value-of-platforming-engineering/</guid><description>My attempt to define what Platform Engineering means for me and what value it brings if employed.</description><content:encoded><![CDATA[<p>I have been working as a Platform Engineer for a few years now. I like my work, I am passionate about it. Aside from the toil&hellip; unless I can automate it, then I am happy too. In this article, I&rsquo;d like to discuss the merits that my particular specialization brings to the table. The Platform Engineer role is still somewhat new and therefore it is not widely agreed upon what the role entails and thereby what value it provides. I wouldn&rsquo;t be surprised if you&rsquo;d ask three people with opinions on the matter that you&rsquo;d get four answers - at least in the details. Further, as Platform Engineering is close to infrastructure, there is no immediate and obvious value visible, as, say, Frontend Engineering would be able to show.</p>
<p>Either way, my real motivation is to clarify my own thoughts on the matter and writing helps me in the process.</p>
<p>Since I am working exclusively within cloud infrastructures these days, all my arguments and mentioning of infrastructure resources should be seen in that context; although I guess many would be transferrable to more classical data centers, or even broader scopes.</p>
<p>Before I provide my argument for value, I think it&rsquo;s prudent to first take a short excursion into the depth of the history of the interwebs. Not only for fun, but also to paint a picture of the context that the value I am promising will emerge from. Of course, I&rsquo;ll be speaking from my personal experience, so your mileage may vary …</p>
<h2 id="a-short-history-of-cloud-computing">A Short History of Cloud Computing</h2>
<blockquote>
<p>Cloud computing is the on-demand availability of computer system resources, especially data storage (cloud storage) and computing power, without direct active management by the user - <a href="https://en.wikipedia.org/wiki/Cloud_computing">Wikipedia: Cloud computing</a></p>
</blockquote>
<p>With the advent of modern Cloud Computing one major thing changed in the computing landscape: Hardware now had an on-demand API. Actually, not hardware, but resources that were previously only expressed in hardware. That did not happen over night, there was no first provider that used the word Cloud and set a new standard for all (even if some might claim that). It was, and still is, a process driven by necessity and demand. It&rsquo;s also not one process, but multiple processes running concurrently, moving somewhat in the same direction.</p>
<p>Two of causal concepts or technologies that I think are particularly important in the context of platform engineering, are:</p>
<p><strong>Virtualization</strong>: While the concept itself is <a href="https://en.wikipedia.org/wiki/IBM_CP-40">decades old</a>, and was productized for edge-cases and large scale enterprise solutions long ago, the first implementation that significantly impacted the larger market were virtual servers, in my opinion. Virtual servers allowed data center owners to separate their expensive hardware into smaller chunks, which could be used by themselves and especially sold to others much easier. This allowed more efficient utilization of available resources. But even more important: With having the ability to create multiple virtual servers within a physical server, the next logical step was, of course, to automate that process and then further: instrument that automatization. The infrastructure API was born. And it goes way beyond managing mere virtual servers; network firewalls, CDNs, database, etc - all virtual, all available via API.</p>
<p><strong>Containerization (&amp; Orchestration)</strong>: In a strict sense containerization is a <a href="https://en.wikipedia.org/wiki/OS-level_virtualization">specific implementation of virtualization</a>. I still think it deserves it&rsquo;s own paragraph as no other single technology containerization builds the bridge in between infrastructure providers and infrastructure users. Encapsulating an application in a container allowed both parties to agree on a common denominator. As long as it fits in a container, we can run it. And this is where orchestration comes in, as the infrastructure perspective on containerization: Running standardized containers at scale in isolation.</p>
<h2 id="new-paradigms">New Paradigms</h2>
<p>The wide-spread availability of the above technologies (and other factors, I am sure) triggered a lot of rethinking and led to a whole host of new perspectives and subsequent businesses arising. Again, I&rsquo;d like to highlight a few which I consider especially impactful and relevant for context:</p>
<p><strong>Micro Services</strong>: Micro Services are an entirely different perspective on application design and implementation. It makes you think of even the most complex application as a set of distinct, potentially inter-connected functionality. This mindset has immediate consequences not only for implementation (build &ldquo;simplistic&rdquo; Micro Services), but also for organization (ownership of well-defined parts of the whole), and, of course, for deployment and execution: where monolithic designs often came with a long list of highly specific requirements towards the OS and the hardware (resources), Micro Services encapsulated in containers can work in much more homogenous infrastructure, scale not as a whole but per service (part), fail individually with smaller blast radius and so on. That doesn&rsquo;t mean every application is (or <a href="https://martinfowler.com/bliki/MonolithFirst.html">should be</a>) designed from the get go as a Micro Service, but it creates the mindset, drives organization and fosters standardization nonetheless.</p>
<p><strong>Pets vs Cattle</strong>: Back in the days, servers used to have names and were individually and lovingly configured. Having worked on bare-metal with physical machines that I personally put a sticker with a name on before shoving them into the rack, I am well aware of the Pets that can be created. With having access to APIs that provide virtual servers, or any other resource, there was no way or need to keep up with that. Infrastructure users can now buy resources entirely detached from physical things. On-demand and auto-scaling. As a consequence, availability of resources is of far less concern (they are just available); we think in stacks (of resources) and not individual machines. Resources are numbers. Cattle, not Pets. <a href="http://cloudscaling.com/blog/cloud-computing/the-history-of-pets-vs-cattle/">Read more from Randy Bias, who summarized the analogy perfectly</a>.</p>
<p><strong>Infrastructure as Code</strong>: Applications are complicated. Operating systems are complicated. When both correlate it becomes even more complicated. There used to be a time when most people, myself included, configured systems manually. That resulted in deep and often unique knowledge about the systems. Unique, as in: low <a href="https://en.wikipedia.org/wiki/Bus_factor">bus factor</a>, as in: Nobody knows about the system, but one person. The answer to that was <a href="https://en.wikipedia.org/wiki/Configuration_management">configuration management</a>, which allowed the maintainers to describe the whole setup in a replicable, testable, version controlled and standardized documented way. With that system, configurations can be easily re-created (comparatively speaking), the human error factor is massively reduced and any setup is understood in short order by others (comparatively speaking). Infrastructure as Code (IaC) does the same thing for, well, infrastructure resources. Instead of manually provisioning / configuring / ordering resources, that are required for a specific service or application, that can now be described in code, which is standardized documented, checked into version control, code reviewable, testable and replicable.</p>
<p><strong>As a Service</strong>: As infrastructure resource automation became ever more commonplace, things that run on said infrastructure also gained easy access to a super-power: scalability. What that means is that you only need to pay the resources that you need. Or from the business perspective: You pay only for what you actually sell. Roughly speaking. With that in mind, it&rsquo;s easy to understand why these days about every <a href="https://free-for.dev/">functionality can be bought <em>as a service</em></a>. Think of it as a supply chain, with Infrastructure as a Service (IaaS) providing the foundation. That enables Platform as a Service (PaaS) to build their services upon - like compute runtimes, databases, cdn, etc. With that, Software as a Service (SaaS) builders can concentrate exclusively on their domain: software building, not deeply understanding the infrastructure layer. And everybody can grow or shrink as demand requires. Note that there are <a href="https://en.wikipedia.org/wiki/As_a_service">75 <em>as a Service</em> types</a> at the time of writing listed on Wikipedia, so I left out a few. Point is: The market changed. Concerns like hardware, operating system, service operations can now be outsourced, bought on-demand.</p>
<p>All these paradigms deeply entangled. You can consider <em>as a Service</em> a result of <em>Micro Services</em> or the other way around. Also <em>Pets vs Cattle</em> would hardly be possible without <em>Infrastructure as Code</em>, and the latter was needed by the former.</p>
<h2 id="what-is-platform-engineering">What is Platform Engineering?</h2>
<p>Before I can address the value I argue Platform Engineering brings to the table, I first need to clarify a bit what I mean - or don&rsquo;t mean - by that. Also mind that I am of the opinion that roles are like hats: You wear them as needed. Some hats you wear more often, some you like better than others, some you stash away and hope you never ever have to take them out again. Roles are not clear cut, roles are not bound to job titles either.</p>
<h3 id="platforming">Platforming</h3>
<p>I think it is safe to say that Platform Engineers are involved in Platforms. Since the term Platform is <a href="https://en.wikipedia.org/wiki/Computing_platform">rather vague</a> I will try explain what I mean by that - within the scope of this article. Let&rsquo;s start with: <em>a Platform is a well defined interface, that simplifies processes on and access to resources</em>.</p>
<p>In the Platform Engineering world, these resources are, of course, <em>infrastructure resources</em> of one type or another. From a software developer perspective the <a href="https://refactoring.guru/design-patterns/facade">Facade design pattern</a> is the closest approximation of key properties of a Platform I can think of. I would argue a Platform consists of one or multiple &ldquo;service facades&rdquo; combined with their interface specifications and documentation. <em>All</em> of these are required, as the intention of a platform is to automate common use-cases.</p>
<p>Platforms are mostly transparent to the user (as in: you don&rsquo;t know what&rsquo;s happening inside), but I am not sure whether or not this is a requirement - though it certainly is a good idea in most cases.</p>
<p>By this definition, Github would be a Platform. AWS would be a Platform - or maybe rather a Platform of Platforms. But also, any individual, in-house created solution that provides a simplified interface to manage the infrastructure resources that your use-case demands is a Platform.</p>
<p>Platforming then, is the process of identifying common use-cases (or patterns), modelling interfaces that describe them, providing automated solutions that implement them, and documenting it so it can be used with the least amount of manual interaction.</p>
<p>Platform Engineering is then the discipline that is concerned with Platforming.</p>
<h3 id="compared-to-other-roles">Compared to Other Roles</h3>
<p>While Platform Engineering (PE) is a new role, it did not come from nothing, but emerged as a specialization from other existing roles and responsibilities - like all roles. I&rsquo;d like to highlight a few which I think influence PE greatly:</p>
<p>As the closest &ldquo;sibling&rdquo; of the PE role I would consider the <strong>DevOps Engineer</strong> (DE), which is concerned with providing (cloud infrastructure based) solutions for specific applications. Or so I think - <a href="https://devops.com/devops-lifestyle-not-title/">DevOps is a lifestyle</a>, after all. What a PE does is pretty close to that. The main difference for me would be perspective and resulting scale. Whereas the DE advocates for &ldquo;their&rdquo; application(s), the PE is concerned with many or all applications. DE solves the special use-case (build infrastructure that a set of specific applications run in), PE solves the common use-case (build platform that all / most applications run in). DE is more interested in specifics, PE is more interested in commonalities. From my experience, both are usually needed, the borders are very blurry and often the same people wear both hats.</p>
<p>Probably involved in the origins of the Platform Engineer role is the <strong>Infrastructure Engineer</strong> (IE) role, that is concerned with building, deploying and maintaining, well, infrastructures. That role borders somewhere with System Administrator, Network Engineer and likely also DevOps on another side. It extends beyond the realm of cloud, as it is also concerned with data centers. Within this article, only the cloud scope is relevant. Within that the term is, I think, <strong>Cloud (Infrastructure) Engineer</strong>, so I am referring to that. From here PE took, of course, working with (cloud) infrastructure and generally thinking in infrastructure architectures. The main difference I see is that IE has strong concerns in operability and reliability, whereas PE has a focus on accessibility.</p>
<p>Also playing a role is the <strong>Backend Engineer</strong> (BE), who is concerned with the <a href="https://en.wikipedia.org/wiki/Front_end_and_back_end">data access layer</a> of applications. It&rsquo;s a broad field, with lots of sub-specializations, and certainly bordering on DevOps. One of the core concerns is designing and implementing APIs, including working with various data sources, queues and all that. PE does that as well, albeit with different purposes in mind. BE are &ldquo;customers&rdquo; (be it in-company) of PE created platforms and build their application upon it.</p>
<p>As I said, the borders are hard to draw, and there would be likely more roles (e.g. Site Reliability Engineering) I&rsquo;d like to compare with, but I have to stop at some point and hope this painted somewhat of a clearer picture.</p>
<h2 id="the-value-proposition">The Value Proposition</h2>
<p>Now, finally to the argument I want to make: The Value of Platform Engineering.</p>
<p>Taking the changes in the technology landscape into account, as well as the resulting new paradigms, one thing becomes clear: Complexity in the application ecosphere is on the rise. This is not caused by increased complexity in using the infrastructure side, nor the application development side. Things in Infrastructure actually got much easier, with Infrastructure as Code et al. Application development, from my perspective, also took huge strides towards ease of use.</p>
<p>So what is it then? Well, it is the fault of the great success that resulted from that: The increased amount of possibilities and opportunities that arose from the changes I highlighted (and others). Everybody now has easy access to scalability? Well, that also means it is now a concern for everybody. And this is why Platform Engineering plays a key role: it helps making those opportunities easily accessible by reducing complexity for the user, the application developer.</p>
<p>In more detail:</p>
<h3 id="the-standard-paas-pitch">The Standard PaaS Pitch</h3>
<blockquote>
<p>The advantages of PaaS are primarily that it allows for higher-level programming with dramatically reduced complexity - <a href="https://en.wikipedia.org/wiki/Platform_as_a_service#Advantages_and_disadvantages">Wikipedia: Platform as a Service</a></p>
</blockquote>
<p>First of all: I think that should be the general <em>as a Service</em> pitch, not specifically for PaaS. Like: <em>The advantages of as a Service are primarily that it allows for higher-level use with dramatically reduced complexity</em> - you know, sending an e-mail, streaming movies. All much better interfaces with dramatic reduction in complexity - considering the alternatives.</p>
<p>Anyway, this is what Platform Engineering can do: create higher-level interfaces for infrastructure resources that are designed so that they fit the use-case(s) and then implement them. Just not for any end-users, as the above generic as a Service pitch implies, but for application developers. Standardization comes as a free bonus.</p>
<p>Platform Engineers, of course, do not work exclusively for PaaS providers (there aren&rsquo;t that many around), they build platforms all over. Most PaaS providers address mass markets. Due to size, security, legal, legacy or many other reasons there are many, many companies that don&rsquo;t fit in that offering. They still need to use infrastructure to run their services on, that their developers create.</p>
<p>DevOps Engineering and Platform Engineering bridges the gap between developers, who are specialized in the application layer, and infrastructure providers that provide the resources to run the application on. DevOps Engineering provides solutions to run a small set of specialized services in cloud infrastructures. Platform Engineering provides solutions in the form of platforms that run more generalized services in cloud infrastructures. The borderlines in between are blurry and mostly a question of size and growth.</p>
<p>Either way: this allows developers to focus on development of applications, which they are great in. In my coloured opinion, you should of course start with platforming as early as possible, unless you don&rsquo;t expect infrastructure growth or change.</p>
<p><strong>Value</strong>: Lasting, high-paced development progress</p>
<h3 id="counteract-technical-debt">Counteract Technical Debt</h3>
<p><a href="https://en.wikipedia.org/wiki/Technical_debt">Technical debt</a> increases when things change or grow. As in: Always, unless you stand still. The question is not how to fully stop it but how to slow it down, so that it becomes manageable and does not increase until you are forced to stand still.</p>
<p>There are many contributing factors to the increase of technical debt. Of course there are business-side causes that seize priorities, leaving little or no time to align infrastructure or software design to counteract the build-up of technical debt. Then, there are structural or architectural causes that contribute. Patterns like Micro Services also arose to address that from an architectural side.</p>
<p>One major factor contributing to fast growth of technical debt is to have too many solutions for the same problem. As in: Every other application has their own unique deployment pipeline or service runtime or database setup or you-name-it. An ever growing zoo of solutions and patterns, that might sound like great ideas in the moment, as they solve the problem at hand, but will become an unmanageable chaos in the future, are highly fragile and there be dragons that you cannot touch without great risk.</p>
<p>Platform Engineering, at least, counteracts this last factor, and to different degrees others, by providing a standardized framework, a common denominator for services. It also enforces clear boundaries and interfaces, that allow you to understand, grow and change the application landscape much easier - in the now and in the future.</p>
<p>Closely related to that is also build up of <a href="https://en.wikipedia.org/wiki/Legacy_system">legacy</a> over time. This also translates to technical debt that needs to be paid at some point. While Platform Engineering does not, cannot, directly tackle legacy, it confines it to the agreed upon boundaries that make up a service or an application.</p>
<p>Lastly, Platform Engineering fosters modern paradigms like the aforementioned Micro Services, which offset technical debt on their own. Platform Engineering has an enabling and supporting role here.</p>
<p><strong>Value</strong>: Agility for change / Uninterrupted growth</p>
<h3 id="ready-for-change">Ready for Change</h3>
<p>The only constant is change. This was already known <a href="https://www.ancient.eu/Heraclitus_of_Ephesos/">2500 years ago</a> and still holds true, even for modern day application infrastructures. Still, it keeps surprising us when it comes. In the last 20 years of working in that ecosphere, I&rsquo;ve never encountered any system that did not change over time. Change comes in many forms. From small things, like new features that improve the value of an application, up to foundational change, like migrating from physical data centers into cloud infrastructure or rebuilding entire applications from scratch. Either way: Things change, you need to be ready for it, or pay a high bill when it comes due. Which it will.</p>
<p>You guessed it, there is a common theme here: Platform Engineering to the rescue. How? It provides a standardized environment to deploy and run your applications. Emphasis is on the word <em>standardized</em>. Think of it like that: Moving a hundred applications that each have their own way to deploy and run their services is very hard, daunting even. Moving a hundred applications that have a common way to deploy and run their services is much less hard. A Platform of course provides these shared commonalities.</p>
<p>That also implies: Platform early on. Maybe not when building an MVP, not even I would advocate for that, but certainly early enough so that standardization is not so painful that you might omit it even longer. Finding that right moment is not easy, hence: Platform early on.</p>
<p><strong>Value</strong>: Flexibility (in application infrastructure translates to flexibility in business)</p>
<h2 id="the-end">The End</h2>
<p>Thanks for reading. I am still iterating on the idea, there is certainly more to say on this topic than I captured here - but I guess you gotta release at some point. I also acknowledge that my focus in this article is mainly on the &ldquo;Platforming building service facades&rdquo; aspect, though I am aware that is not the full story of Platform Engineering. You can work all year with Kubernetes manifests, Elastichsearch logging clusters or what-have-you without facading (is that a word?) anything, and still be a top notch Platform Engineer.</p>
<p>Anyhow, thinking about this topic by writing about it helped me a lot, I hope it gave you food for thought as well.</p>
<h2 id="further-reading">Further reading</h2>
<ul>
<li><a href="https://softwareengineeringdaily.com/2020/02/13/setting-the-stage-for-platform-engineering/">The Rise of Platform Engineering, by Nick Daigler</a></li>
<li><a href="https://shahadarsh.com/2020/10/12/platform-engineering/">Platform Engineering: Using it to Gain Competitive Advantage, by Adarsh Shah</a></li>
<li><a href="http://cloudscaling.com/blog/cloud-computing/the-history-of-pets-vs-cattle/">The History of Pets vs Cattle and How to Use the Analogy Properly, by Randy Bias</a></li>
</ul>
]]></content:encoded></item><item><title>My Static Website Blogging Stack on AWS</title><link>https://ulrichkautz.com/posts/2021-03-05_my-blogging-stack/</link><pubDate>Fri, 05 Mar 2021 00:00:00 +0000</pubDate><guid>https://ulrichkautz.com/posts/2021-03-05_my-blogging-stack/</guid><category>blog</category><category>hugo</category><category>static-website</category><category>aws</category><description>I modularized my blogging stack in AWS that uses Hugo, S3, CloudFront, Route53 and ACM in an AWS CDK NPM package. This is a show-n-tell.</description><content:encoded><![CDATA[<p>I don&rsquo;t want my blog to be locked in with a specific vendor. My problem is less with the lock-in, and more with the interface. I already have a <a href="https://code.visualstudio.com/">great IDE</a> for writing Markdown and any website based interface would be a step down from that. Tho that is my personal preference of course, and it doesn&rsquo;t keep me from <a href="https://help.medium.com/hc/en-us/articles/360051846853-Can-I-republish-content-from-my-own-blog-">republishing</a> either.</p>
<p>Anyway, I ended up with Hugo + CloudFront + S3. It seemed like a great idea at the time - and it still does. Since I am still playing around with <a href="https://ulrichkautz.com/posts/2021-02-21_why-i-like-aws-cdk/">AWS CDK</a>, I figured it would be a good idea to modularize my stack and also blog about it.</p>
<h2 id="what-does-it-look-like">What does it look like?</h2>
<p>I don&rsquo;t need a complicated stack, which doesn&rsquo;t mean I can&rsquo;t have one to have fun with. No, it&rsquo;s not that bad. I use <a href="https://gohugo.io/">Hugo</a>, a static website generator written in Go, to compile my writings from Markdown to HTML. The generated HTML is then published to an S3 bucket, which is served from CloudFront. Route53 is used delegate my domain to CloudFront. AWS Certificate Management is used to issue the certificates, so that you can enjoy no browser warnings. In essence:</p>
<p><img src="https://ulrichkautz.com/img/posts/my-blogging-stack.png" alt="Static Website Stack in AWS"></p>
<p>The details are a bit .. more detailed. For example: I do not publish the generated HTML directly to S3, but use the <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-deployment-readme.html"><code>@aws-cdk/aws-s3-deployment </code></a> module to do that during <code>cdk deploy</code>. There are also a bunch of glue resources, mainly from the certificate generation via <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-certificatemanager.DnsValidatedCertificate.html"><code>@aws-cdk/aws-certificatemanager.DnsValidatedCertificate</code></a>.</p>
<h2 id="show-me-the-code">Show me the code!</h2>
<p>The source code of the AWS CDK module lives on Github: <a href="https://github.com/ukautz/aws-cdk-static-website">https://github.com/ukautz/aws-cdk-static-website</a>. <strong>Note</strong>: The resulting NPM package is hosted on <a href="https://github.com/features/packages">Github packages</a> as I do not consider it production ready and do not want to contribute to accidental installs&hellip; Read up how to <a href="https://docs.github.com/en/packages/guides/configuring-npm-for-use-with-github-packages#installing-a-package">use Github Packages hosted NPM packages</a> if you want to use it.</p>
<p>I plan on publishing a &ldquo;ready-to-go&rdquo; repository, which lays out a structure for using hugo and cdk in in concert. Like the repo that contains my blog. Once I did so I will update this blog entry. Until then, assuming you are familiar with AWS CDK, I hope the following is helpful to show how to deploy:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdk <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> route53 <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/aws-route53&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { StaticWebsite } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@ukautz/aws-cdk-static-website&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">export</span> <span style="color:#a2f;font-weight:bold">class</span> MyBlogStack <span style="color:#a2f;font-weight:bold">extends</span> cdk.Stack {
</span></span><span style="display:flex;"><span>  <span style="color:#a2f;font-weight:bold">constructor</span>(scope: <span style="color:#0b0;font-weight:bold">cdk.Construct</span>, id: <span style="color:#0b0;font-weight:bold">string</span>, props?: <span style="color:#0b0;font-weight:bold">cdk.Stack</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">super</span>(scope, id, props);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// load or create a hosted zone
</span></span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">const</span> hostedZone <span style="color:#666">=</span> route53.HostedZone.fromLookup(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;HostedZone&#39;</span>, {
</span></span><span style="display:flex;"><span>      domainName<span style="color:#666">:</span> <span style="color:#b44">&#39;mydomain.tld&#39;</span>,
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// create all static website infra
</span></span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">new</span> StaticWebsite(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;StaticWebsite&#39;</span>, {
</span></span><span style="display:flex;"><span>      directory<span style="color:#666">:</span> <span style="color:#b44">&#39;/path/to/my/hugo/public&#39;</span>,
</span></span><span style="display:flex;"><span>      domain<span style="color:#666">:</span> <span style="color:#b44">&#39;mydomain.tld&#39;</span>,
</span></span><span style="display:flex;"><span>      domainAliases<span style="color:#666">:</span> [<span style="color:#b44">&#39;www.mydomain.tld&#39;</span>],
</span></span><span style="display:flex;"><span>      hostedZone,
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>That&rsquo;s about it. As mentioned, once I get around to publish that all-in-one repo, I&rsquo;ll update here. Hope this helps!</p>
]]></content:encoded></item><item><title>Why I like AWS CDK</title><link>https://ulrichkautz.com/posts/2021-02-21_why-i-like-aws-cdk/</link><pubDate>Sun, 21 Feb 2021 00:00:00 +0000</pubDate><guid>https://ulrichkautz.com/posts/2021-02-21_why-i-like-aws-cdk/</guid><category>iac</category><category>infra</category><category>infrastructure as code</category><category>aws</category><description>AWS CDK has been around for a while now and most of the main APIs reached stable. This is a look on the state of affairs from the perspective of a platform engineer.</description><content:encoded><![CDATA[<p>I love to code, and I love to work in infrastructure. Back when I started out in my professional career, in the early 2000s, these two things were, more often than not, areas of concern of different professions. Nowadays, with <a href="https://sre.google/">SRE</a> teams in many companies, <a href="https://en.wikipedia.org/wiki/DevOps">DevOps</a> being considered a <a href="https://devops.com/devops-lifestyle-not-title/">lifestyle</a> and <a href="https://softwareengineeringdaily.com/2020/02/13/setting-the-stage-for-platform-engineering/">platform engineer</a> becoming an established role, there is plenty of work to do with my particular passions.</p>
<p>One of the fun things that came out of the fusion of these skills - or rather the demands and opportunities of cloud infrastructures - is of course <a href="https://en.wikipedia.org/wiki/Infrastructure_as_code">Infrastructure as Code (IaC)</a>. While the landscape of IaC tooling is still limited - compared to the humongous diversity of choice you have when solving &ldquo;pure&rdquo; coding problems - and there was a time when this whole endeavour threatened to be the exclusive domain of declarative DSLs, which I am not a fan of - there are at least a few contenders out there that scratch both my itches. One in particular is the topic of this post: <a href="https://github.com/aws/aws-cdk">AWS CDK</a>, which is (as the name implies) a tooling from and exclusively for the AWS ecosystem.</p>
<h2 id="what-makes-aws-cdk-great">What makes AWS CDK great?</h2>
<p>The AWS Cloud Development Toolkit (CDK) is a 2nd generation infrastructure as code solution. By 2nd generation I am emphasizing the evolution from the previously mentioned purely declarative (JSON / YAML / ..) approaches, which I consider first generation.</p>
<p>Admittedly, those early toolings already solved most of the problems: Having a reproducible, documented (by code), consistent description of your infrastructure, that can be automatically executed from within a CI/CD pipeline, checked into version control, code reviewed, (integration / end-to-end) tested and all the things. That was the promise and that was what they delivered. However, working with CloudFormation YAML and on and off with Terraform HCL for a few years now, there is room for improvement. That in itself is not a critic, it is to be expected. First iteration rarely are perfect. Nor should they be.</p>
<p>In a sense, the first generation toolings addressed (and largely solved) functionality. Machines; satisfy the APIs. The second generation tooling now also addresses usability. Humans; make it maintainable; make it fun!</p>
<p>With the full power of a programming language - like Typescript (or Python, or whichever flavor you prefer) - AWS CDK really hit a nerve - or alas mine. So will / do <a href="https://www.pulumi.com/">Pulumi</a> and <a href="https://github.com/hashicorp/terraform-cdk">Terraform CDK</a> (🤞) - but that is another story. What I am getting at: The <em>C</em> in <em>IaC</em> moves further towards <em>coding</em>, as in programming in a high-level programming language, which comes with a lot of inherent benefits.</p>
<p>This article is not about comparing IaC solutions, but taking a look at AWS CDK from a platform engineer perspective. From here on out I will only make comparisons to CloudFormation YAML, as that is what AWS CDK replaces (well, it still builds and executes CloudFormation YAML under the hood - if you want to be nitpicky - but since you do not write any CloudFormation YAML anymore, I think to say &ldquo;replacing&rdquo; is not too far fetched).</p>
<h3 id="the-right-level-of-abstraction">The right level of abstraction</h3>
<p>One thing I really love about AWS CDK is that it provides &ldquo;<a href="https://en.wikipedia.org/wiki/Goldilocks_principle">the right level</a>&rdquo; of abstraction for my kind of work, meaning: I do not have to deal with all details of all resources - or even all involved resources - unless I need to <em>for reasons outside of the tooling</em>.</p>
<p>To give you an example, here is full amount of required code to setup a VPC, including subnets, routing tables and NAT gateways with associated EIPs:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdk <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> ec2 <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/aws-ec2&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">export</span> <span style="color:#a2f;font-weight:bold">class</span> VpcDemoStack <span style="color:#a2f;font-weight:bold">extends</span> cdk.Stack {
</span></span><span style="display:flex;"><span>  <span style="color:#a2f;font-weight:bold">constructor</span>(scope: <span style="color:#0b0;font-weight:bold">cdk.Construct</span>, id: <span style="color:#0b0;font-weight:bold">string</span>, props?: <span style="color:#0b0;font-weight:bold">cdk.StackProps</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">super</span>(scope, id, props);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// setup VPC
</span></span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">new</span> ec2.Vpc(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;Vpc&#39;</span>);
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Doesn&rsquo;t look overly excessive, does it?</p>
<p>Now to the <em>reasons outside of the tooling</em>. For example: what if you do not want to use NAT gateways, but NAT instances - maybe because your dev cluster doesn&rsquo;t need to cost an arm and a leg - then you can adjust that part easily.</p>
<p>While we are at cost reduction, per default all availability zones (AZ) in the region are used. That means subnets, routing tables and NAT resources are created in all of them. Let&rsquo;s limit the amount of AZs to two, so we still have redundancy but at lower cost.</p>
<p>All together, here you go:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdk <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> ec2 <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/aws-ec2&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">export</span> <span style="color:#a2f;font-weight:bold">class</span> VpcDemoStack <span style="color:#a2f;font-weight:bold">extends</span> cdk.Stack {
</span></span><span style="display:flex;"><span>  <span style="color:#a2f;font-weight:bold">constructor</span>(scope: <span style="color:#0b0;font-weight:bold">cdk.Construct</span>, id: <span style="color:#0b0;font-weight:bold">string</span>, props?: <span style="color:#0b0;font-weight:bold">cdk.StackProps</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">super</span>(scope, id, props);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// setup VPC
</span></span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">new</span> ec2.Vpc(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;Vpc&#39;</span>, {
</span></span><span style="display:flex;"><span>        maxAzs: <span style="color:#0b0;font-weight:bold">2</span>,
</span></span><span style="display:flex;"><span>        natGatewayProvider: <span style="color:#0b0;font-weight:bold">new</span> ec2.NatInstanceProvider({
</span></span><span style="display:flex;"><span>            instanceType: <span style="color:#0b0;font-weight:bold">new</span> ec2.InstanceType(<span style="color:#b44">&#39;t3.micro&#39;</span>),
</span></span><span style="display:flex;"><span>        })
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>This design - that allows you to engage with details only <em>when</em> and <em>if</em> you need to - follows a principle that is close to what the UI/UX folks call <a href="https://www.nngroup.com/articles/progressive-disclosure/">progressive disclosure</a>. Especially when dealing with IaC that manages complex cloud resources (which often require a lot of boilerplate that does not need tinkering with in many cases) this can help a lot to keep your code clean and maintainable. I am a big fan, if that wasn&rsquo;t clear.</p>
<p>Consider reviewing the changes in between the above code examples vs reviewing the changes in equivalent CloudFormation YAML files.</p>
<h3 id="standardization--compliance-without-the-toil">Standardization &amp; Compliance without the toil</h3>
<p>Another thing I very much appreciate is how easy it is to align and standardize common settings of all your cloud resources. If you ever had the questionable pleasure of manually adding the same set of tags to all the resources in all your stacks which are written in pure CloudFormation YAML, you will be happy to hear that there is an out-of-the-box solution for that in AWS CDK.</p>
<p>But that is not all. If you are working in any kind of enterprise setup, think about compliance with company-wide best practice like &ldquo;encrypt all S3 buckets&rdquo; or generally &ldquo;encrypt all that can be encrypted (S3, SNS, SQS, ..)&rdquo; or whatever you think should apply to all or a specified set of resources of your choosing. Again, if you ever went through the pain of updating all the existing stacks in order to comply with a new standard / best practice / policy / gut feeling / you-name-it - you will be pleased how AWS CDK helps you solve that.</p>
<p>If I peaked your interest, then let me introduce you to what AWS calls <a href="https://docs.aws.amazon.com/cdk/latest/guide/aspects.html">Aspects</a>. In short: Aspects allow you to apply an operation on a defined set of resources. The defined set could be as easy as all, or only S3 buckets, or only S3 buckets which already have tag X, or whatever you can think of. The operation can be tagging, adding the right encryption, adding a forwarded header to all behaviors of all CloudFront distribution &hellip; The sky is the limit.</p>
<h4 id="simple-case-tagging">Simple case: Tagging</h4>
<p>Ok, enough talk, let&rsquo;s get back to the code. First the tagging part. AWS took an effort to wrap that so that you do not even need to understand how to work with Aspects. Good on them! Here a code example, extending the generic <code>bin/&lt;your-stack&gt;.ts</code> file that a <code>cdk init ..</code> would have created for you:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="">#</span><span style="color:#666">!</span><span style="">/usr/bin/env node</span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#b44">&#39;source-map-support/register&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdk <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { Tags } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { MyStack } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;../lib/my-stack&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span> app <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> cdk.App();
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">new</span> MyStack(app, <span style="color:#b44">&#39;MyStack&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// add the tags service=my-service and team=my-team to ALL (taggable) resources
</span></span></span><span style="display:flex;"><span>Tags.<span style="color:#a2f;font-weight:bold">of</span>(app).add(<span style="color:#b44">&#39;service&#39;</span>, <span style="color:#b44">&#39;my-service&#39;</span>);
</span></span><span style="display:flex;"><span>Tags.<span style="color:#a2f;font-weight:bold">of</span>(app).add(<span style="color:#b44">&#39;team&#39;</span>, <span style="color:#b44">&#39;my-team&#39;</span>);
</span></span></code></pre></div><p>I don&rsquo;t know about you, but I really like that. Keep in mind that this can be done &ldquo;on every level&rdquo;. Above, it will be applied to all resources &ldquo;in the App&rdquo;. You could equally easily do it from within the stack (think for example: <a href="https://docs.aws.amazon.com/cdk/latest/guide/stacks.html#stack_nesting">NestedStacks</a>). The type of the first parameter for the <code>of()</code> function - where I inserted the <code>app</code> instance - is a <code>cdk.IConstruct</code>. Every resource that AWS CDK deals with, be it the <code>cdk.App</code>, a <code>cdk.Stack</code> or an <code>s3.S3</code> bucket. All of them implement the <code>cdk.IConstruct</code> interface and can be used!</p>
<h4 id="create-generic-aspects">Create generic Aspects</h4>
<p>Ok, now you saw tags, which are a specific case of aspects, let&rsquo;s take look at the general case. At the core of how aspects work is the <code>cdk.IAspect</code> interface:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">interface</span> IAspect {
</span></span><span style="display:flex;"><span>   visit(node: <span style="color:#0b0;font-weight:bold">IConstruct</span>)<span style="color:#666">:</span> <span style="color:#a2f;font-weight:bold">void</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>This is quite straight forward, a classical <a href="https://en.wikipedia.org/wiki/Visitor_pattern">visitor pattern</a>. Any aspect needs to implement exactly one method: <code>visit</code>. Note that the <code>node</code> parameter is of the type <code>IConstruct</code>, hence all aspects can be applied to any resource - and in turn: decision on which resource (type(s)) it should act upon must happen in the method body.</p>
<p>Now assume you have a best practice, which says: <em>All S3 buckets must be encrypted server-side</em> (which is a good advice anyway). Let me first show you how the aspect would look like, then following how to apply it.</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#080;font-style:italic">// assume this is in a file in your CDK project, e.g. `lib/s3-encryption-aspect.ts`
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdk <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> s3 <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/aws-s3&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">export</span> <span style="color:#a2f;font-weight:bold">class</span> S3EncryptionAspect <span style="color:#a2f;font-weight:bold">implements</span> cdk.IAspect {
</span></span><span style="display:flex;"><span>    visit(node: <span style="color:#0b0;font-weight:bold">cdk.IConstruct</span>)<span style="color:#666">:</span> <span style="color:#a2f;font-weight:bold">void</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#080;font-style:italic">// bail out, if we&#39;re not dealing with an S3 bucket
</span></span></span><span style="display:flex;"><span>        <span style="color:#080;font-style:italic">// this aspect _can_ get _all_ resources, including Stacks and Apps
</span></span></span><span style="display:flex;"><span>        <span style="color:#a2f;font-weight:bold">if</span> (<span style="color:#666">!</span>(node <span style="color:#a2f;font-weight:bold">instanceof</span> s3.CfnBucket)) {
</span></span><span style="display:flex;"><span>            <span style="color:#a2f;font-weight:bold">return</span>;
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#080;font-style:italic">// bail out if encryption is already specified (e.g. using a custom key)
</span></span></span><span style="display:flex;"><span>        <span style="color:#a2f;font-weight:bold">if</span> (node.bucketEncryption) {
</span></span><span style="display:flex;"><span>            <span style="color:#a2f;font-weight:bold">return</span>;
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#080;font-style:italic">// apply per default server encryption
</span></span></span><span style="display:flex;"><span>        node.bucketEncryption <span style="color:#666">=</span> {
</span></span><span style="display:flex;"><span>            serverSideEncryptionConfiguration<span style="color:#666">:</span> [
</span></span><span style="display:flex;"><span>                {
</span></span><span style="display:flex;"><span>                    serverSideEncryptionByDefault<span style="color:#666">:</span> {
</span></span><span style="display:flex;"><span>                        sseAlgorithm<span style="color:#666">:</span> <span style="color:#b44">&#39;AES256&#39;</span>
</span></span><span style="display:flex;"><span>                    }
</span></span><span style="display:flex;"><span>                }
</span></span><span style="display:flex;"><span>            ]
</span></span><span style="display:flex;"><span>        };
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Ok, a few things to note:</p>
<ol>
<li><strong>It&rsquo;s <code>s3.CfnBucket</code>, not <code>s3.Bucket</code></strong>: When working &ldquo;on this level of detail&rdquo;, you will not use the high level types, but basically directly work with CloudFormation resources. AWS calls them L1 (level one) constructs, which are available as <code>Cfn&lt;Type&gt;</code> and L2 (level two) constructs, which the <code>s3.Bucket</code> above would be, that hide complexity. More on that below. For now note: when executing <code>cdk synth</code> later on, you can see that the Typescript structure of the <code>s3.CfnBucket</code> <em>exactly</em> matches the Properties of the (generated) CloudFormation YAML:</li>
</ol>
<pre tabindex="0"><code>--%&lt;--
  Bucket12341234:
    Type: AWS::S3::Bucket
    Properties:
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
--%&lt;--
</code></pre><ol start="2">
<li>
<p><strong>Bail out on your own</strong>: As advertised, you have to implement the decisions on what kind of resources the aspect is to act upon yourself. The first <code>if</code> condition takes care of that.</p>
</li>
<li>
<p><strong>Aspects are meant to be re-usable to support D.R.Y.</strong>: You won&rsquo;t write an Aspect to modify one resource in one stack. Make sure that your design is sufficiently flexible and sensible. The best practice from above states only that buckets must be server-side encrypted. There is no reason to overwrite / change an already configured server-side encryption.</p>
</li>
</ol>
<h4 id="use-generic-aspects">Use generic Aspects</h4>
<p>The hard part was the writing of the Aspect. Once that is done, it can be as easily applied as the tagging example above. First a quick stack example, that defines a stack which contains an S3 bucket without encryption:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdk <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> s3 <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/aws-s3&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">export</span> <span style="color:#a2f;font-weight:bold">class</span> S3DemoStack <span style="color:#a2f;font-weight:bold">extends</span> cdk.Stack {
</span></span><span style="display:flex;"><span>  <span style="color:#a2f;font-weight:bold">constructor</span>(scope: <span style="color:#0b0;font-weight:bold">cdk.Construct</span>, id: <span style="color:#0b0;font-weight:bold">string</span>, props?: <span style="color:#0b0;font-weight:bold">cdk.StackProps</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">super</span>(scope, id, props);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// this is how you would create an encrypted S3 bucket with the high level API
</span></span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">/* new s3.Bucket(this, &#39;Bucket&#39;, {
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">      encryption: s3.BucketEncryption.S3_MANAGED,
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">    }); */</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#080;font-style:italic">// for the demo, let&#39;s just create a bucket without encryption
</span></span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">new</span> s3.Bucket(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;Bucket&#39;</span>)
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Now the modified <code>bin/</code> file, which uses the above stack and applies the Aspect:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="">#</span><span style="color:#666">!</span><span style="">/usr/bin/env node</span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#b44">&#39;source-map-support/register&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdk <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { Aspects } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { S3DemoStack } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;../lib/s3-demo-stack&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { S3EncryptionAspect } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;../lib/s3-encryption-aspect&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span> app <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> cdk.App();
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">new</span> S3DemoStack(app, <span style="color:#b44">&#39;S3DemoStack&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// apply the aspects to all resources (the aspect will 
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// decide itself on what resource it should make changes)
</span></span></span><span style="display:flex;"><span>Aspects.<span style="color:#a2f;font-weight:bold">of</span>(app).add(<span style="color:#a2f;font-weight:bold">new</span> S3EncryptionAspect());
</span></span></code></pre></div><h4 id="one-step-further-compliance-in-a-box">One step further: Compliance in a box</h4>
<p>Let&rsquo;s say you have a multitude of best practices / policies / rules that you want to apply to all the stacks that will be deployed in your organization / multi-stack project, then you can create your own (NPM, ..) package that exports your own App (or Stack or ..) that automatically applies all the things you need to make the managed resources compliant.</p>
<p>Here an example how that could look like using a custom App for the ACME company:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdk <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { Aspects, Tags } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { S3EncryptionAspect } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;./s3-encryption-aspect&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">/**
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic"> * All ACME owned resources must be tagged with service and team
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic"> */</span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">export</span> <span style="color:#a2f;font-weight:bold">interface</span> AcmeAppProps <span style="color:#a2f;font-weight:bold">extends</span> cdk.AppProps {
</span></span><span style="display:flex;"><span>    service: <span style="color:#0b0;font-weight:bold">string</span>;
</span></span><span style="display:flex;"><span>    team: <span style="color:#0b0;font-weight:bold">string</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">/**
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic"> * Wrap ACME compliance so that it can be easily re-used
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic"> */</span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">export</span> <span style="color:#a2f;font-weight:bold">class</span> AcmeApp <span style="color:#a2f;font-weight:bold">extends</span> cdk.App {
</span></span><span style="display:flex;"><span>    <span style="color:#a2f;font-weight:bold">constructor</span>(props: <span style="color:#0b0;font-weight:bold">AcmeAppProps</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#a2f;font-weight:bold">super</span>(props);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#080;font-style:italic">// make sure everything is tagged
</span></span></span><span style="display:flex;"><span>        Tags.<span style="color:#a2f;font-weight:bold">of</span>(<span style="color:#a2f;font-weight:bold">this</span>).add(<span style="color:#b44">&#39;service&#39;</span>, props.service);
</span></span><span style="display:flex;"><span>        Tags.<span style="color:#a2f;font-weight:bold">of</span>(<span style="color:#a2f;font-weight:bold">this</span>).add(<span style="color:#b44">&#39;team&#39;</span>, props.team);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#080;font-style:italic">// apply all the aspects that implement your best practices
</span></span></span><span style="display:flex;"><span>        Aspects.<span style="color:#a2f;font-weight:bold">of</span>(<span style="color:#a2f;font-weight:bold">this</span>).add(<span style="color:#a2f;font-weight:bold">new</span> S3EncryptionAspect());
</span></span><span style="display:flex;"><span>        <span style="color:#080;font-style:italic">//Aspects.of(this).add(new SQSEncryptionAspect());
</span></span></span><span style="display:flex;"><span>        <span style="color:#080;font-style:italic">//Aspects.of(this).add(new YourOtherBestPracticeAspect());
</span></span></span><span style="display:flex;"><span>        <span style="color:#080;font-style:italic">//...
</span></span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>And lastly, using the above custom App in your <code>bin/</code> script:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="">#</span><span style="color:#666">!</span><span style="">/usr/bin/env node</span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#b44">&#39;source-map-support/register&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> <span style="color:#666">*</span> <span style="color:#a2f;font-weight:bold">as</span> cdk <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { AcmeApp } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;@acme-aws-cdk/core&#39;</span>;
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span> { ArbitraryServiceStack } <span style="color:#a2f;font-weight:bold">from</span> <span style="color:#b44">&#39;../lib/arbitrary-service-stack&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span> app <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> AcmeApp({
</span></span><span style="display:flex;"><span>    service<span style="color:#666">:</span> <span style="color:#b44">&#39;my-awesome-service&#39;</span>,
</span></span><span style="display:flex;"><span>    team<span style="color:#666">:</span> <span style="color:#b44">&#39;my-awesome-team&#39;</span>
</span></span><span style="display:flex;"><span>});
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">new</span> ArbitraryServiceStack(app, <span style="color:#b44">&#39;ArbitraryServiceStack&#39;</span>);
</span></span></code></pre></div><p>And that&rsquo;s it. Compliance in a box. Nicely done.</p>
<h3 id="platforming---aka-higher-level-abstraction">Platforming - aka higher level abstraction</h3>
<p>When working as a platform engineer your customers are developers. Among other things we build infrastructure tooling and automation that results in a layer of abstraction, which simplifies and hides the underlying complexity. This allows developers to concentrate on their actual work, which is <em>not</em> understanding and defining every last nut and bolt that makes up their service infrastructure, but building outstanding products that create value for the business.</p>
<p>However, in modern DevOps days, developers are at least somewhat responsible for their infrastructure, as in: they own parts of it, they might do on-call for it, they will create and remove resources as they need. They just don&rsquo;t have - or at least need to have - the same high detail perspective on these resources. Deciding whether to use a NAT gateway or NAT instances should not waste their time. They are concerned about whether they are deploying a production or a development stage, that their services has no outages during deployment, is reliably available afterwards, always provides the performance needed and does all of that cost efficiently.</p>
<p>With this in might, I need to bring up the L1 and L2 constructs AWS CDK provides again. A quick refresh:</p>
<ul>
<li><strong>L1 constructs</strong>, like <code>s3.CfnBucket</code>, directly map onto CloudFormation resources, allow (and require) to work on the same level of detail as you would with CloudFormation YAML</li>
<li><strong>L2 constructs</strong>, like <code>s3.Bucket</code> are higher level constructs, that provide a sensible default, keep you from writing boilerplate, take care of glue logic etc</li>
</ul>
<p>Getting to my point, there is a third type of constructs, which AWS calls <strong><em>pattern</em> construct</strong> (all the details <a href="https://docs.aws.amazon.com/cdk/latest/guide/constructs.html">here</a>). I will refer to these pattern constructs as L3 (even though AWS does not), just to keep it simple (for me) and clear (for you). To give you an idea what those L3&rsquo;s can do, here a list of what AWS currently (<code>v1.89.0</code>) provides:</p>
<p><strong><a href="https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/aws-route53-patterns"><code>@aws-cdk/aws-route53-patterns</code></a></strong>: You can specify a single resource (<code>HttpsRedirect</code>), that: Creates a CloudFront that exposes a domain you want to fully redirect ot another, creates an S3 bucket that implements the redirects, creates Route 53 alias records to route the domain to the CloudFront and uses the ACM to issue all the needed certs.</p>
<p><strong><a href="https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/aws-ecs-patterns"><code>@aws-cdk/aws-ecs-patterns</code></a></strong>: Comes with two L3 constructs, which both ECS tasks in a provided ECS cluster and setup an ALB in-front, that routes all traffic to a set of tasks (containers). Flavors are:</p>
<ul>
<li><code>ApplicationLoadBalancedEc2Service</code>: Uses custom ECS with runs on EC2 instances</li>
<li><code>ApplicationLoadBalancedFargateService</code>: Uses Fargate ECS tasks</li>
</ul>
<p><strong><a href="https://aws.amazon.com/solutions/constructs/patterns/">A lot of ready-made AWS CDK solution constructs</a></strong>: or alternatively <a href="https://github.com/awslabs/aws-solutions-constructs/tree/master/source/patterns/%40aws-solutions-constructs">on Github</a></p>
<p>I hope this gives you an idea why I am particular exited about the possibility to encapsulate higher level platform patterns in AWS CDK modules, which can then easily be re-used by others.</p>
<p>However, what AWS CDK comes with is only where it starts. Consider your own patterns, that you see in your organization or across your projects. Just thinking how much time that can save for me makes me feel warm and fuzzy. Not to speak of the impact this can have on standardization.</p>
<p>For example, say in your organization most services run behind an ALB on EC2 instances, which are described in a template and scaled via auto scaling. Some have also CloudFront in-front. Some use RDS databases, or mount EBS volumes, or EFS, or .. There you have an L3 construct in the planning.</p>
<p>Or from another side: Any vendor can provide AWS CDK modules, so you can launch their product in different flavors (EC2 vs ECS vs EKS vs ..), completely encapsulated with a nice interface, as another L3 construct.</p>
<p>Long story short: This is more than practical, this is absolutely fantastic.</p>
<h2 id="is-it-then-all-rainbows-and-butterflies">Is it then all rainbows and butterflies?</h2>
<p>Well, there are always some clouds on the horizon (cheap pun intended). As AWS CDK is &ldquo;only&rdquo; version one, there are learnings and feedbacks I like to share. Also, as a native Berliner, I need to do my part in upholding our reputation as complainers. The highest praise a Berliner offers for even the most delicious food: <em>It wasn&rsquo;t bad</em> (which can be understood as a complaint in itself). With that in mind:</p>
<h3 id="the-rapid-version-change-annoyance">The rapid version change annoyance</h3>
<p>AWS CDK uses <a href="https://semver.org/">semver</a> packages are versioned like <code>MAJOR.MINOR.PATCH</code> as in <code>1.89.0</code> at the time of this writing this article. If you have a look at the <a href="https://github.com/aws/aws-cdk/blob/master/CHANGELOG.md">changelog</a>, you will find that about every 7-10 days a new minor version is released. Those contain many bug fixes, but also newly added features caused by new product or new feature releases. The active development is of course great, but comes at a price. Especially since AWS merrily adds non-stable features within their packages, which (of course) will see breaking changes.</p>
<p>This has consequences for the day-2-day development. Nearly every time I get back to a project, AWS CDK will have moved a few minor versions ahead. So any newly added <code>@aws-cdk/*</code> packages will come in a later version than any already installed <code>@aws-cdk/*</code> package. While semver defines that minor version changes must be non-interface breaking, <em>that does not apply for experimental code</em>.</p>
<p>Mind, I am not referring to (wholly) experimental packages (which exist), but to <a href="https://github.com/aws/aws-cdk/search?q=%22%40experimental%22">experimental parts</a> of otherwise stable packages. This also does not affect only newly released products or features, but long established APIs.</p>
<p>Anyway, understand this as a heads-up, it can sneak up on you. Make sure to read documentation attentively (watch for that <code>@experimental</code> note). Consider to stick with a (minor) version longer than AWS does. Consider setting aside maintenance time to stay up2date and address resulting API changes in your code.</p>
<p>In short: continuous development is appreciated. Taking the time to come up with well thought out interfaces that allow rapid development is appreciated. Experimental code, hidden among the stable, can give you stomach pains, if you are not careful.</p>
<h3 id="referencing-existing-resources">Referencing existing resources</h3>
<p>The AWS CDK allows you to use high-level objects where CloudFormation YAML would expect e.g. ARNs or IDs. As shown with the VPC example, they try to keep the boilerplate down. Another good illustration of that point is how you grant IAM permissions in AWS CDK. Consider the following excerpt, which create a new S3 bucket and a new user and then grants the user read and write permissions to that S3 bucket:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span> user <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> iam.User(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;User&#39;</span>);
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span> bucket <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> s3.Bucket(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;Bucket&#39;</span>);
</span></span><span style="display:flex;"><span>bucket.grantReadWrite(user);
</span></span></code></pre></div><p>Aside from the <code>AWS::IAM::User</code> and the <code>AWS::S3::Bucket</code>, this will also create an <code>AWS::IAM::Policy</code> that implements the read / write permissions for the user to the bucket. Neat.</p>
<p>Now, where is the problem? Well, in the above example, all the resources used were created in the same context (e.g. Stack). Now, if you have existing resources, and want to use them in your stack, then you need to access them differently.</p>
<p>Say you want to replicate the same above, just the user was created in a different stack or maybe even manually, then you need to &ldquo;load&rdquo; it, instead of creating it. AWS CDK provides for that purpose static <code>from*</code> methods on the resource types. Here is how you would load a <code>User</code> whose ARN you know:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span> user <span style="color:#666">=</span> iam.User.fromUserArn(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;User&#39;</span>, <span style="color:#b44">&#39;arn:..of:the:user&#39;</span>);
</span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span> bucket <span style="color:#666">=</span> <span style="color:#a2f;font-weight:bold">new</span> s3.Bucket(<span style="color:#a2f;font-weight:bold">this</span>, <span style="color:#b44">&#39;Bucket&#39;</span>);
</span></span><span style="display:flex;"><span>bucket.grantReadWrite(user);
</span></span></code></pre></div><p>Still, there is no problem. Seems straight forward: that nice <code>fromUserArn</code> function has a simple signature. Aside from the scope (<code>this</code>) and the id (<code>'User'</code>) there is only the ARN that is required. That means: You can load a User just by knowing their unique ARN. Makes sense, no?</p>
<p>Now we are arriving at the actual problem, because that simple signature from above is not consistently available at all. For example, when working with private namespaces in ECS (if you haven&rsquo;t, consider them as something like private Route53 Hosted Zones), then you need to do that:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-typescript" data-lang="typescript"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span> <span style="color:#a2f;font-weight:bold">namespace</span> <span style="color:#666">=</span> servicediscovery.PrivateDnsNamespace.fromPrivateDnsNamespaceAttributes({
</span></span><span style="display:flex;"><span>    namespaceArn<span style="color:#666">:</span> <span style="color:#b44">&#39;arn:..of:the:namespace&#39;</span>,
</span></span><span style="display:flex;"><span>    namespaceId<span style="color:#666">:</span> <span style="color:#b44">&#39;namespace123-id&#39;</span>,
</span></span><span style="display:flex;"><span>    namespaceName<span style="color:#666">:</span> <span style="color:#b44">&#39;namespace123&#39;</span>,
</span></span><span style="display:flex;"><span>});
</span></span></code></pre></div><p>To be clear: All three attributes are <em>mandatory</em>, I did not add them for fun. As you might also note: The namespace ARN <em>is a globally unique identifier</em>. Same goes for the ID, which <a href="https://docs.aws.amazon.com/cli/latest/reference/servicediscovery/get-namespace.html">is sufficient for the AWS CLI requires to fetch a namespace</a>. So why do you need to provide <em>two</em> unique identifiers <em>and</em> another attribute? Well, if you look into the <a href="https://github.com/aws/aws-cdk/blob/v1.89.0/packages/@aws-cdk/aws-servicediscovery/lib/private-dns-namespace.ts#L39-L47">implementation</a>, you&rsquo;ll find no &ldquo;loading&rdquo; is happening at all. It&rsquo;s just filling the interface requirements, and needs you to fill in what it cannot derive from the environment and context.</p>
<p>As I said, I like to complain. I am not sure at all whether this just reflects the early state (v1 after all), or whether this is intentionally API design. I stumbled across a <a href="https://github.com/aws/aws-cdk/issues/8273#issuecomment-640537378">comment from a core contributes</a> that might imply they want to be very strict about determinism - but having SSM value loading, allowing to <a href="https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/aws-s3-assets">package and upload files to S3</a> during build and even <a href="https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/aws-ecr-assets">build and upload docker container images</a> .. I figure that determinism train has left the station a while ago. (Yes I know that happens during synthesizing, so could a convenient <code>load&lt;Something&gt;FromOnly&lt;UniqueIdentifier&gt;</code>() function..).</p>
<p>Huge, show-stopping problem? No. Inconvenient and bothersome? Yes.</p>
<h2 id="summary">Summary</h2>
<p>I don&rsquo;t want to end at a negative note at all, as for me AWS CDK is a great tool! It&rsquo;s a marvelous piece of software design, fun to work with and addresses usability issues that were not tackled by the first generation. It makes maintainability significantly less painful and less error prone. I give it my strong recommendation when working exclusively - or at least mainly - with AWS.</p>
<p>I am exited to see what the upcoming v2 will bring!</p>
]]></content:encoded></item><item><title>Practical introduction to Go: Application development (3/3)</title><link>https://ulrichkautz.com/posts/2020-07-03_practical-go-3-of-3/</link><pubDate>Fri, 03 Jul 2020 19:00:00 +0200</pubDate><guid>https://ulrichkautz.com/posts/2020-07-03_practical-go-3-of-3/</guid><description>Dive into Go application development. Understand advanced language concepts. Express an application design in Go. Learn to write tests.</description><content:encoded><![CDATA[<p>This introduction is written for developers with some experience in Go. I will assume:</p>
<ul>
<li>You have a development environment (<code>go</code> command line tooling, an IDE / code editor)</li>
<li>You know how to run and compile a Go program</li>
<li>You understand Go language basics (variables, built-in types, functions, constants, ..)</li>
</ul>
<p>If any of the above is not (yet) true, please check out the previous articles in this series:</p>
<ul>
<li><a href="https://ulrichkautz.com/posts/2020-06-05_practical-go-1-of-3/">1/3 Practical introduction to Go: Development environment</a></li>
<li><a href="https://ulrichkautz.com/posts/2020-06-10_practical-go-2-of-3/">2/3 Practical introduction to Go: Language basics</a></li>
</ul>
<p>After this course you will:</p>
<ul>
<li>Know how to structure a Go application</li>
<li>Understand advanced language elements like structs, methods, interfaces, custom types, &hellip;</li>
<li>Create your own, re-usable and sharable Go modules</li>
<li>Use 3rd party libraries</li>
<li>Write advanced Go CLI applications</li>
<li>Write tests for your Go code</li>
</ul>
<h2 id="overview">Overview</h2>
<p>Since I believe in learning by doing this course will walk you through the development of an application. I will explain on the way how things are done - and why. The application we&rsquo;re going to write will be an HTTP server, providing a REST API for a simple <em>todo management application</em>.</p>
<p>My approach might be coloured by my own opinions and experiences, but - as far as I know - it follows mostly best practices.</p>
<p>Either way, here we go, I hope you enjoy:</p>
<h2 id="planning">Planning</h2>
<p>Before we dive into writing our Go application, let&rsquo;s take a quick breather and consider what we want to achieve. As mentioned above, the goal is to write an HTTP REST server which provides an API to manage todos. So what do we need to make that happen?</p>
<ul>
<li>an HTTP server, handling requests</li>
<li>an API specification, defining how requests and responses look like</li>
<li>a persistence, taking care of storing, removing and accessing todos</li>
<li>also, since security is always a concern: a way to limit access, so that not everyone can meddle with our todos!</li>
</ul>
<h3 id="components">Components</h3>
<p>Ok, having this spelled out, we can alreadu derive some requirements for later implementation. Let&rsquo;s group the requirement into logical <em>components</em>, as in &ldquo;a thing that does a specific thing&rdquo;:</p>
<ul>
<li><em>Component: HTTP server</em> - will expose API via HTTP</li>
<li><em>Component: Persistence</em> - will store, list, read and delete the todos from a &ldquo;storage&rdquo;</li>
<li><em>Component: Authentication</em> - will allow only an authorized list of users to engage with the API</li>
</ul>
<p>With these components, we can also forsee some requirements for the data structures we will need to deal with. Usually these data structures are called <em>models</em>:</p>
<ul>
<li><em>Model: Todo</em> - a representation of the todo in Go, so we can store it, delete it etc</li>
<li><em>Model: User</em> - a representation of the user, which can authenticate with our service and which manipulates the todos</li>
</ul>
<p>That covers the general ideas and concepts. Let&rsquo;s step further into the details:</p>
<h3 id="todo-model">Todo model</h3>
<p>To keep it simple, let&rsquo;s agree a todo will have the following attributes:</p>
<ul>
<li><em>title</em> - a short summary of the todo / task (e.g. <em>&ldquo;go shopping&rdquo;</em>)</li>
<li><em>description</em> - a detailed explanation of the todo (e.g. <em>&ldquo;buy 3 pizzas, 6 beers and 1 avocado&rdquo;</em>)</li>
<li><em>created</em> - a date when the todo was created (e.g. <em>2020-01-02 12:22:33h CET</em>)</li>
<li><em>user</em> - now that we have the user, let&rsquo;s use it: a reference to the user that created the todo</li>
</ul>
<h3 id="user-model">User model</h3>
<p>Also as simple as possible, at least we need:</p>
<ul>
<li><em>name</em> - something to identify the user</li>
<li><em>credentials</em> - something only the user knows for authentication</li>
</ul>
<h3 id="api-specification">API specification</h3>
<p>We set out to create a REST API, so we need to define the endpoints. Before we do that, let&rsquo;s agree to use JSON whenever data (transport) encoding is required.</p>
<ul>
<li><code>POST /todo</code> - creates a new Todo, expects a JSON encoded body of the form <code>{&quot;title&quot;:&quot;&lt;the title&gt;&quot;, &quot;description&quot;:&quot;&lt;the description&gt;&quot;}</code></li>
<li><code>GET /todo</code> - list all Todos in JSON</li>
<li><code>GET /todo/&lt;id&gt;</code> - Returns a specific Todo in JSON or 404</li>
<li><code>DELETE /todo/&lt;id&gt;</code> - Delete a specific Todo or 404 if not existing</li>
</ul>
<p>That should suffice for a first iteration.</p>
<h2 id="structure">Structure</h2>
<p>The first step is always the hardest. To get started with a new application it makes sense to give it a name. That name will be <em>the module name</em>.</p>
<p>Since version 1.11 Go comes with a built-in package manager and introduced <em><a href="https://blog.golang.org/using-go-modules">Go modules</a></em> as a concept. This not only allows you to easily manage dependencies (aka &ldquo;using 3rd party modules&rdquo;), but also suggests a framework where <em>your</em> Go code can live, so that it can be used by 3rd parties (<em>or yourself</em> - always keep in mind: d.r.y. don&rsquo;t-repeat-yourself).</p>
<p>A module, in the Go sense, is a set of Go packages under the same namespace. Those packages need to <em>live somewhere</em>. That <em>somewhere</em> is often a public repository host like <a href="https://github.com">github.com</a>, but can also be a company-internal web server or your local file system.</p>
<ul>
<li><a href="https://golang.org/doc/code.html#Organization">More on the organization of code in Go</a></li>
</ul>
<h3 id="initialize-go-module">Initialize Go module</h3>
<p>Let&rsquo;s jump right into it. Change into your projects directory (=wherever you store your code on your local machine) and create a new directory for your application. I will call it <code>todo-app</code>. In that directory initialize your Go module:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ <span style="color:#a2f">cd</span> ~/Projects
</span></span><span style="display:flex;"><span>$ mkdir todo-app
</span></span><span style="display:flex;"><span>$ <span style="color:#a2f">cd</span> todo-app
</span></span><span style="display:flex;"><span>$ go mod init github.com/ukautz/go-intro/todo-app
</span></span></code></pre></div><p>The last line creates the Go module with the name <code>github.com/ukautz/go-intro/todo-app</code>. This name is not arbitrary, it provides a lot of useful information:</p>
<ul>
<li>It is hosted on Github</li>
<li>It is owned by the Github user <a href="https://github.com/ukautz"><code>ukautz</code></a> - that&rsquo;s me</li>
<li>It is located in the Github repo <a href="https://github.com/ukautz/go-intro"><code>go-intro</code></a></li>
<li>It has the <strong>module import path</strong> <code>github.com/ukautz/go-intro/todo-app</code></li>
</ul>
<p>If you now list the directory contents, you fill find a new file named <code>go.mod</code>. That file should look like this:</p>
<pre tabindex="0"><code>module github.com/ukautz/go-intro/todo-app

go 1.14
</code></pre><p>That reflects exactly what we did:</p>
<ul>
<li><code>module github.com/ukautz/go-intro/todo-app</code>: declares the name of our module</li>
<li><code>go 1.14</code> indicates to the Go compiler that this module depends Go version 1.14 (or above), as this was the Go version I used to execute <code>go mod init</code></li>
</ul>
<h4 id="about-go-version-compatibility">About Go version compatibility</h4>
<p>Go comes with a <a href="https://golang.org/doc/go1compat">promise of compatibility</a>. In short this promise is a commitment that all Go <code>1.x</code> code will be able to run on any future Go <code>1.y</code> version, if <code>1.y</code> &gt; <code>1.x</code>. So far this <a href="https://en.wikipedia.org/wiki/Go_(programming_language)#Version_history">holds true</a>.</p>
<p>However, the reverse is not guaranteed! Every new Go release comes with at least some <a href="https://golang.org/doc/go1.14#library">newly introduced functionality in the standard library</a>. If your Go program uses these new functions, older Go versions won&rsquo;t be able to compile the code anymore.</p>
<h3 id="directory-structure">Directory structure</h3>
<p>There is no <em>official way</em> to structure Go code, but there is the standard library, written by the authors of Go (<a href="https://en.wikipedia.org/wiki/Go_(programming_language)">Rob Pike, Robert Griesemer, Ken Thompson at Google</a>), which is often used to derive good practice and standards from. However, this mostly pertains to structuring Go <em>libraries</em> and helps only somewhat with structuring Go <em>applications</em>.</p>
<p>If you search for <em>&ldquo;Go application structure&rdquo;</em> you will find the <a href="https://github.com/golang-standards/project-layout">Go standard project layout</a>, which collects common layout patterns for Go (application) projects.</p>
<p>The structure I am going to present to you here is mostly adhering to that standard project layout.</p>
<p>The pattern, in essence, separates &ldquo;business logic&rdquo; (=what your application does) from &ldquo;command logic&rdquo; (=how your application is being used) and you might have seen similar strategies in other languages (it&rsquo;s really nothing new). To that end, start out by creating the following directories:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ mkdir -p cmd/server pkg
</span></span></code></pre></div><p>This leaves your with the folder structure:</p>
<pre tabindex="0"><code>cmd/
  server/
pkg/
</code></pre><p>To phrase that in plain English:</p>
<ul>
<li><code>cmd</code> contains the <em>commands</em>, the code that is required to execute your application
<ul>
<li><code>server</code> contains the <em>commands</em> to start the HTTP REST API server (which we are building)</li>
</ul>
</li>
<li><code>pkg</code> contains the package code, your library, your business logic, which will be used by the command - or commands</li>
</ul>
<p>If you are confused about the <code>cmd/server</code>, instead of just <code>cmd</code>: Consider we might adding another command line program, which uses the same library code in <code>pkg</code>. I am thinking here of a client application, which talks to the HTTP API of our server. It would then live in the directory <code>cmd/client</code>. In anticipation of that, because the standard project layout recommends it and because it feels wrong for me break that pattern, I went ahead and complicated things for you ;)</p>
<h2 id="main">Main</h2>
<p>Any program needs to start somewhere. The <code>main</code> package in Go is that starting point for Go programs. Open up <code>cmd/server/main.go</code> in your editor of choice and copy the following as a starting point of our soon-to-be HTTP REST API server.</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>main<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span>(<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;fmt&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;net/http&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">todo</span>(w<span style="color:#bbb"> </span>http.ResponseWriter,<span style="color:#bbb"> </span>r<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>w.<span style="color:#00a000">Write</span>([]<span style="color:#a2f">byte</span>(<span style="color:#b44">&#34;todo&#34;</span>))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">main</span>()<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#b44">&#34;Starting API server&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>http.<span style="color:#00a000">ListenAndServe</span>(<span style="color:#b44">&#34;:12345&#34;</span>,<span style="color:#bbb"> </span>http.<span style="color:#00a000">HandlerFunc</span>(todo));<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f">panic</span>(err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>This is our <strong>main</strong> Go file. Go runs the <code>main</code> function in the <code>main</code> package, when you run it or execute a compiled binary:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ go run cmd/server/main.go
</span></span><span style="display:flex;"><span>Starting API server
</span></span></code></pre></div><p>In another terminal, you can now curl your running HTTP server and see the word <code>todo</code> returned:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ curl http://localhost:12345
</span></span><span style="display:flex;"><span>todo
</span></span></code></pre></div><h3 id="recap-program-anatomy">Recap: Program anatomy</h3>
<p><em>In case you have read the <a href="https://ulrichkautz.com/posts/2015-05-21_practical-go-2-of-3/">previous</a> article in the series, feel free to skip this section.</em></p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>main<span style="color:#bbb">
</span></span></span></code></pre></div><p>Every <code>.go</code> file is in a package and must have a <code>package</code> directive on top of the file. Usually package name match the directory name (so it would be <code>server</code> here). The package name <code>main</code> we used is a special case and required here, as this is our executable part of the code and Go mandates it. There are a few other rules you should keep in mind:</p>
<ul>
<li>every <code>.go</code> file in the same directory must have the same package name (there is an exception for tests, more on that later)</li>
<li>the name should be the same as the folder name they are located in</li>
<li>package names should be <a href="https://golang.org/doc/effective_go.html#package-names">succinct, single-word and no underscores or mixed caps needed</a></li>
</ul>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span>(<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;fmt&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;net/http&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>)<span style="color:#bbb">
</span></span></span></code></pre></div><p>These are <em>package import statements</em>. As we are going to use <code>fmt.Println</code> and various <code>http.*</code> things a few lines below, we first need to import both packages.</p>
<p>You might notice <code>fmt</code> and even <code>net/http</code> are somewhat shorter than our <code>github.com/ukautz/go-intro/todo-app</code>. This is because both are part of the standard library. While we could have also chosen a short module name (eg only <code>todo-app</code>), it is considered bad practice to chose &ldquo;local names&rdquo; (as in short, without url of location) for your own packages. Reason: (among others) those names are used by the Go package manager to download from. So, use location based modules names - or expect headaches in any deploy pipeline.</p>
<p>The last block:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">main</span>()<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#b44">&#34;Starting API server&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>http.<span style="color:#00a000">ListenAndServe</span>(<span style="color:#b44">&#34;:12345&#34;</span>,<span style="color:#bbb"> </span>http.<span style="color:#00a000">HandlerFunc</span>(todo));<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f">panic</span>(err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Well, in short: that prints out the message <code>Starting API server</code> and then starts the HTTP server - and runs until you press <em>ctrl + c</em>.</p>
<h2 id="models">Models</h2>
<p>We already have <a href="#todo-model">generic specification</a> of our model. Translating that into Go we will be using <code>struct</code> (&ldquo;structure&rdquo;), which you can think of something like <code>class</code> in other languages, tho not fully; Go has it&rsquo;s own approach to things. You will see. For now just take with you: <code>struct</code> is especially useful to model anything that has properties or attributes. Like your Todo or User.</p>
<h3 id="todo-model-1">Todo Model</h3>
<p>Create a new file named <code>todo.go</code> in the <code>pkg</code> folder, with the following contents:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>todo<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;time&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Todo<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>ID<span style="color:#bbb">          </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Title<span style="color:#bbb">       </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Description<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Created<span style="color:#bbb">     </span>time.Time<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>UserID<span style="color:#bbb">      </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Ignore all but the <code>type Todo struct {..}</code> for a moment. First: This implements <a href="#todo-model">the model from above</a> in Go. <code>Title</code>, <code>Description</code> and <code>Created</code> should be self-explanatory. The user reference is implemented via the <code>UserID</code> field, which will point to an <code>ID</code> attribute of a following <code>User</code> model. I&rsquo;ve added the <code>ID</code> here as well, so that we have some guaranteed unique value to utilize. This will be simplify reading and deleting a specific Todo via the REST API.</p>
<p><strong>Why <code>todo</code>, not <code>pkg</code>?</strong></p>
<p>The name of the folder the <code>todo.go</code> file is in is <code>pkg</code>. So, per convention, the name of the package should be <code>pkg</code>, not <code>todo</code>.</p>
<p>The reason is that <code>pkg</code> is actual the &ldquo;root folder&rdquo; of our library code. There is no library code &ldquo;above&rdquo; it. Now think of using multiple libraries that you import, that follow that directory structure and are named <code>pkg</code>&hellip; Although you can rename package namespaces during import within the scope of the import, it makes great sense to name it <code>package todo</code> to begin with.</p>
<p>I choose <code>todo</code> as the name as it describes the concern of the package best in my opinion.</p>
<h3 id="structs-in-go">Structs in Go</h3>
<p>A bit more about <code>struct</code>s in Go in general: You might be familiar with object oriented (OO) programming as a concept. While <a href="https://golang.org/doc/faq#Is_Go_an_object-oriented_language">Go has it&rsquo;s own flavor</a> of how to implement OO, ultimately it provides <a href="https://golang.org/doc/faq#Is_Go_an_object-oriented_language">the required features</a>:</p>
<blockquote>
<p>[objects] can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods)</p>
</blockquote>
<h4 id="struct-fields">Struct fields</h4>
<p>In the code above you can see the first part: <em>Objects contain data in the form of fields / attributes</em>. We <strong>declared a type</strong> with the following <strong>fields</strong>:</p>
<ul>
<li><code>ID</code> of type <code>string</code></li>
<li><code>Title</code> of type <code>string</code></li>
<li><code>Description</code> of type <code>string</code></li>
<li><code>Created</code> of type <code>time.Time</code></li>
<li><code>User</code> of type <code>string</code></li>
</ul>
<p>A struct can define any amount of fields - or none, for that matter. It can also have &ldquo;complex&rdquo; attributes, which are themselves structs or slices or slices of structs or interfaces, or any variation thereof. For example:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Nothing<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Something<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Field1<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Field2<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>SubField1<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>SubField2<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>SubSubField1<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">int</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>The <code>Field2</code> attribute is itself a (<em>anonymous</em>) struct, that contains an scalar value (<code>string</code>) and yet another anonymous struct.</p>
<p>In practice, you would often define structs that have properties that are other structs and can contain them yet again. Along the lines of:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Address<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Name<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Street<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>City<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Zip<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">int</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Country<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>BasketItem<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Amount<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">int</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>ItemID<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">int</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Order<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Address<span style="color:#bbb">   </span>Address<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Items<span style="color:#bbb">     </span>[]BasketItem<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Timestamp<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">uint</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><h4 id="instantiating-structs">Instantiating structs</h4>
<p>To make it a bit clearer what you can do with our <code>Todo</code> type, let me give you a quick usage example:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>t<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>Todo{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">    </span>ID:<span style="color:#bbb">          </span><span style="color:#b44">&#34;todo-0001&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Title:<span style="color:#bbb">       </span><span style="color:#b44">&#34;go shopping&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Description:<span style="color:#bbb"> </span><span style="color:#b44">&#34;buy 3 pizzas, 6 beers and 1 avocado&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Created:<span style="color:#bbb">     </span>time.<span style="color:#00a000">Now</span>(),<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>fmt.<span style="color:#00a000">Printf</span>(<span style="color:#b44">&#34;Todo: %s, created %s&#34;</span>,<span style="color:#bbb"> </span>t.Title,<span style="color:#bbb"> </span>t.Created)<span style="color:#bbb">
</span></span></span></code></pre></div><p>The above declares a new variable <code>t</code> (as an instance) of the type <code>Todo</code> and specifies values for the fields of the type, then accesses its fields (here: <code>Created</code> and <code>Title</code>) below.</p>
<p>Note: There is no (programmatic) need to fill in all the available fields. You could also write:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>t<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>Todo{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Description:<span style="color:#bbb"> </span><span style="color:#b44">&#34;buy 3 pizzas, 6 beers and 1 avocado&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>or even</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>t<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>Todo{}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// synonym to</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>t<span style="color:#bbb"> </span>Todo<span style="color:#bbb">
</span></span></span></code></pre></div><p>As a consequence, all &ldquo;not mentioned fields&rdquo; are initialized with their empty value (what that is depends on the attribute-type). In the above case <code>t.Title</code>, as it is not specified, would contain the empty string <code>&quot;&quot;</code>.</p>
<p>The struct fields are also write-accessible after creation:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>t.Title<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#b44">&#34;do something&#34;</span><span style="color:#bbb">
</span></span></span></code></pre></div><h3 id="user-model-1">User Model</h3>
<p>While we are at it, let&rsquo;s also define the above mentioned User model. For that create the file <code>pkg/user.go</code> with the following content:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>todo<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>User<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>ID<span style="color:#bbb">       </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Name<span style="color:#bbb">     </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Password<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>That is even simpler. Note that I diverted from our initial specification a bit:</p>
<ul>
<li>I used <code>Name</code> and <code>Password</code> instead of <code>Credentials</code>, as we are going to use a simple username + password authentication later on</li>
<li>I added an <code>ID</code> attribute - which will be used &ldquo;internally&rdquo;, so even if the <code>Name</code> of the <code>User</code> changes, the <code>ID</code> will stay the same.</li>
</ul>
<h4 id="struct-methods">Struct Methods</h4>
<p>The second property of the OOP definition <em>Objects have functionality / code, in the form of procedures / methods</em> is fully supported with structs.</p>
<p>As an example, consider what I wrote above:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>fmt.<span style="color:#00a000">Printf</span>(<span style="color:#b44">&#34;Todo: %s, created %s&#34;</span>,<span style="color:#bbb"> </span>t.Title,<span style="color:#bbb"> </span>t.Created)<span style="color:#bbb">
</span></span></span></code></pre></div><p>That would print out something like: <code>Todo: &lt;The-Title-Content&gt;, created &lt;Date&gt;</code>.</p>
<p>If there is a need to print out a Todo multiple times (e.g. think of logging), it&rsquo;s a good idea to create a function that renders the string, so it can be re-used. Since <code>Todo</code> is already a struct, we can simply add a <em>method</em> to it:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(t<span style="color:#bbb"> </span>Todo)<span style="color:#bbb"> </span><span style="color:#00a000">String</span>()<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">    </span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>fmt.<span style="color:#00a000">Sprintf</span>(<span style="color:#b44">&#34;%s, created %s&#34;</span>,<span style="color:#bbb"> </span>t.Title,<span style="color:#bbb"> </span>t.Created)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>This is close to a function definition, but it has an additional statement after <code>func</code>. The <code>(t Todo)</code> expression specifies the <strong>receiver</strong>. With <code>t</code> being the <em>receiver instance</em> and <code>Todo</code> the <em>receiver type</em>.</p>
<p>Now that the &ldquo;rendering&rdquo; is wrapped up in a method, we could write:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>fmt.<span style="color:#00a000">Printf</span>(<span style="color:#b44">&#34;Todo: %s&#34;</span>,<span style="color:#bbb"> </span>t.<span style="color:#00a000">String</span>())<span style="color:#bbb">
</span></span></span></code></pre></div><p>Actually, there is even a shorter way:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>fmt.<span style="color:#00a000">Printf</span>(<span style="color:#b44">&#34;Todo: %s&#34;</span>,<span style="color:#bbb"> </span>t)<span style="color:#bbb">
</span></span></span></code></pre></div><p>This works, because the <code>fmt.Printf</code> function is able to use the <code>String() string</code> method automatically. To understand why, you need to know how Go implements <em>interfaces</em>.</p>
<h3 id="interfaces-in-go">Interfaces in Go</h3>
<p>Interfaces are a common concept in many high-level programming languages. In plain terms, an interface is a <em>contract</em>. To use a real-life example, consider the power button <code>⏻</code> you will find on many electronic devices. The <em>contract</em> that button implies is: Pressing it powers a stopped device on and a running device off. It toggles it&rsquo;s running state. In the same way an interface in programming is a contract. Consider the following piece of Go code:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>OnOffSwitch<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">interface</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// TogglePower switches a running device off and a stopped device on</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#00a000">TogglePower</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>The above specifies an interface named <code>OnOffSwitch</code>. The contract states basically: <em>Anything that has a method <code>TogglePower()</code> is of the interface <code>OnOffSwitch</code></em>. This means: <strong>In Go implementation of the methods of an interface, implements that interface.</strong></p>
<p>A code example, implementing the above <code>OnOffSwitch</code> interface, would be:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>RedButton<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(r<span style="color:#bbb"> </span>RedButton)<span style="color:#bbb"> </span><span style="color:#00a000">TogglePower</span>()<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// do something</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>The <code>RedButton</code> struct now implements the <code>OnOffSwitch</code> interface, because it has the <code>TogglePower()</code> method.</p>
<p>In most other programming languages, that I know off, and that have interface concepts, do it the other way around. They have an <em>explicit interface declaration</em>, like:</p>
<pre tabindex="0"><code>class SomeClass implements OnOffSwitch {
    TogglePower() {
        // ..
    }
}
</code></pre><p>Go does not do that. It has <em>implicit interface implementation</em>. If you implement all the methods, the interfaces specifies then you are done. The interfaceis implemented.</p>
<p>And this is why <code>log.Printf(&quot;something %s&quot;, todo)</code> is able to use the <code>String() string</code> method automatically: it just checks if an provided argument is a <code>string</code>, or does have the <code>String() string</code> method. Knowing that Go uses implicit interface implementation, the question &ldquo;does something have method X&rdquo; and &ldquo;does something implements an interface Y that specifies method X&rdquo; are synonym.</p>
<p>To put that into code, here the <code>Stringer</code> interface from the <code>fmt</code> package of the standard library:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Stringer<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">interface</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#00a000">String</span>()<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>With the above interface: Everything that implements <code>Stringer</code> has the <code>String() string</code> method. Also in reverse: everything that has the <code>String() string</code> method implements the <code>Stringer</code> interface. If the interface would have more than one method, then things would need to implement all of the methods - partially doesn&rsquo;t help.</p>
<p>Now back to <code>log.Printf</code>: The implementation of that function would then check: Does the argument I got implements <code>fmt.Stringer</code>? If so, then it has the <code>String() string</code> method, and that can be used.</p>
<p>This is a good segway to the next topic. To check &ldquo;if something implements a method&rdquo;, you need an &ldquo;any type&rdquo; - a type that can be multiple things, can be of multiple types. In Go, that is the empty interface <code>interface{}</code>:</p>
<h4 id="the-empty-interface">The empty interface</h4>
<p>As shown previously, implementing an interface in Go just requires to implement the methods specified in that interface. If additional methods are implemented, Go doesn&rsquo;t care. It just needs to have <em>also</em> the methods of the interface.</p>
<p>Now, with that in mind: What if an interface does not specify <em>any</em> methods? An empty interface, so to speak. Well, from Go&rsquo;s point of view that means: Anything automatically implements that interface, as it cannot be missing any of the methods specified in that interface, as there are none. Or in short: Anything implements the empty interface.</p>
<p>Why is this useful? Consider the <code>log.Printf</code> again. It allows you to pass parameters of any type (after the first, which must be a <code>string</code>). To use a simple example, consider a greeter function, that generates a hello message:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">Greet</span>(anyone<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">interface</span>{})<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">switch</span><span style="color:#bbb"> </span>value<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>anyone.(<span style="color:#a2f;font-weight:bold">type</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">case</span><span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>:<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;Hello &#34;</span><span style="color:#bbb"> </span><span style="color:#666">+</span><span style="color:#bbb"> </span>value<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">case</span><span style="color:#bbb"> </span>fmt.Stringer:<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;Hello &#34;</span><span style="color:#bbb"> </span><span style="color:#666">+</span><span style="color:#bbb"> </span>value.<span style="color:#00a000">String</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">default</span>:<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;Hello unsupported&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>The above uses a common Go pattern, in the context of the empty interface: The <a href="https://tour.golang.org/methods/16">type switch</a>. Basically: Do something different, based on and the type of an argument that can have any type.</p>
<p>The above <code>Greet</code> function would work with <code>string</code> type arguments - or anything that implements the <code>fmt.Stringer</code> interface, so has that <code>String() string</code> method:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Person<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Name<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(p<span style="color:#bbb"> </span>Person)<span style="color:#bbb"> </span><span style="color:#00a000">String</span>()<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>p.Name<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// --%&lt;--</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">main</span>()<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#00a000">Greet</span>(<span style="color:#b44">&#34;Me&#34;</span>))<span style="color:#bbb"> </span><span style="color:#080;font-style:italic">// prints out &#34;Hello Me&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#00a000">Greet</span>(Person{Name:<span style="color:#bbb"> </span><span style="color:#b44">&#34;Alice&#34;</span>}))<span style="color:#bbb"> </span><span style="color:#080;font-style:italic">// prints out &#34;Hello Alice&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>You will see <code>interface{}</code> being used quite often. To give you some examples:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#080;font-style:italic">// as function parameter</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">something</span>(v<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">interface</span>{})<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// as a variable</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>w<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">interface</span>{}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// as a slice variable</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>a<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#a2f">make</span>([]<span style="color:#a2f;font-weight:bold">interface</span>{},<span style="color:#bbb"> </span><span style="color:#666">0</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// as a map</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>m<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#a2f">make</span>(<span style="color:#a2f;font-weight:bold">map</span>[<span style="color:#0b0;font-weight:bold">string</span>]<span style="color:#a2f;font-weight:bold">interface</span>{})<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>n<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#a2f">make</span>(<span style="color:#a2f;font-weight:bold">map</span>[<span style="color:#a2f;font-weight:bold">interface</span>{}]<span style="color:#a2f;font-weight:bold">interface</span>{})<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// ..</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><h2 id="components-1">Components</h2>
<p>That was a lot theory, back to the problem at hand. Now that we have the models, let&rsquo;s get to the components.</p>
<p>First let&rsquo;s look at the <em>HTTP server</em>. Go already comes with an excellent <a href="https://golang.org/pkg/net/http/#Server">HTTP server in the standard library</a>. We already used it in the above <code>main.go</code>. So what we need is an <em>HTTP router</em>, which decides based on the incoming requests which API action is to be executed. That router must then:</p>
<ul>
<li>use the <em>Authentication</em> component to check whether the requests are authenticated</li>
<li>use the <em>Persistence</em> component to store and access the Todos.</li>
</ul>
<p>Ok, let&rsquo;s start with a draft of the HTTP router and find out in implementation what it requires from the other components.</p>
<h3 id="http-router-draft">HTTP router draft</h3>
<p>Previously interfaces where introduced. With that knowledge, let me show you the probably most important interface in Go HTTP handling, the <a href="https://golang.org/pkg/net/http/#Handler"><code>Handler</code></a> from the <a href="https://golang.org/pkg/net/http/"><code>net/http</code></a> package.</p>
<p>It&rsquo;s quite short, have a look:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Handler<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">interface</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#00a000">ServeHTTP</span>(ResponseWriter,<span style="color:#bbb"> </span><span style="color:#666">*</span>Request)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>This means we just need to create a custom type, which has a <code>ServeHTTP(ResponseWriter, *Request)</code> method, and we have an HTTP router!</p>
<p>Let&rsquo;s get started then. Create the file <code>pkg/router.go</code> and add:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>todo<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;net/http&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// Router handles HTTP request routing for the Todo REST API server</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Router<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// ServeHTTP implements the http.Handler interface</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(r<span style="color:#bbb"> </span>Router)<span style="color:#bbb"> </span><span style="color:#00a000">ServeHTTP</span>(rw<span style="color:#bbb"> </span>http.ResponseWriter,<span style="color:#bbb"> </span>req<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// TODO: authenticate each request</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// TODO: handle create, get, list and delete</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>rw.<span style="color:#00a000">Write</span>([]<span style="color:#a2f">byte</span>(<span style="color:#b44">&#34;from the router&#34;</span>))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>As described in the <code>// TODO</code> comments, we&rsquo;re not done yet, but let&rsquo;s go ahead and integrate the <code>Router</code> in the <code>main.go</code>:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>main<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span>(<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;errors&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;fmt&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;net/http&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>todo<span style="color:#bbb"> </span><span style="color:#b44">&#34;github.com/ukautz/go-intro/todo-app/pkg&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">main</span>()<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#b44">&#34;Starting API server&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>router<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>todo.Router{}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>http.<span style="color:#00a000">ListenAndServe</span>(<span style="color:#b44">&#34;:12345&#34;</span>,<span style="color:#bbb"> </span>router);<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f">panic</span>(err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>The server should now return <code>from the router</code> on all requests:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ curl http://localhost:12345
</span></span><span style="display:flex;"><span>from the router
</span></span></code></pre></div><h3 id="authentication-interface">Authentication interface</h3>
<p>To make sure only &ldquo;valid users&rdquo; can access the application, we will need something that makes sure that:</p>
<ul>
<li>each incoming HTTP request is authenticated (or rejected)</li>
<li>for each authentication, the user ID must be known (so it can be used in e.g. in Todo creation).</li>
</ul>
<p>Not considering implementation, the following expresses that in Go:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>todo<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;net/http&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// Authentication permits HTTP requests for known users with valid credentials and rejects all other</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Authentication<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">interface</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// Authenticate returns ID of identified user creating the HTTP request</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#00a000">Authenticate</span>(req<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request)<span style="color:#bbb"> </span>(userID<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Besides the <code>error</code>, which will be returned in case the access is not permitted, or any other internal error ocurred, the <code>userID string</code> will contain the unique identifier of the <code>User</code> that issued the request.</p>
<h3 id="integrate-authentication">Integrate authentication</h3>
<p>Before implementing any actual authentication, let&rsquo;s first integrate it. Going back to <code>pkg/router.go</code>:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>todo<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span>(<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;log&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;net/http&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// Router handles HTTP request routing for the Todo REST API server</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Router<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// Authentication validates that requests are from permitted users</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Authentication<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// ServeHTTP implements the http.Handler interface</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(r<span style="color:#bbb"> </span>Router)<span style="color:#bbb"> </span><span style="color:#00a000">ServeHTTP</span>(rw<span style="color:#bbb"> </span>http.ResponseWriter,<span style="color:#bbb"> </span>req<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// end with an error for all not authenticated requests</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>_,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>r.<span style="color:#00a000">Authenticate</span>(req)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>r.<span style="color:#00a000">handleError</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>rw.<span style="color:#00a000">Write</span>([]<span style="color:#a2f">byte</span>(<span style="color:#b44">&#34;you are authenticated&#34;</span>))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// handleError prints out errors in the logs and lets the request fail</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(r<span style="color:#bbb"> </span>Router)<span style="color:#bbb"> </span><span style="color:#00a000">handleError</span>(rw<span style="color:#bbb"> </span>http.ResponseWriter,<span style="color:#bbb"> </span>req<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>log.<span style="color:#00a000">Printf</span>(<span style="color:#b44">&#34;Error in %s %s: %s&#34;</span>,<span style="color:#bbb"> </span>req.Method,<span style="color:#bbb"> </span>req.URL,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>rw.<span style="color:#00a000">Header</span>().<span style="color:#00a000">Set</span>(<span style="color:#b44">&#34;content-type&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;application/json&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>errors.<span style="color:#00a000">Is</span>(NotAllowedError,<span style="color:#bbb"> </span>err)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>rw.<span style="color:#00a000">WriteHeader</span>(http.StatusForbidden)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>rw.<span style="color:#00a000">Write</span>([]<span style="color:#a2f">byte</span>(<span style="color:#b44">`{&#34;error&#34;:&#34;forbidden&#34;}`</span>))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">else</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>rw.<span style="color:#00a000">WriteHeader</span>(http.StatusInternalServerError)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>rw.<span style="color:#00a000">Write</span>([]<span style="color:#a2f">byte</span>(<span style="color:#b44">`{&#34;error&#34;:&#34;internal server error&#34;}`</span>))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>First take a look how <code>Authentication</code> ise being used in the <code>type Router struct</code>:</p>
<p>Sweet! Although we could not really run that, because we have no implementation yet, of the <code>Authentication</code> interface, the security concern is already addressed in the routing.</p>
<p>Before going into any implementation, let&rsquo;s continue a bit further with the next component:</p>
<h3 id="persistence-interface">Persistence interface</h3>
<p>We can already forsee what we will need from our Persistence component from our API specification: Create, List, Get, Delete on the Todos.</p>
<p>Again, let&rsquo;s start with the interface before implementation. Create <code>pkg/persistence.go</code> with:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>todo<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// Persistence is a storage for todos</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Persistence<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">interface</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// Create stores a new Todo and returns the ID</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#00a000">Create</span>(todo<span style="color:#bbb"> </span>Todo)<span style="color:#bbb"> </span>(<span style="color:#0b0;font-weight:bold">string</span>,<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// Delete removes a single Todo identified by it&#39;s ID. Returns os.ErrNotExist if not found</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#00a000">Delete</span>(id<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// Get fetches a single Todo identified by it&#39;s ID. Returns os.ErrNotExist if not found</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#00a000">Get</span>(id<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span>(<span style="color:#666">*</span>Todo,<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// List returns all Todos</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#00a000">List</span>()<span style="color:#bbb"> </span>([]Todo,<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>This interface matches our requirements. I&rsquo;ve extended the functionality a bit, to make it more convenient in our use-case.</p>
<ul>
<li><code>Create</code> returns the ID of the newly created <code>Todo</code>, so we can return that in the HTTP response</li>
<li><code>Delete</code> must return an <code>os.ErrNotExist</code> error if attempted to remove an not existing Todo, so we can differentiate between that and any other error</li>
<li><code>Get</code> also returns an <code>os.ErrNotExist</code>, if the requests <code>Todo</code> does not exist - also the returned <code>Todo</code> is a pointer, so it can be <code>nil</code> in case it was not found</li>
</ul>
<p>If you were wondering why I chose to (re-)use <code>os.ErrNotExist</code> for our purposes: It&rsquo;s convenient. We could have also defined our own &ldquo;custom&rdquo; error (or error type) for that, but I think this is semantically clear.</p>
<h3 id="integrate-persistence-in-router">Integrate persistence in Router</h3>
<p>With this, we can draft out the rest of the Router (back in <code>pkg/router.go</code>). We need to:</p>
<ol>
<li>build a decision tree to handle the incoming requests (=the routing)</li>
<li>call the respective <code>Persistence</code> methods to implement the REST endpoints</li>
</ol>
<p>First to the decision tree. Modify the <code>ServeHTTP</code> method like so:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#080;font-style:italic">// ServeHTTP implements the http.Handler interface</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(r<span style="color:#bbb"> </span>Router)<span style="color:#bbb"> </span><span style="color:#00a000">ServeHTTP</span>(rw<span style="color:#bbb"> </span>http.ResponseWriter,<span style="color:#bbb"> </span>req<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// end with an error for all not authenticated requests</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>userId,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>r.Authentication.<span style="color:#00a000">Authenticate</span>(req)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>r.<span style="color:#00a000">handleError</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// handle </span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// - POST and GET for /todo </span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// - DELETE and GET for a path looking like /todo/&lt;id&gt;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>path<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>req.URL.Path<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>path<span style="color:#bbb"> </span><span style="color:#666">==</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;/todo&#34;</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">switch</span><span style="color:#bbb"> </span>req.Method<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">case</span><span style="color:#bbb"> </span>http.MethodPost:<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>r.<span style="color:#00a000">create</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span>userId)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">case</span><span style="color:#bbb"> </span>http.MethodGet:<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>r.<span style="color:#00a000">list</span>(rw,<span style="color:#bbb"> </span>req)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">else</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>strings.<span style="color:#00a000">HasPrefix</span>(path,<span style="color:#bbb"> </span><span style="color:#b44">&#34;/todo/&#34;</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>id<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>path[<span style="color:#a2f">len</span>(<span style="color:#b44">&#34;/todo/&#34;</span>):]<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">switch</span><span style="color:#bbb"> </span>req.Method<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">case</span><span style="color:#bbb"> </span>http.MethodDelete:<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>r.<span style="color:#a2f">delete</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span>id)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">case</span><span style="color:#bbb"> </span>http.MethodGet:<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>r.<span style="color:#00a000">get</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span>id)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// anything else, we don&#39;t now</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>rw.<span style="color:#00a000">WriteHeader</span>(http.StatusNotFound)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>rw.<span style="color:#00a000">Write</span>([]<span style="color:#a2f">byte</span>(<span style="color:#b44">&#34;not found&#34;</span>))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>This show-cases a minimal HTTP router in Go implementing our specific requirements. With larger projects you would probably start using a 3rd party library with a more convenient path routing setup. For our use-case this is not required.</p>
<p>Some things of note:</p>
<ul>
<li>the called methods <code>create</code>, <code>list</code>, <code>delete</code> and <code>get</code> do not yet exist (can be found below)</li>
<li>the last two lines, which return a 404: this is executed if the decision tree does not end up in a handled-state, i.e. the fallback for invalid / not implemented requests</li>
<li>the todo <code>id</code> extraction does not account for empty or malformed IDs at this stage, validation should be addressed in an actual application</li>
</ul>
<p>Now to the above mentioned methods, which will implement the calls to the <code>Persistence</code> interface which was defined earlier. Add below the <code>ServeHTTP</code> method:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// --%&lt;--</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// Router handles HTTP request routing for the Todo REST API server</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Router<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// Authentication is used to filter out requests that are not from valid users</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Authentication<span style="color:#bbb"> </span>Authentication<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// Persistence is used to access Todos</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Persistence<span style="color:#bbb"> </span>Persistence<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// --%&lt;--</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(r<span style="color:#bbb"> </span>Router)<span style="color:#bbb"> </span><span style="color:#00a000">create</span>(rw<span style="color:#bbb"> </span>http.ResponseWriter,<span style="color:#bbb"> </span>req<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request,<span style="color:#bbb"> </span>userId<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// read Todo from JSON body of HTTP request</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>todo<span style="color:#bbb"> </span>Todo<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>decoder<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>json.<span style="color:#00a000">NewDecoder</span>(req.Body)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>decoder.<span style="color:#00a000">Decode</span>(<span style="color:#666">&amp;</span>todo);<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>r.<span style="color:#00a000">handleError</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// create Todo in Persistence</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>todo.UserID<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span>userId<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>todoID,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>r.Persistence.<span style="color:#00a000">Create</span>(todo)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>r.<span style="color:#00a000">handleError</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>r.<span style="color:#00a000">json</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">map</span>[<span style="color:#0b0;font-weight:bold">string</span>]<span style="color:#0b0;font-weight:bold">string</span>{<span style="color:#b44">&#34;id&#34;</span>:<span style="color:#bbb"> </span>todoID})<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(r<span style="color:#bbb"> </span>Router)<span style="color:#bbb"> </span><span style="color:#00a000">list</span>(rw<span style="color:#bbb"> </span>http.ResponseWriter,<span style="color:#bbb"> </span>req<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>todos,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>r.Persistence.<span style="color:#00a000">List</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>r.<span style="color:#00a000">handleError</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>r.<span style="color:#00a000">json</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span>todos)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(r<span style="color:#bbb"> </span>Router)<span style="color:#bbb"> </span><span style="color:#a2f">delete</span>(rw<span style="color:#bbb"> </span>http.ResponseWriter,<span style="color:#bbb"> </span>req<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request,<span style="color:#bbb"> </span>todoID<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>r.Persistence.<span style="color:#00a000">Delete</span>(todoID)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>r.<span style="color:#00a000">handleError</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>r.<span style="color:#00a000">json</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">map</span>[<span style="color:#0b0;font-weight:bold">string</span>]<span style="color:#0b0;font-weight:bold">string</span>{<span style="color:#b44">&#34;id&#34;</span>:<span style="color:#bbb"> </span>todoID})<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(r<span style="color:#bbb"> </span>Router)<span style="color:#bbb"> </span><span style="color:#00a000">get</span>(rw<span style="color:#bbb"> </span>http.ResponseWriter,<span style="color:#bbb"> </span>req<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request,<span style="color:#bbb"> </span>todoID<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>todo,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>r.Persistence.<span style="color:#00a000">Read</span>(todoID)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>r.<span style="color:#00a000">handleError</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>r.<span style="color:#00a000">json</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span>todo)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// json prints out a JSON HTTP response</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(r<span style="color:#bbb"> </span>Router)<span style="color:#bbb"> </span><span style="color:#00a000">json</span>(rw<span style="color:#bbb"> </span>http.ResponseWriter,<span style="color:#bbb"> </span>req<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request,<span style="color:#bbb"> </span>data<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">interface</span>{})<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>rw.<span style="color:#00a000">Header</span>().<span style="color:#00a000">Set</span>(<span style="color:#b44">&#34;content-type&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;application/json&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>json.<span style="color:#00a000">NewEncoder</span>(rw).<span style="color:#00a000">Encode</span>(data)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>r.<span style="color:#00a000">handleError</span>(rw,<span style="color:#bbb"> </span>req,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Since we agreed to use JSON for transport encoding, the last method <code>json()</code> prints arbitrary (JSON-transformable) data as an HTTP response with a JSON body.</p>
<p>In the <code>create</code> method the decoding (unmarshalling) of a <code>Todo</code> instance from the JSON body of the incoming HTTP request is show-cased. Then it is created via <code>Persistence</code>.</p>
<p>The other methods do not provide any surprises: They call the respective <code>Persistence</code> method and handle the error with the previously implemented <code>handleError</code> method. If needed they use the <code>json()</code> method to print out JSON formatted responses.</p>
<h3 id="authentication-implementation">Authentication implementation</h3>
<p>Ok, now that we go the basic Router logic in place we need to provide an actual implementation for the <code>Authentication</code> interface. For simplicity sake, let&rsquo;s do <a href="https://en.wikipedia.org/wiki/Basic_access_authentication">HTTP basic authentication</a>.</p>
<p>So what our implementation must do is:</p>
<ul>
<li>Extract the user name and password from the request</li>
<li>Check if there is a valid user with that name and password</li>
</ul>
<p>So two things need to be decided:</p>
<ul>
<li>the authentication method, aka how to extract user name and password from request</li>
<li>access to a list of valid users, to check with for valid credentials</li>
</ul>
<p>Still in the spirit of simplicity let&rsquo;s use a JSON file containing the user credentials.</p>
<h4 id="structs-to-json">Structs to JSON</h4>
<p>Encoding or decoding Go types, especially structs like our <code>User</code> or <code>Todo</code> , from and into transport encoding like JSON is quite simple. To that end, the standard library provides <a href="https://golang.org/pkg/encoding/json/"><code>encoding/json</code></a>.</p>
<p>Assume you have an instance of <code>User</code> like so:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>u<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>User{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>ID:<span style="color:#bbb">       </span><span style="color:#b44">&#34;u01&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Name:<span style="color:#bbb">     </span><span style="color:#b44">&#34;alice&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Password:<span style="color:#bbb"> </span><span style="color:#b44">&#34;secret&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>To encode that into JSON, using <code>encoding/json</code>:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>encoded,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>json.<span style="color:#00a000">Marshal</span>(u)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// ..</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#a2f">string</span>(encoded))<span style="color:#bbb"> </span><span style="color:#080;font-style:italic">// encoded is []byte</span><span style="color:#bbb">
</span></span></span></code></pre></div><p>This would yield the following output:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-json" data-lang="json"><span style="display:flex;"><span>{<span style="color:#008000;font-weight:bold">&#34;ID&#34;</span>:<span style="color:#b44">&#34;u01&#34;</span>,<span style="color:#008000;font-weight:bold">&#34;Name&#34;</span>:<span style="color:#b44">&#34;alice&#34;</span>,<span style="color:#008000;font-weight:bold">&#34;Password&#34;</span>:<span style="color:#b44">&#34;secret&#34;</span>}
</span></span></code></pre></div><p><em>Note: Only public (UpperCase) attributes can be accessed by the encoder. Private (lowerCase) attributes are not part of any resulting encoding.</em></p>
<p>Commonly, you write JSON attributes lowercase. This is easily done in Go. You just need to tell the JSON encoder, what the field names should be. Here is how that looks like, using the <code>User</code> type in the <code>pkg/user.go</code> file:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>User<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>ID<span style="color:#bbb">       </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb"> </span><span style="color:#b44">`json:&#34;id&#34;`</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Name<span style="color:#bbb">     </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb"> </span><span style="color:#b44">`json:&#34;name&#34;`</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Password<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb"> </span><span style="color:#b44">`json:&#34;pass&#34;`</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Each of the attributes has now an added <code>json:&quot;&lt;something&gt;&quot;</code> in backticks `. These expressions are called <a href="https://github.com/golang/go/wiki/Well-known-struct-tags">struct tags</a> and can be used in in <a href="https://blog.golang.org/laws-of-reflection">reflection</a>, which allows you to inspect a variable or type at runtime.</p>
<p>In this case, when we encode an instance of <code>User</code> into JSON, the used <a href="https://pkg.go.dev/encoding/json#Encoder">encoder</a> will be able to get the information from the struct tag and will use it as the JSON attribute/key name, instead of the attribute name (<code>ID</code> -&gt; <code>id</code>). To make that plain:</p>
<p>With the above struct tags, that encoded to JSON would yield:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-json" data-lang="json"><span style="display:flex;"><span>{<span style="color:#008000;font-weight:bold">&#34;id&#34;</span>:<span style="color:#b44">&#34;u01&#34;</span>,<span style="color:#008000;font-weight:bold">&#34;name&#34;</span>:<span style="color:#b44">&#34;alice&#34;</span>,<span style="color:#008000;font-weight:bold">&#34;pass&#34;</span>:<span style="color:#b44">&#34;secret&#34;</span>}
</span></span></code></pre></div><p>The reverse, decoding (aka unmarshalling) from JSON into Go, for example into the <code>User</code> struct, looks like this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>user<span style="color:#bbb"> </span>User<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>encoded<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>[]<span style="color:#a2f">byte</span>(<span style="color:#b44">`{&#34;id&#34;:&#34;u01&#34;,&#34;name&#34;:&#34;alice&#34;,&#34;pass&#34;:&#34;secret&#34;}`</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>json.<span style="color:#00a000">Unmarshal</span>(encoded,<span style="color:#bbb"> </span><span style="color:#666">&amp;</span>user)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// ..</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#b44">&#34;ID&#34;</span>,<span style="color:#bbb"> </span>user.ID)<span style="color:#bbb"> </span><span style="color:#080;font-style:italic">// &#34;u01&#34;</span><span style="color:#bbb">
</span></span></span></code></pre></div><h4 id="load-json-file">Load JSON file</h4>
<p>Now to the JSON file from which the valid users are supposed to be loaded from. Create a <code>data</code> folder in the root of the todo application directory and then create a file named <code>users.json</code> within. Fill it with the following:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-json" data-lang="json"><span style="display:flex;"><span>[
</span></span><span style="display:flex;"><span>  {<span style="color:#008000;font-weight:bold">&#34;id&#34;</span>:<span style="color:#b44">&#34;u01&#34;</span>, <span style="color:#008000;font-weight:bold">&#34;name&#34;</span>:<span style="color:#b44">&#34;alice&#34;</span>, <span style="color:#008000;font-weight:bold">&#34;pass&#34;</span>:<span style="color:#b44">&#34;secret1&#34;</span>},
</span></span><span style="display:flex;"><span>  {<span style="color:#008000;font-weight:bold">&#34;id&#34;</span>:<span style="color:#b44">&#34;u01&#34;</span>, <span style="color:#008000;font-weight:bold">&#34;name&#34;</span>:<span style="color:#b44">&#34;bob&#34;</span>, <span style="color:#008000;font-weight:bold">&#34;pass&#34;</span>:<span style="color:#b44">&#34;secret2&#34;</span>}
</span></span><span style="display:flex;"><span>]
</span></span></code></pre></div><p>An easy implementation of the <code>Authentication</code> interface which uses that JSON file can be found when looking it as two separate problems:</p>
<ul>
<li>decode JSON array of users into slice of <code>User</code></li>
<li>write an <code>Authentication</code> implementation for a list of <code>User</code>s</li>
</ul>
<p>Let&rsquo;s start with the <code>Authentication</code> by appending to the existing file in <code>pkg/authentication.go</code>.</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#080;font-style:italic">// NotAllowedError is returns when access is not permitted</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>NotAllowedError<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span>errors.<span style="color:#00a000">New</span>(<span style="color:#b44">&#34;access not permitted&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// UsersAuthentication checks credentials against a list of users</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>UsersAuthentication<span style="color:#bbb"> </span>[]User<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// Authenticate extracts HTTP basic auth user credentials and returns whether a user</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// in the list has a matching username and password</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(a<span style="color:#bbb"> </span>UsersAuthentication)<span style="color:#bbb"> </span><span style="color:#00a000">Authenticate</span>(req<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request)<span style="color:#bbb"> </span>(<span style="color:#0b0;font-weight:bold">string</span>,<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>name,<span style="color:#bbb"> </span>pass,<span style="color:#bbb"> </span>ok<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>req.<span style="color:#00a000">BasicAuth</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>!ok<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span>fmt.<span style="color:#00a000">Errorf</span>(<span style="color:#b44">&#34;missing credentials: %w&#34;</span>,<span style="color:#bbb"> </span>NotAllowedError)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">for</span><span style="color:#bbb"> </span>_,<span style="color:#bbb"> </span>user<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">range</span><span style="color:#bbb"> </span>a<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#080;font-style:italic">// found a user!</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>user.Name<span style="color:#bbb"> </span><span style="color:#666">==</span><span style="color:#bbb"> </span>name<span style="color:#bbb"> </span><span style="color:#666">&amp;&amp;</span><span style="color:#bbb"> </span>user.Password<span style="color:#bbb"> </span><span style="color:#666">==</span><span style="color:#bbb"> </span>pass<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>user.ID,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span>NotAllowedError<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>The <code>UsersAuthentication</code> type extends the <code>[]User</code> (slice) type. The defined <code>Authenticate</code> method then implements the <code>Authentication</code> interface. That is pretty neat, as we now are just left with loading the JSON file into a <code>[]User</code>-type variable and then can use that directly.</p>
<p><em>Note: I added <code>NotAllowedError</code> so we have a specific error to differentiate, for example, from file read problems.</em></p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#080;font-style:italic">// LoadAuthenticationFromJSON reads a JSON file, returns an Authentication implementation</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">LoadAuthenticationFromJSON</span>(filename<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span>(Authentication,<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// define a slice of users &amp; fill it from a JSON file</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>users<span style="color:#bbb"> </span>[]User<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>encoded,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>ioutil.<span style="color:#00a000">ReadFile</span>(filename)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span>,<span style="color:#bbb"> </span>err<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">else</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span>json.<span style="color:#00a000">Unmarshal</span>(encoded,<span style="color:#bbb"> </span><span style="color:#666">&amp;</span>users);<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span>,<span style="color:#bbb"> </span>err<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// cast the slice of users into an Authentication implementation</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#00a000">UsersAuthentication</span>(users),<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>That gives us a good-enough Authentication component for the moment. Since we used an interface, we can later write something using LDAP, AWS DynamoDB or whatever makes sense and just switch it out.</p>
<h3 id="persistence-implementation">Persistence implementation</h3>
<p>Continuing with JSON as the encoding for our structs, let us first add some struct tags to the <code>Todo</code> struct type. Open <code>pkg/todo.go</code> again and modify:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Todo<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>ID<span style="color:#bbb">          </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">    </span><span style="color:#b44">`json:&#34;id&#34;`</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Title<span style="color:#bbb">       </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">    </span><span style="color:#b44">`json:&#34;title&#34;`</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Description<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">    </span><span style="color:#b44">`json:&#34;description&#34;`</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Created<span style="color:#bbb">     </span>time.Time<span style="color:#bbb"> </span><span style="color:#b44">`json:&#34;created&#34;`</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>UserID<span style="color:#bbb">      </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">    </span><span style="color:#b44">`json:&#34;user_id&#34;`</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Basically CamelCase to snake_case. With that decided, let&rsquo;s agree on the file system as the storage, in the manner:</p>
<pre tabindex="0"><code>&lt;base-directory&gt;/&lt;id&gt;.json
</code></pre><p>So bascially: All todos will live in the same directory in a file named after their ID plus the <code>.json</code> suffix.</p>
<p>Considering the <code>Persistence</code> interface, our directory-based implementation will do roughly</p>
<ul>
<li><em>Get(id)</em> will open a file <code>&lt;base-dir&gt;/&lt;id&gt;.json</code>, decode from JSON into <code>Todo</code> and return that</li>
<li><em>Delete(id)</em> will remove a file <code>&lt;base-dir&gt;/&lt;id&gt;.json</code>, if it exists</li>
<li><em>List()</em> will enumerate &amp; decode all JSON files in <code>&lt;base-dir&gt;</code></li>
<li><em>Create(todo)</em> will create a new ID and then store JSON encoded <code>Todo</code> in <code>&lt;base-dir&gt;/&lt;id&gt;.json</code></li>
</ul>
<h4 id="use-3rd-party-libraries">Use 3rd party libraries</h4>
<p>Our <code>Todo</code> struct contains an <code>ID</code> attribute, which should contain a unique identifier. An <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">UUID</a> is a good choice. There are many Go implementations, I suggest <a href="https://github.com/google/uuid">github.com/google/uuid</a>, which is well tested in production.</p>
<p>While Go downloads dependencies whenever you run it (or build, or test, ..), I prefer explicit download of dependencies from the command line (so I  see the dependencies it might have):</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ go get -v github.com/google/uuid
</span></span><span style="display:flex;"><span>go: github.com/google/uuid <span style="color:#b8860b">upgrade</span> <span style="color:#666">=</span>&gt; v1.1.1
</span></span><span style="display:flex;"><span>github.com/google/uuid
</span></span></code></pre></div><p><em>Note: This will extend both <code>go.mod</code> and <code>go.sum</code></em></p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ cat go.mod 
</span></span><span style="display:flex;"><span>module github.com/ukautz/go-intro/todo-app
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>go 1.14
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>require github.com/google/uuid v1.1.1 // indirect
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>$ cat go.sum 
</span></span><span style="display:flex;"><span>github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY<span style="color:#666">=</span>
</span></span><span style="display:flex;"><span>github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+y
</span></span></code></pre></div><h4 id="json-file-persistence">JSON file Persistence</h4>
<p>Open the file <code>pkg/persistence.go</code> again and add:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// --%&lt;--</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// in imports add:</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;github.com/google/uuid&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// --%&lt;--</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// DirectoryPersistence implements Persistence with a local file system directory</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>DirectoryPersistence<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// Create stores Todo in &lt;directory&gt;/&lt;id&gt;.json file</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(p<span style="color:#bbb"> </span>DirectoryPersistence)<span style="color:#bbb"> </span><span style="color:#00a000">Create</span>(todo<span style="color:#bbb"> </span>Todo)<span style="color:#bbb"> </span>(<span style="color:#0b0;font-weight:bold">string</span>,<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>todo.ID<span style="color:#bbb"> </span><span style="color:#666">==</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>todo.ID<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span>uuid.<span style="color:#00a000">New</span>().<span style="color:#00a000">String</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>encoded,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>json.<span style="color:#00a000">Marshal</span>(todo)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span>err<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>path<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>p.<span style="color:#00a000">path</span>(todo.ID)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>err<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span>ioutil.<span style="color:#00a000">WriteFile</span>(path,<span style="color:#bbb"> </span>encoded,<span style="color:#bbb"> </span><span style="color:#666">0640</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span>err<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>todo.ID,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// Delete removes &lt;directory&gt;/&lt;id&gt;.json file</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(p<span style="color:#bbb"> </span>DirectoryPersistence)<span style="color:#bbb"> </span><span style="color:#00a000">Delete</span>(id<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>os.<span style="color:#00a000">Remove</span>(p.<span style="color:#00a000">path</span>(id))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// Get reads Todo from &lt;directory&gt;/&lt;id&gt;.json file</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(p<span style="color:#bbb"> </span>DirectoryPersistence)<span style="color:#bbb"> </span><span style="color:#00a000">Get</span>(id<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span>(<span style="color:#666">*</span>Todo,<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>p.<span style="color:#00a000">read</span>(p.<span style="color:#00a000">path</span>(id))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// List reads all Todos from &lt;id&gt;.json files in &lt;directory&gt;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(p<span style="color:#bbb"> </span>DirectoryPersistence)<span style="color:#bbb"> </span><span style="color:#00a000">List</span>()<span style="color:#bbb"> </span>([]Todo,<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>todos<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#a2f">make</span>([]Todo,<span style="color:#bbb"> </span><span style="color:#666">0</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>filepath.<span style="color:#00a000">Walk</span>(<span style="color:#a2f">string</span>(p),<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">func</span>(path<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>,<span style="color:#bbb"> </span>info<span style="color:#bbb"> </span>os.FileInfo,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>err<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>}<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">else</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>info.<span style="color:#00a000">IsDir</span>()<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>}<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">else</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>filepath.<span style="color:#00a000">Ext</span>(path)<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;.json&#34;</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>todo,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>p.<span style="color:#00a000">read</span>(path)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>err<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>todos<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#a2f">append</span>(todos,<span style="color:#bbb"> </span><span style="color:#666">*</span>todo)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>})<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>todos,<span style="color:#bbb"> </span>err<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(p<span style="color:#bbb"> </span>DirectoryPersistence)<span style="color:#bbb"> </span><span style="color:#00a000">path</span>(id<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>filepath.<span style="color:#00a000">Join</span>(<span style="color:#a2f">string</span>(p),<span style="color:#bbb"> </span>id<span style="color:#666">+</span><span style="color:#b44">&#34;.json&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(p<span style="color:#bbb"> </span>DirectoryPersistence)<span style="color:#bbb"> </span><span style="color:#00a000">read</span>(path<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span>(<span style="color:#666">*</span>Todo,<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>fh<span style="color:#bbb"> 
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>encoded,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>ioutil.<span style="color:#00a000">ReadFile</span>(path)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span>,<span style="color:#bbb"> </span>err<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>todo<span style="color:#bbb"> </span>Todo<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span>json.<span style="color:#00a000">Unmarshal</span>(encoded,<span style="color:#bbb"> </span><span style="color:#666">&amp;</span>todo);<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span>,<span style="color:#bbb"> </span>err<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#666">&amp;</span>todo,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>That should be largely self-explanatory. The following statement might be a bit surprising:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>DirectoryPersistence<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span></code></pre></div><p>Reason: The type could be structured instead like <code>type DirectoryPersistence struct { Directory string }</code>, but that would not gain much, but add complexity.</p>
<p>The respective public methods (with uppercase first letter) implement the the <code>Persistence</code> interface as intended.</p>
<p>To not repeat code, the following helper methods are implemented:</p>
<ul>
<li><code>path(id)</code> - generates the full <code>&lt;base-dir&gt;/&lt;id&gt;.json</code> file path for a given ID</li>
<li><code>read(path)</code> - is used by <code>List</code> and <code>Get</code> alike to read &amp; decode a JSON file into a <code>Todo</code></li>
</ul>
<h3 id="bring-it-all-together">Bring it all together</h3>
<p>Now that we have both working <code>Authentication</code> and <code>Persistence</code> implementations, all can be setup together in the main method. Since this is about practical application development, let me introduce the <a href="https://github.com/urfave/cli">urfarve/cli</a> library to you. It&rsquo;s a very commonly used CLI framework.</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ go get -v github.com/urfave/cli/v2
</span></span><span style="display:flex;"><span>go: github.com/urfave/cli/v2 <span style="color:#b8860b">upgrade</span> <span style="color:#666">=</span>&gt; v2.2.0
</span></span></code></pre></div><p>This framework has a nice interface to rapidly develop simple or complex command line applications. I even use it for very small tools, just because it supports very readable code structures. I recommend to <a href="https://github.com/urfave/cli/blob/master/docs/v2/manual.md">look into the extensive documentation, with many examples</a>.</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>main<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span>(<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;log&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;net/http&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;os&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;path/filepath&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>todo<span style="color:#bbb"> </span><span style="color:#b44">&#34;github.com/ukautz/go-intro/todo-app/pkg&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;github.com/urfave/cli/v2&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">main</span>()<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>app<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>cli.<span style="color:#00a000">NewApp</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>app.Name<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#b44">&#34;server&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>app.Usage<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#b44">&#34;HTTP API for todos&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>app.Flags<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span>[]cli.Flag{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#666">&amp;</span>cli.StringFlag{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Name:<span style="color:#bbb">    </span><span style="color:#b44">&#34;storage-directory&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Aliases:<span style="color:#bbb"> </span>[]<span style="color:#0b0;font-weight:bold">string</span>{<span style="color:#b44">&#34;d&#34;</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Usage:<span style="color:#bbb">   </span><span style="color:#b44">&#34;Path to directory to store todos&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Value:<span style="color:#bbb">   </span>filepath.<span style="color:#00a000">Join</span>(<span style="color:#b44">&#34;data&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;store&#34;</span>),<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#666">&amp;</span>cli.StringFlag{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Name:<span style="color:#bbb">    </span><span style="color:#b44">&#34;users&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Aliases:<span style="color:#bbb"> </span>[]<span style="color:#0b0;font-weight:bold">string</span>{<span style="color:#b44">&#34;u&#34;</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Usage:<span style="color:#bbb">   </span><span style="color:#b44">&#34;Path to JSON file containing user credentials&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Value:<span style="color:#bbb">   </span>filepath.<span style="color:#00a000">Join</span>(<span style="color:#b44">&#34;data&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;users.json&#34;</span>),<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#666">&amp;</span>cli.StringFlag{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Name:<span style="color:#bbb">    </span><span style="color:#b44">&#34;address&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Aliases:<span style="color:#bbb"> </span>[]<span style="color:#0b0;font-weight:bold">string</span>{<span style="color:#b44">&#34;a&#34;</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Usage:<span style="color:#bbb">   </span><span style="color:#b44">&#34;Listen address for the HTTP server&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Value:<span style="color:#bbb">   </span><span style="color:#b44">&#34;127.0.0.1:12345&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#666">&amp;</span>cli.StringFlag{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Name:<span style="color:#bbb">    </span><span style="color:#b44">&#34;path-prefix&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Aliases:<span style="color:#bbb"> </span>[]<span style="color:#0b0;font-weight:bold">string</span>{<span style="color:#b44">&#34;p&#34;</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Usage:<span style="color:#bbb">   </span><span style="color:#b44">&#34;Prefix for &#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Value:<span style="color:#bbb">   </span><span style="color:#b44">&#34;/v1&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>app.Action<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">func</span>(c<span style="color:#bbb"> </span><span style="color:#666">*</span>cli.Context)<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>listenAddr<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>c.<span style="color:#00a000">String</span>(<span style="color:#b44">&#34;address&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>routePrefix<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>c.<span style="color:#00a000">String</span>(<span style="color:#b44">&#34;path-prefix&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#080;font-style:italic">// init storage</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>store<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>todo.<span style="color:#00a000">DirectoryPersistence</span>(c.<span style="color:#00a000">String</span>(<span style="color:#b44">&#34;storage-directory&#34;</span>))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#080;font-style:italic">// load users for authentication</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>usersFile<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>c.<span style="color:#00a000">String</span>(<span style="color:#b44">&#34;users&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>auth,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>todo.<span style="color:#00a000">LoadAuthenticationFromJSON</span>(usersFile)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>err<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#080;font-style:italic">// setup router</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>router<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>todo.Router{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Prefix:<span style="color:#bbb">         </span>routePrefix,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Authentication:<span style="color:#bbb"> </span>auth,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>Persistence:<span style="color:#bbb">    </span>store,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#080;font-style:italic">// run server</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>log.<span style="color:#00a000">Printf</span>(<span style="color:#b44">&#34;Starting API server at http://%s%s, storage directory: %s&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>listenAddr,<span style="color:#bbb"> </span>routePrefix,<span style="color:#bbb"> </span>store)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>http.<span style="color:#00a000">ListenAndServe</span>(listenAddr,<span style="color:#bbb"> </span>router)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>app.<span style="color:#00a000">Run</span>(os.Args)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f">panic</span>(err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Ok, before going through all of that, best run the application once with the <code>-h</code> help flag:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ go run cmd/server/main.go -h
</span></span><span style="display:flex;"><span>NAME:
</span></span><span style="display:flex;"><span>   server - HTTP API <span style="color:#a2f;font-weight:bold">for</span> todos
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>USAGE:
</span></span><span style="display:flex;"><span>   main <span style="color:#666">[</span>global options<span style="color:#666">]</span> <span style="color:#a2f">command</span> <span style="color:#666">[</span><span style="color:#a2f">command</span> options<span style="color:#666">]</span> <span style="color:#666">[</span>arguments...<span style="color:#666">]</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>COMMANDS:
</span></span><span style="display:flex;"><span>   help, h  Shows a list of commands or <span style="color:#a2f">help</span> <span style="color:#a2f;font-weight:bold">for</span> one <span style="color:#a2f">command</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>GLOBAL OPTIONS:
</span></span><span style="display:flex;"><span>   --storage-directory value, -d value  Path to directory to store todos <span style="color:#666">(</span>default: <span style="color:#b44">&#34;data/store&#34;</span><span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>   --users value, -u value              Path to JSON file containing user credentials <span style="color:#666">(</span>default: <span style="color:#b44">&#34;data/users.json&#34;</span><span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>   --address value, -a value            Listen address <span style="color:#a2f;font-weight:bold">for</span> the HTTP server <span style="color:#666">(</span>default: <span style="color:#b44">&#34;127.0.0.1:12345&#34;</span><span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>   --path-prefix value, -p value        Prefix <span style="color:#a2f;font-weight:bold">for</span>  <span style="color:#666">(</span>default: <span style="color:#b44">&#34;/v1&#34;</span><span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>   --help, -h                           show <span style="color:#a2f">help</span> <span style="color:#666">(</span>default: <span style="color:#a2f">false</span><span style="color:#666">)</span>
</span></span></code></pre></div><p>As you can see, this is a quite nice interface already. Have a look at the rendered out options, their default values, aliases etc and how that matches their implementation.</p>
<p>To run the application, first make sure:</p>
<ul>
<li><code>data/store</code> folder exists - or any folder you specify with <code>--storage-directory</code></li>
<li><code>data/users.json</code> exist (with example code from above), or any file you specify with <code>--users</code></li>
</ul>
<p>Then run:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>go run cmd/server/main.go 
</span></span><span style="display:flex;"><span>2020/05/20 17:39:42 Starting API server at http://127.0.0.1:12345/v1, storage directory: data/store
</span></span></code></pre></div><p>In another terminal, you can now use the API with <code>curl</code>:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span><span style="color:#080;font-style:italic"># create a new todo</span>
</span></span><span style="display:flex;"><span>$ curl -s -u <span style="color:#b44">&#34;alice:secret1&#34;</span> -X POST http://127.0.01:12345/v1/todo <span style="color:#b62;font-weight:bold">\
</span></span></span><span style="display:flex;"><span>	-d <span style="color:#b44">&#34;{\&#34;title\&#34;:\&#34;my first todo\&#34;, \&#34;description\&#34;:\&#34;api must be played with\&#34;}&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic"># list all todos</span>
</span></span><span style="display:flex;"><span>$ curl -s -u <span style="color:#b44">&#34;alice:secret1&#34;</span> http://127.0.01:12345/v1/todo
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic"># get a specific todo</span>
</span></span><span style="display:flex;"><span>$ curl -s -u <span style="color:#b44">&#34;alice:secret1&#34;</span> http://127.0.01:12345/v1/todo/SOME_ID
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic"># delete a specific todo</span>
</span></span><span style="display:flex;"><span>$ curl -s -u <span style="color:#b44">&#34;alice:secret1&#34;</span> -X DELETE http://127.0.01:12345/v1/todo/SOME_ID
</span></span></code></pre></div><h2 id="testing">Testing</h2>
<p>While the application is &ldquo;feature complete&rdquo;, according to the requirements, the development is not done. Any software, which needs to be maintained (which is any software you don&rsquo;t throw out immediately), should have a test-suite.</p>
<p>Go provides an easy to use tooling and language support and there is a large number of 3rd party libraries to satisfy any taste of writing tests.</p>
<h3 id="writing-tests-in-go">Writing tests in Go</h3>
<p>Before going into the specific tests for this application, let me give you first an introduction on how to write tests in Go in a more general sense.</p>
<p>It&rsquo;s not hard, the Go tooling comes already with all you need, including conventions on how to structure files and name tests.</p>
<p>Test files should always live in the same directory as the code they are testing. The convention is to create a new file named the same as the file containing the actual code, just with a suffix <code>_test</code>. For example, if you wish to write tests for code in a file named <code>app.go</code>, you would do so in the file <code>app_test.go</code>.</p>
<p>Let&rsquo;s look at some code to make that clear. Assume the following code, which is to be tested:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#080;font-style:italic">// file: app.go</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>myapp<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">Multiply</span>(a,<span style="color:#bbb"> </span>b<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">int</span>)<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">int</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>a<span style="color:#bbb"> </span><span style="color:#666">*</span><span style="color:#bbb"> </span>b<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>In the same directory:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#080;font-style:italic">// file: app_test.go</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>myapp_test<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;testing&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">TestMultiply</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing.T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// here come the tests</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>We will fill in some actual test code in a moment, let&rsquo;s quickly go through the test file:</p>
<ul>
<li><code>package myapp_test</code> - if you remember Go does not allow for different package names within the same directory, this was not entirely true: there is an exception for test files. The reason is, with having all tests in the <code>myapp_test</code> &ldquo;namespace&rdquo;, you are forced to test <em>only the public interface</em> (public functions, methods etc), because, since it is in a different package, you can only access the public interface of the code you want to write tests for! This is not a hard convention. You will find many tests using the same package (<code>myapp</code>) as the code.</li>
<li><code>import &quot;testing&quot;</code> - this imports the Golang testing package, which provides all you need to run tests (and benchmarks, but this is another story)</li>
<li><code>func TestMultiply(t *testing.T)</code> - this will contain the actual test. The prefix of the function name <code>Test</code> is mandatory. Go needs it to identify this function as a test. Als mandatory is the exact signature <code>(t *testing.T)</code>.</li>
</ul>
<p>Now, fill that test with something senseful:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#080;font-style:italic">// file: app_test.go</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>myapp_test<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span>(<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;testing&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;github.com/acme/myapp&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">TestMultiply</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing.T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>result<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>myapp.<span style="color:#00a000">Multiply</span>(<span style="color:#666">5</span>,<span style="color:#bbb"> </span><span style="color:#666">10</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>result<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#666">50</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>t.<span style="color:#00a000">Errorf</span>(<span style="color:#b44">&#34;expected 50, got %d&#34;</span>,<span style="color:#bbb"> </span>result)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>To run this test we can use the <code>go test</code> command. I am adding the <code>-v</code> parameter for verbosity and the path to the test file:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ go <span style="color:#a2f">test</span> -v app_test.go
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestMultiply
</span></span><span style="display:flex;"><span>--- PASS: TestMultiply <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>PASS
</span></span><span style="display:flex;"><span>ok  	command-line-arguments	0.002s
</span></span></code></pre></div><p>This looks good, the test is green!</p>
<p><em>Note: If you would omit the path to the test file (<code>app_test.go</code>) and just write <code>go test -v</code>, then all tests in all <code>_test.go</code> files in the current directory would be executed.</em></p>
<p><em>Note: If you want to run all the tests in the current directory and all sub-directories do: <code>go test -v ./...</code> with <code>./...</code> meaning: traverse this and all sub-directories recursively</em></p>
<p>So you have seen it, let&rsquo;s make the test fail once by changing the condition:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">TestMultiply</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing.T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>result<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>todo.<span style="color:#00a000">Multiply</span>(<span style="color:#666">5</span>,<span style="color:#bbb"> </span><span style="color:#666">10</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>result<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#666">40</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>t.<span style="color:#00a000">Errorf</span>(<span style="color:#b44">&#34;expected 40, got %d&#34;</span>,<span style="color:#bbb"> </span>result)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>The output would look like this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ go <span style="color:#a2f">test</span> -v app_test.go
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestMultiply
</span></span><span style="display:flex;"><span>    TestMultiply: app_test.go:13: expected 40, got <span style="color:#666">50</span>
</span></span><span style="display:flex;"><span>--- FAIL: TestMultiply <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>FAIL
</span></span><span style="display:flex;"><span>FAIL	command-line-arguments	0.002s
</span></span><span style="display:flex;"><span>FAIL
</span></span></code></pre></div><h4 id="pattern-list-tests">Pattern: List tests</h4>
<p>While this is only an artificial example, there is already something to optimize. The above test only checks for a single, arbitrary chosen multiplication. In &ldquo;real life&rdquo;, you want to test more thoroughly. You could either create multiple test functions (<code>TestMultiply1</code>, <code>TestMultiply2</code>, &hellip;) or do a list test like so:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">TestMultiply</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing.T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>expects<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>[]<span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>a,<span style="color:#bbb"> </span>b<span style="color:#bbb">   </span><span style="color:#0b0;font-weight:bold">int</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>result<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">int</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>{<span style="color:#666">1</span>,<span style="color:#bbb"> </span><span style="color:#666">1</span>,<span style="color:#bbb"> </span><span style="color:#666">1</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>{<span style="color:#666">1</span>,<span style="color:#bbb"> </span><span style="color:#666">2</span>,<span style="color:#bbb"> </span><span style="color:#666">2</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>{<span style="color:#666">2</span>,<span style="color:#bbb"> </span><span style="color:#666">2</span>,<span style="color:#bbb"> </span><span style="color:#666">4</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>{<span style="color:#666">3</span>,<span style="color:#bbb"> </span><span style="color:#666">3</span>,<span style="color:#bbb"> </span><span style="color:#666">9</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>{<span style="color:#666">3</span>,<span style="color:#bbb"> </span><span style="color:#666">4</span>,<span style="color:#bbb"> </span><span style="color:#666">12</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>{<span style="color:#666">333</span>,<span style="color:#bbb"> </span><span style="color:#666">777</span>,<span style="color:#bbb"> </span><span style="color:#666">258741</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">for</span><span style="color:#bbb"> </span>_,<span style="color:#bbb"> </span>expect<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">range</span><span style="color:#bbb"> </span>expects<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>t.<span style="color:#00a000">Run</span>(fmt.<span style="color:#00a000">Sprintf</span>(<span style="color:#b44">&#34;expect %d * %d = %d&#34;</span>,<span style="color:#bbb"> </span>expect.a,<span style="color:#bbb"> </span>expect.b,<span style="color:#bbb"> </span>expect.result),<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">func</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing.T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>result<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>todo.<span style="color:#00a000">Multiply</span>(expect.a,<span style="color:#bbb"> </span>expect.b)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>result<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span>expect.result<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">				</span>t.<span style="color:#00a000">Errorf</span>(<span style="color:#b44">&#34;expected %d, got %d&#34;</span>,<span style="color:#bbb"> </span>expect.result,<span style="color:#bbb"> </span>result)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>})<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>This is a very common pattern you will find in many Go test files. The construct setting up the tests expectations might be a bit unfamiliar, so let me explain:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>expects<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>[]<span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>a,<span style="color:#bbb"> </span>b<span style="color:#bbb">   </span><span style="color:#0b0;font-weight:bold">int</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>result<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">int</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>{<span style="color:#666">1</span>,<span style="color:#bbb"> </span><span style="color:#666">1</span>,<span style="color:#bbb"> </span><span style="color:#666">1</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// ...</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>This creates a list of anonymous structs, which have three int attributes (<code>a</code>, <code>b</code> and <code>result</code>) and initialize them with a set of values. The first line <code>{1, 1, 1}</code> sets <code>a</code>, <code>b</code> and <code>result</code> to <code>1</code>.</p>
<p>This pattern is quite helpful, both for brevity and readability. When executing the test the <code>t.Run(..)</code> command will print out the sub-tests it ran:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ go <span style="color:#a2f">test</span> -v app_test.go
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   <span style="color:#b8860b">TestMultiply</span>
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestMultiply/expect_1_*_1_<span style="color:#666">=</span><span style="color:#b8860b">_1</span>
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestMultiply/expect_1_*_2_<span style="color:#666">=</span><span style="color:#b8860b">_2</span>
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestMultiply/expect_2_*_2_<span style="color:#666">=</span><span style="color:#b8860b">_4</span>
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestMultiply/expect_3_*_3_<span style="color:#666">=</span><span style="color:#b8860b">_9</span>
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestMultiply/expect_3_*_4_<span style="color:#666">=</span><span style="color:#b8860b">_12</span>
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestMultiply/expect_333_*_777_<span style="color:#666">=</span>_258741
</span></span><span style="display:flex;"><span>--- PASS: TestMultiply <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>    --- PASS: TestMultiply/expect_1_*_1_<span style="color:#666">=</span>_1 <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>    --- PASS: TestMultiply/expect_1_*_2_<span style="color:#666">=</span>_2 <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>    --- PASS: TestMultiply/expect_2_*_2_<span style="color:#666">=</span>_4 <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>    --- PASS: TestMultiply/expect_3_*_3_<span style="color:#666">=</span>_9 <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>    --- PASS: TestMultiply/expect_3_*_4_<span style="color:#666">=</span>_12 <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>    --- PASS: TestMultiply/expect_333_*_777_<span style="color:#666">=</span>_258741 <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>PASS
</span></span><span style="display:flex;"><span>ok  	command-line-arguments	0.002s
</span></span></code></pre></div><h3 id="3rd-party-test-libraries">3rd party test libraries</h3>
<p>While the standard library <code>testing</code> package comes with all you need to write tests, there are various 3rd party libraries making things easier and providing different flavours.</p>
<p>The most important ones, in my experience, are:</p>
<ul>
<li><a href="https://github.com/stretchr/testify">github.com/stretchr/testify</a> - clean API, easy readable code, supports test-suites &amp; helpers for mocking</li>
<li><a href="http://onsi.github.io/ginkgo/">Ginkgo</a> and <a href="https://github.com/smartystreets/goconvey/">GoConvey</a> - Write tests BDD style</li>
</ul>
<p>I am a big fan of testify, due to it&rsquo;s neat and readable API and will use it in the tests for this application. As any external dependency I prefer to install it before using it:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ go get -v github.com/stretchr/testify    
</span></span><span style="display:flex;"><span>go: github.com/stretchr/testify <span style="color:#b8860b">upgrade</span> <span style="color:#666">=</span>&gt; v1.6.1
</span></span></code></pre></div><p>Rewriting the above <code>TestMultiply</code> using testify would look like:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>todo_test<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span>(<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;testing&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;github.com/stretchr/testify/assert&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;github.com/acme/myapp&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">TestMultiply</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing.T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span><span style="color:#666">50</span>,<span style="color:#bbb"> </span>myapp.<span style="color:#00a000">Multiply</span>(<span style="color:#666">5</span>,<span style="color:#bbb"> </span><span style="color:#666">10</span>))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>I think this is much more expressive than the standard Go testing tooling. Changing that <code>50</code> to the (wrong) expectation <code>40</code> again, the testify library also provides a much better readable failure reporting:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestMultiply
</span></span><span style="display:flex;"><span>    app_test.go:11: 
</span></span><span style="display:flex;"><span>        	Error Trace:	app_test.go:11
</span></span><span style="display:flex;"><span>        	Error:      	Not equal: 
</span></span><span style="display:flex;"><span>        	            	expected: <span style="color:#666">40</span>
</span></span><span style="display:flex;"><span>        	            	actual  : <span style="color:#666">50</span>
</span></span><span style="display:flex;"><span>        	Test:       	TestMultiply
</span></span><span style="display:flex;"><span>--- FAIL: TestMultiply <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>FAIL
</span></span><span style="display:flex;"><span>FAIL	command-line-arguments	0.002s
</span></span><span style="display:flex;"><span>FAIL
</span></span></code></pre></div><p>All in all, I prefer testify much over the standard tooling, hence I am going to use it in the actual test of this application. Check out the available <a href="https://pkg.go.dev/github.com/stretchr/testify/require#pkg-index">assertions in the documentation</a>.</p>
<h3 id="test-authentication">Test: Authentication</h3>
<p>To test our authentication we need to test the method <code>Authenticate(*http.Request) (string, error)</code> of the <code>UsersAuthentication</code> implementation.</p>
<p>To describe that intention in a Go test function name you will find usually the naming pattern <code>Test&lt;Type&gt;_&lt;Method&gt;</code> in testing code, as in:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">TestUsersAuthentication_Authenticate</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing<span style="color:#bbb"> </span>T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// todo</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Create <code>pkg/authorization_test.go</code> with the following contents:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>todo_test<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span>(<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;net/http&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;net/http/httptest&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;testing&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;github.com/stretchr/testify/assert&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>todo<span style="color:#bbb"> </span><span style="color:#b44">&#34;github.com/ukautz/go-intro/todo-app/pkg&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">TestUsersAuthentication_Authenticate</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing.T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>auth<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>todo.UsersAuthentication{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>{ID:<span style="color:#bbb"> </span><span style="color:#b44">&#34;u01&#34;</span>,<span style="color:#bbb"> </span>Name:<span style="color:#bbb"> </span><span style="color:#b44">&#34;alice&#34;</span>,<span style="color:#bbb"> </span>Password:<span style="color:#bbb"> </span><span style="color:#b44">&#34;secret1&#34;</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>{ID:<span style="color:#bbb"> </span><span style="color:#b44">&#34;u02&#34;</span>,<span style="color:#bbb"> </span>Name:<span style="color:#bbb"> </span><span style="color:#b44">&#34;bob&#34;</span>,<span style="color:#bbb"> </span>Password:<span style="color:#bbb"> </span><span style="color:#b44">&#34;secret2&#34;</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>expects<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>[]<span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>name<span style="color:#bbb">    </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>request<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>id<span style="color:#bbb">      </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>allowed<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">bool</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>{<span style="color:#b44">&#34;missing basic auth forbidden&#34;</span>,<span style="color:#bbb"> </span><span style="color:#00a000">createBasicAuthTestRequest</span>(<span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>),<span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">false</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>{<span style="color:#b44">&#34;unknown credentials forbidden&#34;</span>,<span style="color:#bbb"> </span><span style="color:#00a000">createBasicAuthTestRequest</span>(<span style="color:#b44">&#34;foo&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;bar&#34;</span>),<span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">false</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>{<span style="color:#b44">&#34;invalid credentials forbidden&#34;</span>,<span style="color:#bbb"> </span><span style="color:#00a000">createBasicAuthTestRequest</span>(<span style="color:#b44">&#34;alice&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;invalid&#34;</span>),<span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">false</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>{<span style="color:#b44">&#34;allow valid user u01&#34;</span>,<span style="color:#bbb"> </span><span style="color:#00a000">createBasicAuthTestRequest</span>(<span style="color:#b44">&#34;alice&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;secret1&#34;</span>),<span style="color:#bbb"> </span><span style="color:#b44">&#34;u01&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">true</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>{<span style="color:#b44">&#34;allow valid user u02&#34;</span>,<span style="color:#bbb"> </span><span style="color:#00a000">createBasicAuthTestRequest</span>(<span style="color:#b44">&#34;bob&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;secret2&#34;</span>),<span style="color:#bbb"> </span><span style="color:#b44">&#34;u02&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">true</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">for</span><span style="color:#bbb"> </span>_,<span style="color:#bbb"> </span>expect<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">range</span><span style="color:#bbb"> </span>expects<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#080">//expect := expect</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>t.<span style="color:#00a000">Run</span>(expect.name,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">func</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing.T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#080">//t.Parallel()</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>userID,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>auth.<span style="color:#00a000">Authenticate</span>(expect.request)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>expect.allowed<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">				</span>assert.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">				</span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span>expect.id,<span style="color:#bbb"> </span>userID)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>}<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">else</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">				</span>assert.<span style="color:#00a000">Error</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>})<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">createBasicAuthTestRequest</span>(user,<span style="color:#bbb"> </span>pass<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>req<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>httptest.<span style="color:#00a000">NewRequest</span>(http.MethodGet,<span style="color:#bbb"> </span><span style="color:#b44">&#34;http://localhost:12345/bla&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>user<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>req.<span style="color:#00a000">SetBasicAuth</span>(user,<span style="color:#bbb"> </span>pass)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>req<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Let&rsquo;s run that test before I explain how it works:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ go <span style="color:#a2f">test</span> -v pkg/authorization_test.go
</span></span><span style="display:flex;"><span>?   	github.com/ukautz/go-intro/todo-app/cmd/server	<span style="color:#666">[</span>no <span style="color:#a2f">test</span> files<span style="color:#666">]</span>
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   <span style="color:#b8860b">TestUsersAuthentication_Authenticate</span>
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestUsersAuthentication_Authenticate/missing_basic_auth_forbidden
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestUsersAuthentication_Authenticate/unknown_credentials_forbidden
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestUsersAuthentication_Authenticate/invalid_credentials_forbidden
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestUsersAuthentication_Authenticate/allow_valid_user_u01
</span></span><span style="display:flex;"><span><span style="color:#666">===</span> RUN   TestUsersAuthentication_Authenticate/allow_valid_user_u02
</span></span><span style="display:flex;"><span>--- PASS: TestUsersAuthentication_Authenticate <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>    --- PASS: TestUsersAuthentication_Authenticate/missing_basic_auth_forbidden <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>    --- PASS: TestUsersAuthentication_Authenticate/unknown_credentials_forbidden <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>    --- PASS: TestUsersAuthentication_Authenticate/invalid_credentials_forbidden <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>    --- PASS: TestUsersAuthentication_Authenticate/allow_valid_user_u01 <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>    --- PASS: TestUsersAuthentication_Authenticate/allow_valid_user_u02 <span style="color:#666">(</span>0.00s<span style="color:#666">)</span>
</span></span><span style="display:flex;"><span>PASS
</span></span><span style="display:flex;"><span>ok  	github.com/ukautz/go-intro/todo-app/pkg	0.002s
</span></span></code></pre></div><p>Excellent, the test passes and the test output is rather expressive, too! Let&rsquo;s go through it then, starting with the <code>createAuthTestRequest</code> helper function:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">createAuthTestRequest</span>(user,<span style="color:#bbb"> </span>pass<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>req<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>httptest.<span style="color:#00a000">NewRequest</span>(http.MethodGet,<span style="color:#bbb"> </span><span style="color:#b44">&#34;http://localhost:12345/bla&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>user<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>req.<span style="color:#00a000">SetBasicAuth</span>(user,<span style="color:#bbb"> </span>pass)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>req<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>As we want to check whether requests with valid credentials are passed through and requests with missing or invalid are not, a helper to create those requests with or without credentials is useful. The URL and the method type are of no consequence, so they are set to dummy values. The username and password in the request are set as basic auth credentials, as we need for the tests.</p>
<p>As you can see I am making use of <a href="https://pkg.go.dev/net/http/httptest"><code>net/http/httptest</code></a>, which provides a lot of helpful tooling around testing HTTP services and functionality. I especially recommend to have a look at the <a href="https://pkg.go.dev/net/http/httptest?tab=doc#Server">test HTTP server</a>, it might come in handy in your future endeavors.</p>
<p>Now, in the <code>TestUsersAuthentication_Authenticate</code> function: First an instance of the <code>todo.UsersAuthentication</code> type with two valid users is created. All the checks will use that instance:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>auth<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>todo.UsersAuthentication{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>{ID:<span style="color:#bbb"> </span><span style="color:#b44">&#34;u01&#34;</span>,<span style="color:#bbb"> </span>Name:<span style="color:#bbb"> </span><span style="color:#b44">&#34;alice&#34;</span>,<span style="color:#bbb"> </span>Password:<span style="color:#bbb"> </span><span style="color:#b44">&#34;secret1&#34;</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>{ID:<span style="color:#bbb"> </span><span style="color:#b44">&#34;u02&#34;</span>,<span style="color:#bbb"> </span>Name:<span style="color:#bbb"> </span><span style="color:#b44">&#34;bob&#34;</span>,<span style="color:#bbb"> </span>Password:<span style="color:#bbb"> </span><span style="color:#b44">&#34;secret2&#34;</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Next, all test expectations are being declared. Since we are going to run &ldquo;sub-tests&rdquo;, each of the expectations has:</p>
<ul>
<li>a <code>name</code> to identify it, should it fail</li>
<li>an <code>*http.Request</code> as input</li>
<li>an expected user <code>id</code> as the output</li>
<li>a flag <code>allowed</code>, to signify whether we expect it to pass or be rejected</li>
</ul>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>expects<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>[]<span style="color:#a2f;font-weight:bold">struct</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>name<span style="color:#bbb">    </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>request<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>id<span style="color:#bbb">      </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>allowed<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">bool</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>{<span style="color:#b44">&#34;missing basic auth forbidden&#34;</span>,<span style="color:#bbb"> </span><span style="color:#00a000">createAuthTestRequest</span>(<span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>),<span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">false</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>{<span style="color:#b44">&#34;unknown credentials forbidden&#34;</span>,<span style="color:#bbb"> </span><span style="color:#00a000">createAuthTestRequest</span>(<span style="color:#b44">&#34;foo&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;bar&#34;</span>),<span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">false</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>{<span style="color:#b44">&#34;invalid credentials forbidden&#34;</span>,<span style="color:#bbb"> </span><span style="color:#00a000">createAuthTestRequest</span>(<span style="color:#b44">&#34;alice&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;invalid&#34;</span>),<span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">false</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>{<span style="color:#b44">&#34;allow valid user u01&#34;</span>,<span style="color:#bbb"> </span><span style="color:#00a000">createAuthTestRequest</span>(<span style="color:#b44">&#34;alice&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;secret1&#34;</span>),<span style="color:#bbb"> </span><span style="color:#b44">&#34;u01&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">true</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>{<span style="color:#b44">&#34;allow valid user u02&#34;</span>,<span style="color:#bbb"> </span><span style="color:#00a000">createAuthTestRequest</span>(<span style="color:#b44">&#34;bob&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;secret2&#34;</span>),<span style="color:#bbb"> </span><span style="color:#b44">&#34;u02&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">true</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Lastly the actual test execution, which iterates the expectations and tests them sequentially by calling the <code>auth.Authenticate</code> method:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">for</span><span style="color:#bbb"> </span>_,<span style="color:#bbb"> </span>expect<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">range</span><span style="color:#bbb"> </span>expects<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>t.<span style="color:#00a000">Run</span>(expect.name,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">func</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing.T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>userID,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>auth.<span style="color:#00a000">Authenticate</span>(expect.request)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>expect.allowed<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>assert.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span>expect.id,<span style="color:#bbb"> </span>userID)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>}<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">else</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>assert.<span style="color:#00a000">Error</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>})<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Taking a deeper look at the body of the encapsulated <code>Run</code> method call:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>userID,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>auth.<span style="color:#00a000">Authenticate</span>(expect.request)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>expect.allowed<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>assert.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span>expect.id,<span style="color:#bbb"> </span>userID)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">else</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>assert.<span style="color:#00a000">Error</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>This first line executes the <code>Authenticate</code> method with the HTTP request from the expectation. Depending on whether we expect it to pass (<code>expect.allowed</code>), we either do not want it to error (<code>assert.NoError</code>) and return the ID (which must metch the expectation) - or make sure that it returns an error.</p>
<h3 id="test-persistence">Test: Persistence</h3>
<p>Now to testing the <code>Persistence</code> implementation: <code>DirectoryPersistence</code>. As we want to test the whole public interface, we need to write tests for all four public methods: <code>Create</code>, <code>Delete</code>, <code>Get</code> and <code>List</code>.</p>
<p>In the interest of brevity I will guide you here only through the tests for <code>Create</code> and <code>Get</code>. To see the full code have a look at <a href="https://github.com/ukautz/go-intro/blob/master/todo-app/pkg/persistence_test.go">https://github.com/ukautz/go-intro/blob/master/todo-app/pkg/persistence_test.go</a></p>
<p>Ok, let&rsquo;s dive in:</p>
<h4 id="test-todo-creation">Test Todo creation</h4>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">TestDirectoryPersistence_Create</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing.T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>p<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#00a000">createTestDirectoryPersistence</span>(t)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>id,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>p.<span style="color:#00a000">Create</span>(todo.Todo{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>Title:<span style="color:#bbb">       </span><span style="color:#b44">&#34;the-title&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>Description:<span style="color:#bbb"> </span><span style="color:#b44">&#34;the-description&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>UserID:<span style="color:#bbb">      </span><span style="color:#b44">&#34;u01&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>})<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>require.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>require.<span style="color:#00a000">NotEmpty</span>(t,<span style="color:#bbb"> </span>id)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>testFile<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>filepath.<span style="color:#00a000">Join</span>(testPersistenceDir,<span style="color:#bbb"> </span>fmt.<span style="color:#00a000">Sprintf</span>(<span style="color:#b44">&#34;%s.json&#34;</span>,<span style="color:#bbb"> </span>id))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">defer</span><span style="color:#bbb"> </span>os.<span style="color:#00a000">Remove</span>(testFile)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>raw,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>ioutil.<span style="color:#00a000">ReadFile</span>(testFile)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>require.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>td<span style="color:#bbb"> </span>todo.Todo<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>require.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>json.<span style="color:#00a000">Unmarshal</span>(raw,<span style="color:#bbb"> </span><span style="color:#666">&amp;</span>td))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span>id,<span style="color:#bbb"> </span>td.ID)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span><span style="color:#b44">&#34;u01&#34;</span>,<span style="color:#bbb"> </span>td.UserID)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span><span style="color:#b44">&#34;the-title&#34;</span>,<span style="color:#bbb"> </span>td.Title)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span><span style="color:#b44">&#34;the-description&#34;</span>,<span style="color:#bbb"> </span>td.Description)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>The first step is to create a new instance of <code>DirectoryPersistence</code>. Since we need to do that in all the tests (for all the public methods), I created the <code>createTestDirectoryPersistence</code> helper function, which makes sure a test (fixture) directory exists and then returns an instance using that test directory (have a look at <a href="https://github.com/ukautz/go-intro/blob/master/todo-app/pkg/persistence_test.go">code for the implementation</a>).</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>p<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#00a000">createTestDirectoryPersistence</span>(t)<span style="color:#bbb">
</span></span></span></code></pre></div><p>Now we need to call the <code>Create</code> method, with a &ldquo;dummy <code>Todo</code>&rdquo;, and make sure the creation worked:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>id,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>p.<span style="color:#00a000">Create</span>(todo.Todo{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Title:<span style="color:#bbb">       </span><span style="color:#b44">&#34;the-title&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Description:<span style="color:#bbb"> </span><span style="color:#b44">&#34;the-description&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>UserID:<span style="color:#bbb">      </span><span style="color:#b44">&#34;u01&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>})<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>require.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>require.<span style="color:#00a000">NotEmpty</span>(t,<span style="color:#bbb"> </span>id)<span style="color:#bbb">
</span></span></span></code></pre></div><p>The two expressions with the <code>require.</code> prefix call functions of a <a href="https://pkg.go.dev/github.com/stretchr/testify/require">(sub) package</a> of the testify library. The only and main difference between the <code>assert.*</code> and the <code>require.*</code> functions is that <code>require.*</code> calls fatal (meaning: end the test with an error immediately), if they fail, while <code>assert.*</code> just print out the error and continue the test.</p>
<p>Since the following test code would not be able to execute / would not make sense, if the create already fails using <code>require.*</code> is opportune.</p>
<p>The following two lines give us the path to the JSON file, which we expect will be created by the <code>DirectoryPersistence</code> implementation, and make sure it&rsquo;s removed <em>after the test execution ends</em>.</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>testFile<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>filepath.<span style="color:#00a000">Join</span>(testPersistenceDir,<span style="color:#bbb"> </span>fmt.<span style="color:#00a000">Sprintf</span>(<span style="color:#b44">&#34;%s.json&#34;</span>,<span style="color:#bbb"> </span>id))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">defer</span><span style="color:#bbb"> </span>os.<span style="color:#00a000">Remove</span>(testFile)<span style="color:#bbb">
</span></span></span></code></pre></div><p>Note especially the <a href="https://tour.golang.org/flowcontrol/12"><code>defer</code> expression</a>, which makes sure <code>os.Remove()</code> on that file is being called <em>after</em> the function ends - <em>however</em> this function ends: Either if it runs to the end (with a success) or ends anywhere in the middle (with a failure), the <code>os.Remove</code> <em>will be executed thereafter</em>. This way, we make sure the state before the test (no exiting JSON file) is guaranteed after the test.</p>
<p>To the next block, in which we&rsquo;re going to read the contents of the file (we assume has been created) and decode (unmarshal) these contents into a new <code>Todo</code> instance:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>raw,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>ioutil.<span style="color:#00a000">ReadFile</span>(testFile)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>require.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>td<span style="color:#bbb"> </span>todo.Todo<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>require.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>json.<span style="color:#00a000">Unmarshal</span>(raw,<span style="color:#bbb"> </span><span style="color:#666">&amp;</span>td))<span style="color:#bbb">
</span></span></span></code></pre></div><p>Again, <code>require.</code> is used instead of <code>assert.</code> as we need not continue with the test code, if anything on the way is already failing.</p>
<p>Finally to the the last assertions, where we check whether the JSON written by the <code>Create</code> method contains all the same, provided data:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span>id,<span style="color:#bbb"> </span>td.ID)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span><span style="color:#b44">&#34;u01&#34;</span>,<span style="color:#bbb"> </span>td.UserID)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span><span style="color:#b44">&#34;the-title&#34;</span>,<span style="color:#bbb"> </span>td.Title)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span><span style="color:#b44">&#34;the-description&#34;</span>,<span style="color:#bbb"> </span>td.Description)<span style="color:#bbb">
</span></span></span></code></pre></div><p>And that&rsquo;s it. Now we can be reasonably sure that <code>Create</code> of the <code>DirectoryPersistence</code>:</p>
<ul>
<li>Writes a JSON file in the directory we expect</li>
<li>Encodes in that JSON file the Todo with the data we provided</li>
</ul>
<h4 id="test-todo-reading">Test Todo reading</h4>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">TestDirectoryPersistence_Get</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing.T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">defer</span><span style="color:#bbb"> </span>os.<span style="color:#00a000">Remove</span>(<span style="color:#00a000">assertJSONTodoFile</span>(t,<span style="color:#bbb"> </span><span style="color:#666">2</span>))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>p<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#00a000">createTestDirectoryPersistence</span>(t)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>td,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>p.<span style="color:#00a000">Get</span>(<span style="color:#b44">&#34;todo-02&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>require.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span>todo.Todo{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>ID:<span style="color:#bbb">          </span><span style="color:#b44">&#34;todo-02&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>Title:<span style="color:#bbb">       </span><span style="color:#b44">&#34;todo 02&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>Description:<span style="color:#bbb"> </span><span style="color:#b44">&#34;the todo number 02&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>UserID:<span style="color:#bbb">      </span><span style="color:#b44">&#34;u02&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>Created:<span style="color:#bbb">     </span>time.<span style="color:#00a000">Date</span>(<span style="color:#666">2010</span>,<span style="color:#bbb"> </span><span style="color:#666">11</span>,<span style="color:#bbb"> </span><span style="color:#666">12</span>,<span style="color:#bbb"> </span><span style="color:#666">13</span>,<span style="color:#bbb"> </span><span style="color:#666">14</span>,<span style="color:#bbb"> </span><span style="color:#666">15</span>,<span style="color:#bbb"> </span><span style="color:#666">0</span>,<span style="color:#bbb"> </span>time.UTC),<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>},<span style="color:#bbb"> </span><span style="color:#666">*</span>td)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>This is way shorter than the previous test, but contains a condensed statements at the start, which needs explanation:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">defer</span><span style="color:#bbb"> </span>os.<span style="color:#00a000">Remove</span>(<span style="color:#00a000">assertJSONTodoFile</span>(t,<span style="color:#bbb"> </span><span style="color:#666">2</span>))<span style="color:#bbb">
</span></span></span></code></pre></div><p>First, quickly about the custom <code>assertJSONTodoFile</code> helper function: This creates a JSON file in the test directory containing an encoded Todo, so it can be assumed in the tests. The path to that file is then returned. In this case, the <code>2</code> indicates to create the test file <code>test-02.json</code>. See the <a href="https://github.com/ukautz/go-intro/blob/master/todo-app/pkg/persistence_test.go">source code</a> for more details.</p>
<p>Now here is what the whole <code>defer</code>-expression does:</p>
<ul>
<li>create the <code>test-02.json</code> file in the test folder</li>
<li>remove the <code>test-02.json</code> from the test folder <em>after the test ends</em></li>
</ul>
<p>This might be a bit confusing, but since it is a common trick in Go it is worth to take the time to understand it properly.</p>
<p>To make it plain, consider the following small program (which you can run <a href="https://play.golang.org/p/U0SB9D8LWag">here in the playground</a>) first to show how <code>defer</code> itself works:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>main<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;fmt&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">main</span>()<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">defer</span><span style="color:#bbb"> </span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#b44">&#34;deferred hello&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#b44">&#34;hello&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>If you execute the above, you will see the following:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>hello
</span></span><span style="display:flex;"><span>deferred hello
</span></span></code></pre></div><p>I hope this makes it clear that <code>defer</code> executes the statement when the code block, it is in (in this case: the <code>main</code> function), ends.</p>
<p>Now, let&rsquo;s extend that example (also <a href="https://play.golang.org/p/5W-RdH-L0Rf">in the playground</a>):</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>main<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;fmt&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">greet</span>()<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#b44">&#34;returning greetings&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;greetings&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">main</span>()<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">defer</span><span style="color:#bbb"> </span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#00a000">greet</span>())<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#b44">&#34;hello&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>This will print out:</p>
<pre tabindex="0"><code>returning greetings
hello
greetings
</code></pre><p>Here is how the execution works:</p>
<ul>
<li><code>defer fmt.Println(greet())</code> executes <code>greet()</code> immediately, as <code>greet()</code> is just an argument to the wrapping <code>fmt.Println()</code> call - which is deferred. This immediately prints out <code>returning greetings</code> - and returns the string <code>greetings</code></li>
<li>the <code>fmt.Println(&quot;hello&quot;)</code> printing <code>hello</code> is executed</li>
<li>the function ends, and the deferred <code>fmt.Println(&quot;greetings&quot;)</code> is executed, printing <code>greetings</code></li>
</ul>
<p>This &ldquo;trick&rdquo; can be often found, especially in the context of (cleanup in) testing.</p>
<p>Now to the rest of test body:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>p<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#00a000">createTestDirectoryPersistence</span>(t)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>td,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>p.<span style="color:#00a000">Get</span>(<span style="color:#b44">&#34;todo-02&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>require.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span>todo.Todo{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>ID:<span style="color:#bbb">          </span><span style="color:#b44">&#34;todo-02&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Title:<span style="color:#bbb">       </span><span style="color:#b44">&#34;todo 02&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Description:<span style="color:#bbb"> </span><span style="color:#b44">&#34;the todo number 02&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>UserID:<span style="color:#bbb">      </span><span style="color:#b44">&#34;u02&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Created:<span style="color:#bbb">     </span>time.<span style="color:#00a000">Date</span>(<span style="color:#666">2010</span>,<span style="color:#bbb"> </span><span style="color:#666">11</span>,<span style="color:#bbb"> </span><span style="color:#666">12</span>,<span style="color:#bbb"> </span><span style="color:#666">13</span>,<span style="color:#bbb"> </span><span style="color:#666">14</span>,<span style="color:#bbb"> </span><span style="color:#666">15</span>,<span style="color:#bbb"> </span><span style="color:#666">0</span>,<span style="color:#bbb"> </span>time.UTC),<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>},<span style="color:#bbb"> </span><span style="color:#666">*</span>td)<span style="color:#bbb">
</span></span></span></code></pre></div><p>As before, we create a new instance using <code>createTestDirectoryPersistence</code> and then call the <code>Get</code> method using the ID <code>todo-02</code>. A JSON file, representing that Todo, was created earlier with the <code>assertJSONTodoFile(t, 2)</code> call.</p>
<p>Again, using <code>require</code> to make sure the test ends if any error was returned from <code>Get</code> and lastly a comparison of the returned <code>*Todo</code> with our expectations.</p>
<p>That&rsquo;s it. Have a <a href="https://github.com/ukautz/go-intro/blob/master/todo-app/pkg/persistence_test.go">look into the other tests</a>, which will use similar patterns to the ones explained here.</p>
<h3 id="test-router">Test: Router</h3>
<p>At last, we need to test our HTTP router. To that end, we need to test whether</p>
<ul>
<li>HTTP POST to <code>/todo</code> with the appropriate JSON body creates a Todo in <code>Persistence</code></li>
<li>HTTP GET to <code>/todo</code> lists all Todos from <code>Persistence</code></li>
<li>HTTP DELETE <code>/todo/&lt;todo-id&gt;</code> removes a specific Todo from <code>Persistence</code></li>
<li>HTTP GET <code>/todo/&lt;todo-id&gt;</code> fetches a specific Todo from <code>Persistence</code></li>
</ul>
<h4 id="test-fakes--stubs--mocks">Test Fakes / Stubs / Mocks</h4>
<p>As we are writing unit(&lsquo;ish) tests, we are constraint to test the code in isolation. Since the <code>Router</code> requires both <code>Persistence</code> and <code>Authentication</code>, we need something to fulfill that need.</p>
<p>Luckily, we defined <code>Persistence</code> and <code>Authentication</code> as interfaces, which allows us now to use &ldquo;test doubles&rdquo;, which implement those interfaces, but are not the &ldquo;actual implementations&rdquo; (from above) and thereby not violate our isolation constraint (much).</p>
<p>If you are familiar with software testing patterns in other languages you might have heard of mocking or stubbing or test dummies or test fakes. There are a few definitions about in the interwebs. I decided to go with the one from <a href="https://www.martinfowler.com/articles/mocksArentStubs.html#TheDifferenceBetweenMocksAndStubs">Martin Fowler, specifcially what he calls a (test) <strong>Fake</strong></a>.</p>
<p><em>Note: If you wish to use mocks in Go, consider the <a href="https://pkg.go.dev/github.com/stretchr/testify/mock"><code>mock</code> package from the testify library</a>.</em></p>
<p>Let me show you a quick example. For that we first need an interface for which we then write a test fake. Consider the following interface:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>Filesystem<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">interface</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// Write stores a file under the given path with the given content</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#00a000">Write</span>(path<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>,<span style="color:#bbb"> </span>data<span style="color:#bbb"> </span>[]<span style="color:#0b0;font-weight:bold">byte</span>)<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// Delete removes a file from the file system with the given path</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#00a000">Delete</span>(path<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Assume we have an actual implementation (which would actually remove or write a file on the file system), here is how a fake implementing that interface could look like:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>FakeFilesystem<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">map</span>[<span style="color:#0b0;font-weight:bold">string</span>][]<span style="color:#0b0;font-weight:bold">byte</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(f<span style="color:#bbb"> </span>FakeFilesystem)<span style="color:#bbb"> </span><span style="color:#00a000">Write</span>(path<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>,<span style="color:#bbb"> </span>data<span style="color:#bbb"> </span>[]<span style="color:#0b0;font-weight:bold">byte</span>)<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>f[path]<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span>data<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(f<span style="color:#bbb"> </span>FakeFilesystem)<span style="color:#bbb"> </span><span style="color:#00a000">Delete</span>(path<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f">delete</span>(f,<span style="color:#bbb"> </span>path)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>As you can see, the <code>FakeFilesystem</code> simulates an actual file system. Further: <em>it contains state</em>, by storing the written &ldquo;files&rdquo; in a <code>map</code> - and by having the deleted &ldquo;files&rdquo; removed from that map. Why is that helpful? Easy: In a test, which uses that fake, where you want to test if a file was created, you can just check the <code>map</code> after the test run, whether it now contains a key with that file path and whether it contains the (expectedly) written contents.</p>
<p>Going back to our <code>Router</code> testing, let me show you the <code>Authentication</code> fake implementation, as you can find in <a href="https://github.com/ukautz/go-intro/blob/master/todo-app/pkg/router_test.go">pkg/router_test.go</a>:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">type</span><span style="color:#bbb"> </span>testAuthentication<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">map</span>[<span style="color:#0b0;font-weight:bold">string</span>]<span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span>(a<span style="color:#bbb"> </span>testAuthentication)<span style="color:#bbb"> </span><span style="color:#00a000">Authenticate</span>(req<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request)<span style="color:#bbb"> </span>(userID<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>user,<span style="color:#bbb"> </span>pass,<span style="color:#bbb"> </span>hasBasic<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>req.<span style="color:#00a000">BasicAuth</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>!hasBasic<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span>errors.<span style="color:#00a000">New</span>(<span style="color:#b44">&#34;no basic&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>known,<span style="color:#bbb"> </span>has<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>a[user];<span style="color:#bbb"> </span>has<span style="color:#bbb"> </span><span style="color:#666">&amp;&amp;</span><span style="color:#bbb"> </span>pass<span style="color:#bbb"> </span><span style="color:#666">==</span><span style="color:#bbb"> </span>known<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>user,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span><span style="color:#b44">&#34;&#34;</span>,<span style="color:#bbb"> </span>errors.<span style="color:#00a000">New</span>(<span style="color:#b44">&#34;not allowed&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>This is a pretty common &ldquo;in-memory&rdquo; pattern, using a <code>map</code> as the underlying &ldquo;storage&rdquo;.</p>
<p>The fake for <code>Persistence</code> is a bit more extensive, since it needs to implement four public methods. Please have a look in <a href="https://github.com/ukautz/go-intro/blob/master/todo-app/pkg/router_test.go">pkg/router_test.go</a>, the type is called <code>testPersistence</code>.</p>
<h4 id="http-testing">HTTP testing</h4>
<p>Now with both Fakes in place, we can write the actual tests. I won&rsquo;t be going through all the tests of our REST API here, but let me walk you through the interesting bits, starting with a test constructor to create a <code>todo.Router</code> instance, which uses the above test Fakes and fills them with useful contents for the test:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">testNewRouter</span>()<span style="color:#bbb"> </span>todo.Router<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>todo.Router{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>Authentication:<span style="color:#bbb"> </span>testAuthentication{<span style="color:#b44">&#34;the-user&#34;</span>:<span style="color:#bbb"> </span><span style="color:#b44">&#34;the-pass&#34;</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>Persistence:<span style="color:#bbb"> </span>testPersistence{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#b44">&#34;todo-01&#34;</span>:<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">				</span>ID:<span style="color:#bbb">    </span><span style="color:#b44">&#34;todo-01&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">				</span>Title:<span style="color:#bbb"> </span><span style="color:#b44">&#34;todo 01&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span><span style="color:#b44">&#34;todo-02&#34;</span>:<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">				</span>ID:<span style="color:#bbb">    </span><span style="color:#b44">&#34;todo-02&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">				</span>Title:<span style="color:#bbb"> </span><span style="color:#b44">&#34;todo 02&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">			</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>},<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><h4 id="test-http-request-authentication">Test HTTP request authentication</h4>
<p>With that in mind, consider the following test to make sure the <code>Router</code> is using the <code>Authentication</code> to reject requests with invalid credentials:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">TestRouter_ServeHTTP_RejectInvalidCredentials</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing.T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>req<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>httptest.<span style="color:#00a000">NewRequest</span>(http.MethodGet,<span style="color:#bbb"> </span><span style="color:#b44">&#34;/todo&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>req.<span style="color:#00a000">SetBasicAuth</span>(<span style="color:#b44">&#34;invalid&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;invalid&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>router<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#00a000">testNewRouter</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>rec<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>httptest.<span style="color:#00a000">NewRecorder</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>router.<span style="color:#00a000">ServeHTTP</span>(rec,<span style="color:#bbb"> </span>req)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>res<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>rec.<span style="color:#00a000">Result</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>require.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span>http.StatusForbidden,<span style="color:#bbb"> </span>res.StatusCode)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>The first two lines create a new HTTP request and set invalid HTTP basic auth credentials:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>req<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>httptest.<span style="color:#00a000">NewRequest</span>(http.MethodGet,<span style="color:#bbb"> </span><span style="color:#b44">&#34;/todo&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>req.<span style="color:#00a000">SetBasicAuth</span>(<span style="color:#b44">&#34;invalid&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;invalid&#34;</span>)<span style="color:#bbb">
</span></span></span></code></pre></div><p>In the next block you see a typical HTTP testing pattern:</p>
<ul>
<li>Create a new instance of our HTTP <code>Router</code></li>
<li>Create a new <code>httptest.Recorder</code>, which implements the <code>http.ResponseWriter</code> interface</li>
<li>Run the <code>ServeHTTP</code> method of the <code>Router</code> with the test HTTP request and the test HTTP response (writer)</li>
</ul>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>router<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#00a000">testNewRouter</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>rec<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>httptest.<span style="color:#00a000">NewRecorder</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>router.<span style="color:#00a000">ServeHTTP</span>(rec,<span style="color:#bbb"> </span>req)<span style="color:#bbb">
</span></span></span></code></pre></div><p>Now all we need to do is check the HTTP response status that simulated HTTP request handling returned:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>res<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>rec.<span style="color:#00a000">Result</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>require.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span>http.StatusForbidden,<span style="color:#bbb"> </span>res.StatusCode)<span style="color:#bbb">
</span></span></span></code></pre></div><p>And done. We expect to see a <code>403 Forbidden</code> response status code and the test will fail if that is not the case.</p>
<h4 id="test-fetching-a-single-todo">Test fetching a single Todo</h4>
<p>Now towards testing the actual API. Keep in mind the above <code>Persistence</code> fake, which contains two items in the &ldquo;database&rdquo;. In the following test, we are checking whether the <code>Router</code> returns the expected Todo for <code>GET</code> requests to the path <code>/todo/todo-01</code>:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">TestRouter_ServeHTTP_Get</span>(t<span style="color:#bbb"> </span><span style="color:#666">*</span>testing.T)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>req<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>httptest.<span style="color:#00a000">NewRequest</span>(http.MethodGet,<span style="color:#bbb"> </span><span style="color:#b44">&#34;/todo/todo-01&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>req.<span style="color:#00a000">SetBasicAuth</span>(<span style="color:#b44">&#34;the-user&#34;</span>,<span style="color:#bbb"> </span><span style="color:#b44">&#34;the-pass&#34;</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>router<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#00a000">testNewRouter</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>rec<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>httptest.<span style="color:#00a000">NewRecorder</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>router.<span style="color:#00a000">ServeHTTP</span>(rec,<span style="color:#bbb"> </span>req)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>res<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>rec.<span style="color:#00a000">Result</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>require.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span>http.StatusOK,<span style="color:#bbb"> </span>res.StatusCode)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>ret,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>ioutil.<span style="color:#00a000">ReadAll</span>(res.Body)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>require.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>out<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>todo.Todo{}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>require.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>json.<span style="color:#00a000">Unmarshal</span>(ret,<span style="color:#bbb"> </span><span style="color:#666">&amp;</span>out))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span>todo.Todo{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>ID:<span style="color:#bbb">    </span><span style="color:#b44">&#34;todo-01&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span>Title:<span style="color:#bbb"> </span><span style="color:#b44">&#34;todo 01&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>},<span style="color:#bbb"> </span>out)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>The test starts similar to the previous one, where we checked whether invalid credentials are rejected. Of course we&rsquo;re now using the &ldquo;correct&rdquo; credentials and querying a differnt path (<code>/todo/todo-01</code>) and expected an <code>200 OK</code> response. Assuming that we get it (and <code>require.Equal</code> makes sure the test aborts if we don&rsquo;t), the test then reads the returned HTTP response body, decodes it from JSON into a <code>todo.Todo</code> instance (which will fail if it&rsquo;s not, not valid or not compatible JSON). Finally, we also compare the decode <code>todo.Todo</code> instance with what we put into the fake <code>Persistence</code> above:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>ret,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>ioutil.<span style="color:#00a000">ReadAll</span>(res.Body)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>require.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>out<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>todo.Todo{}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>require.<span style="color:#00a000">NoError</span>(t,<span style="color:#bbb"> </span>json.<span style="color:#00a000">Unmarshal</span>(ret,<span style="color:#bbb"> </span><span style="color:#666">&amp;</span>out))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>assert.<span style="color:#00a000">Equal</span>(t,<span style="color:#bbb"> </span>todo.Todo{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>ID:<span style="color:#bbb">    </span><span style="color:#b44">&#34;todo-01&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>Title:<span style="color:#bbb"> </span><span style="color:#b44">&#34;todo 01&#34;</span>,<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>},<span style="color:#bbb"> </span>out)<span style="color:#bbb">
</span></span></span></code></pre></div><p>If that test does not fail, we can be reasonable sure that:</p>
<ul>
<li>given valid basic auth credentials</li>
<li>given for an existing Todo ID, there is a JSON file in the right path</li>
<li>a GET request returns the respective Todo from the persistence</li>
</ul>
<p>And that&rsquo;s it. Again, please take a look into the rest of the <a href="https://github.com/ukautz/go-intro/blob/master/todo-app/pkg/router_test.go">test source code</a> to find the tests for the other HTTP endpoints.</p>
<p>Please also keep in mind that this is foremost an example and you could be easily optimized. I leave that to the reader as an exercise, if so desired.</p>
<h2 id="finish">Finish</h2>
<p>Phew. That was quite a lot. Thanks for reading! I hope you learned something and had a bit of fun on the way. I might continue this series in the future, going deeper into detail topics.</p>
]]></content:encoded></item><item><title>Practical introduction to Go: Language basics (2/3)</title><link>https://ulrichkautz.com/posts/2020-06-10_practical-go-2-of-3/</link><pubDate>Wed, 10 Jun 2020 21:00:00 +0200</pubDate><guid>https://ulrichkautz.com/posts/2020-06-10_practical-go-2-of-3/</guid><description>Understand the Go language basics. Get familiar with the Go ecosystem and standard library. Run and compile your first Go program.</description><content:encoded><![CDATA[<p>This introduction to Go is geared towards anyone, with</p>
<ul>
<li>some development background (what are variables, what are loops, conditions, functions, etc &hellip;)</li>
<li>a running Go development environment (<code>go</code> command line tooling + an IDE of your choice)</li>
<li>an interest in learning Go</li>
</ul>
<p>If you don&rsquo;t have a running Go development environment yet, please <a href="https://ulrichkautz.com/posts/2020-06-05_practical-go-1-of-3/">check out the previous article of this series</a>.</p>
<p>Outcome of of this article will be:</p>
<ul>
<li>Understanding of the Go language basics</li>
<li>Ability to read &amp; write simple Go code</li>
<li>Some experience with Go CLI (run, compile)</li>
<li>Some experience with Go standard lib</li>
<li>Know about (official) Go documentation and other useful sources</li>
</ul>
<p>This part will prepare you for the next part in the series: <a href="https://ulrichkautz.com/posts/2020-07-03_practical-go-3-of-3/">Intro to application development in Go</a>.</p>
<h2 id="a-hello-world-http-server">A hello-world HTTP server</h2>
<p>As this is a show-and-tell introduction let&rsquo;s first have a look at the code of a small, working Go program. I will guide you through the lines so that you can become familiar with the essentials on the way.</p>
<p>Without further ado here is a minimal HTTP server:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#080;font-style:italic">// returns a `200 OK` response with the body `Hello World` to any incoming request</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>main<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span>(<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;fmt&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;net/http&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span><span style="color:#bbb"> </span>address<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#b44">&#34;127.0.0.1:12345&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>counter<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#666">0</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">main</span>()<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#b44">&#34;Starting HTTP server at&#34;</span>,<span style="color:#bbb"> </span>address)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>http.<span style="color:#00a000">HandleFunc</span>(<span style="color:#b44">&#34;/&#34;</span>,<span style="color:#bbb"> </span>helloWorld)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>http.<span style="color:#00a000">ListenAndServe</span>(address,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f">panic</span>(err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">helloWorld</span>(writer<span style="color:#bbb"> </span>http.ResponseWriter,<span style="color:#bbb"> </span>request<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>counter<span style="color:#666">++</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>response<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>fmt.<span style="color:#00a000">Sprintf</span>(<span style="color:#b44">&#34;Hello World (%d)&#34;</span>,<span style="color:#bbb"> </span>counter)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>writer.<span style="color:#00a000">Write</span>([]<span style="color:#a2f">byte</span>(response))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>You can find all the Go code also in <a href="http://github.com/ukautz/go-intro">http://github.com/ukautz/go-intro</a></p>
<h2 id="run-go-code">Run Go code</h2>
<p>Copy the above code and store it in a filed named <code>main.go</code> (wherever you prefer on your file system). Then open up a terminal, navigate to the directory the file is stored in, then execute:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ go run main.go
</span></span><span style="display:flex;"><span>Starting HTTP server at http://127.0.0.1:12345
</span></span></code></pre></div><p>Once that happened, you can visit the URL <code>http://127.0.0.1:12345</code> either in your browser or with <code>curl</code> (from another terminal). In any case, you should see: <code>Hello World (1)</code> with increasing numbers in parenthesis with each request.</p>
<p>Congratulations! You ran your first Go HTTP server &#x1f601; &#x1f389;</p>
<p><strong>Hint</strong>: You can stop your HTTP server from the terminal by hitting <code>ctrl + c</code>.</p>
<h3 id="compile-into-binary">Compile into binary</h3>
<p>While we are at it, let me show you how to compile your HTTP server into a binary file, so that it can be deployed to other systems (which do not have the <code>go</code> compiler installed) and executed there.</p>
<p>The difference is minimal. Instead of <code>go run</code> you execute <code>go build</code>, like:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ go build main.go
</span></span></code></pre></div><p>This will create a binary, executable file named <code>main</code> in the same directory, which you can then execute as any other executable file:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ ./main
</span></span><span style="display:flex;"><span>Starting HTTP server
</span></span></code></pre></div><p><strong>Hint</strong>: The file name <code>main</code> is automatically derived from <code>main.go</code>. You can specify an alternative with the <code>-o &lt;name&gt;</code> parameter, as in: <code>go build -o http-server main.go</code></p>
<h2 id="understanding-the-code">Understanding the code</h2>
<p>Now that you saw it working, let us go through the code block by block:</p>
<h3 id="writing-code-comments">Writing code comments</h3>
<p>Let&rsquo;s start out easy, albeit with a very important feature of any language: The code comment. The first line in the example program reads as following:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#080;font-style:italic">// returns a `200 OK` response with the body `Hello World` to any incoming request</span><span style="color:#bbb">
</span></span></span></code></pre></div><p>This is a comment in Go. For multiline comments you can also use the <code>/**/</code> as in:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#080;font-style:italic">/*
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">This is a
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">multiline
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">comment
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">*/</span><span style="color:#bbb">
</span></span></span></code></pre></div><h3 id="declaring-the-package">Declaring the package</h3>
<p>Continuing with the next line:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">package</span><span style="color:#bbb"> </span>main<span style="color:#bbb">
</span></span></span></code></pre></div><p>Go orders code into packages. The first line of code in every <code>.go</code> file is always the <code>package &lt;package-name&gt;</code> declaration  (aside from comments or whitespace).</p>
<p>The package name <a href="https://golang.org/doc/effective_go.html#package-names">should be concise and is by convention a lower case, single-word name, without underscores or mixedCaps</a>. Basically: keep it short &amp; simple.</p>
<p>The package name <code>main</code> which is used here is <em>special</em>: In Go all execution starts in the <code>main</code> package. Since we are writing a simple, executable HTTP server, all the code can live in a single file: the <code>main.go</code>. With larger projects, you would structure your code into multiple files, which would live in multiple directories and thereby multiple packages.</p>
<p><strong>Note</strong>: Every <code>.go</code> file within the same directory <em>must be in the same package</em>. If you have multiple <code>.go</code> files in a directory and not all have the same <code>package &lt;name&gt;</code>, then Go will refuse to compile! Also: Usually, the package name matches the name of the directory the file is in. However, this is a convention and can be broken when necessary (more on that in the next article of this series).</p>
<h4 id="importing-other-packages">Importing other packages</h4>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">import</span><span style="color:#bbb"> </span>(<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;fmt&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#b44">&#34;net/http&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>)<span style="color:#bbb">
</span></span></span></code></pre></div><p>As mentioned before Go structures code into packages. To use any code from another package you first need to explicitly import the package. The above code block imports the two packages <code>fmt</code> and <code>net/http</code> - from the Go standard library to be precise. The standard library is part of the Go SDK and comes with Go itself - no need to install it separately.</p>
<p><strong>Note</strong>: Packages from the standard library have very short import names. You will also use 3rd party libraries (=modules), which are often hosted on public repositories, and which have a longer name of the form <code>&lt;public-location&gt;/&lt;repository&gt;</code>, as in <code>github.com/aws/aws-sdk-go</code> - more on that later.</p>
<h4 id="package-documentation">Package documentation</h4>
<p>You can investigate all publicly available Go packages using the <code>https://pkg.go.dev</code> website (formerly known as <code>https://godoc.org</code>). Just visit: <code>https://pkg.go.dev/&lt;package-path&gt;</code> to display the documentation of the exported interface of the package.</p>
<p>In practical terms, here is the documentation for the two packages we imported above:</p>
<ul>
<li><a href="https://pkg.go.dev/fmt">https://pkg.go.dev/fmt</a></li>
<li><a href="https://pkg.go.dev/net/http">https://pkg.go.dev/net/http</a></li>
</ul>
<p><strong>Note</strong>: as this documentation is auto-generated from comments in the source code, this also works with 3rd party packages, like the aforementioned AWS SDK: <a href="https://pkg.go.dev/github.com/aws/aws-sdk-go">https://pkg.go.dev/github.com/aws/aws-sdk-go</a>. Of course it would <em>not</em> work with privately hosted (access restricted) packages.</p>
<h3 id="constants--variables">Constants &amp; Variables</h3>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span><span style="color:#bbb"> </span>address<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#b44">&#34;127.0.0.1:12345&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>counter<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#666">0</span><span style="color:#bbb">
</span></span></span></code></pre></div><p>Most higher level languages differentiate between constants and variables. So does Go. In the above code snippet you see first the declaration of a <code>string</code>-type constant named <code>address</code> then the declaration of the <code>int</code>-type variable named <code>counter</code>.</p>
<p>As the name implies a constant is unchangeable (immutable) after declaration, whereas a variable can be modified (mutated) at leisure. To make that clear:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#080;font-style:italic">// declare a variable with an initial value</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>iAmChangeable<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#b44">&#34;foo&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// change the value of the variable -&gt; no problem</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>iAmChangable<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#b44">&#34;bar&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// declare constant with value</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span><span style="color:#bbb"> </span>iAmUnchangable<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#b44">&#34;foo&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// try to change constant after declaration -&gt; failure at compile time</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>iAmUnchangable<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#b44">&#34;bar&#34;</span><span style="color:#bbb">
</span></span></span></code></pre></div><p>However, while you can change the <em>content</em> of a variable after declaration, you <em>cannot change the type!</em> Which means the following will fail:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#080;font-style:italic">// declare a string variable with initial value</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>iAmChangeable<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#b44">&#34;foo&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#080;font-style:italic">// attempt to assign an int value to variable after declaration -&gt; failure at compile time</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>iAmChangeable<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#666">123</span><span style="color:#bbb">
</span></span></span></code></pre></div><p>Same as with the <code>import</code> code from above, Go knows two notations. The following is equivalent and makes sense when more than one constant (or variable) needs to be declared:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span><span style="color:#bbb"> </span>(<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>address<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#b44">&#34;127.0.0.1:12345&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>(<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>counter<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#666">0</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>)<span style="color:#bbb">
</span></span></span></code></pre></div><h3 id="about-types">About types</h3>
<p>Go is a <em>strong typed language</em>. This means: every constant or variable is of a specific, unchangeable type.</p>
<p>The type of a variable or constant can be provided implicitly (as above) or explicitly. The above could be written <em>explicitly</em> like so:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">const</span><span style="color:#bbb"> </span>address<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span><span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#b44">&#34;127.0.0.1:12345&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>(<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>counter<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">int</span><span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#666">5</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>)<span style="color:#bbb">
</span></span></span></code></pre></div><p>As Go is perfectly able to figure out the types in the above example, I omitted them. However, this works for a small set of types, namely: <code>string</code>, <code>int</code>, <code>float64</code> and <code>bool</code>. Here an example of types Go can &ldquo;auto detect&rdquo;:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>aString<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#b44">&#34;123&#34;</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>anInt<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#666">123</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>aFloat<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#666">123.456</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">var</span><span style="color:#bbb"> </span>aBool<span style="color:#bbb"> </span>=<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">true</span><span style="color:#bbb">
</span></span></span></code></pre></div><p>There are, roughly speaking, two &ldquo;kinds of types&rdquo;:</p>
<p><strong>built-in (primitive) types</strong></p>
<ul>
<li>like <code>int</code>, <code>uint</code>, <code>int64</code>, <code>float64</code>, <code>string</code>, <code>byte</code>, <code>bool</code> etc as you might now from other languages</li>
<li>they are written in <code>lowercase</code></li>
<li>in depth: <a href="https://go101.org/article/basic-types-and-value-literals.html">go101.org - Basic Types and Basic Value Literals</a></li>
</ul>
<p><strong>user defined (complex) types</strong></p>
<ul>
<li>they are specified in plain Go in the standard library, 3rd party or your code</li>
<li>they look like <code>package.CamelCase</code></li>
<li>the next post in this series will elaborate in depth on them</li>
</ul>
<h3 id="function-declarations">Function declarations</h3>
<p>Going back to the above <code>main.go</code> file, let&rsquo;s have a look at the <code>main</code> function therein:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">main</span>()<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#b44">&#34;Starting HTTP server at&#34;</span>,<span style="color:#bbb"> </span>address)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>http.<span style="color:#00a000">HandleFunc</span>(<span style="color:#b44">&#34;/&#34;</span>,<span style="color:#bbb"> </span>helloWorld)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>http.<span style="color:#00a000">ListenAndServe</span>(<span style="color:#b44">&#34;:12345&#34;</span>,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span>)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f">panic</span>(err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Ok, this is a bigger piece of code, let&rsquo;s go through it slowly:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">main</span>()<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// ..</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>This is a minimal declaration of a parameter-less function which does not return anything.</p>
<p>The general pattern for functions in Go looks as following:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">nameOfTheFunction</span>(param1<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">int</span>,<span style="color:#bbb"> </span>param2<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">string</span>)<span style="color:#bbb"> </span>(<span style="color:#0b0;font-weight:bold">string</span>,<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span>)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// body</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>To put that in words:</p>
<ul>
<li>starting with the keyword <code>func</code></li>
<li>followed by the <code>nameOfTheFunction</code></li>
<li>followed parenthesis <code>()</code> which may contain a list of typed input parameters
<ul>
<li>here: <code>(param1 int, param2 string)</code>, meaning that the function call expects two parameters, the first of the type <code>int</code> and the second of the type <code>string</code></li>
</ul>
</li>
<li>optionally followed by typed return parameters (within parenthesis <code>()</code> - if there is more than one)
<ul>
<li>here <code>(string, error)</code>, meaning that the function call will return two variables, the first of the type <code>string</code> and the second of the type <code>error</code></li>
</ul>
</li>
<li>followed by the body (code) within the curly brackets <code>{}</code></li>
</ul>
<h4 id="the-main-function-is-special">The main function is special</h4>
<p>The <code>main</code> function, with an empty signature, within the <code>package main</code> is a special case. It indicates to Go that this function is an <em>entry-point for execution</em>. Basically what is being called when running <code>go run</code> from the shell (or executing the compiled binary).</p>
<p>Having a <code>main</code> function in any other (named) package has no consequence at all. Only in the <code>main</code> package it becomes a special case.</p>
<h3 id="using-packages">Using packages</h3>
<p>Let us investigate the the first line of the body of our <code>main</code> function in detail:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>fmt.<span style="color:#00a000">Println</span>(<span style="color:#b44">&#34;Starting HTTP server at&#34;</span>,<span style="color:#bbb"> </span>address)<span style="color:#bbb">
</span></span></span></code></pre></div><p>You can probably guess what this line is doing: It prints out <code>Starting HTTP server at 127.0.0.1:12345</code> (on <code>STDOUT</code>, to be precise). The prefix <code>fmt.</code> refers to the previously imported <code>fmt</code> package. <code>Println</code> is a public (exported) function from this <code>fmt</code> package.</p>
<h4 id="access-modifiers-public--private">Access modifiers (public / private)</h4>
<p>You might have noted a difference in spelling of our functions (<code>main</code> and <code>helloWorld</code>) and that <code>Println</code> function from the <code>fmt</code> package. The uppercase <code>P</code> is intentionally, as this is how you specify in Go the accessibility (visibility) of, well, anything. In this case a function, but this goes for types, constants, variables etc.</p>
<p>To be clear, the difference is:</p>
<ul>
<li><em>private things</em> can only be accessed (e.g. called) by other code within the same packages (i.e. from files in the same directory)</li>
<li><em>public things</em> can be accessed by any code that imports the package it lives in</li>
</ul>
<p>Or even shorter: <em>Only Uppercase is part of the public interface of a package.</em></p>
<h3 id="setup-http-routing">Setup HTTP routing</h3>
<p>Coming back to the next line of code in the <code>main</code> function:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>http.<span style="color:#00a000">HandleFunc</span>(<span style="color:#b44">&#34;/&#34;</span>,<span style="color:#bbb"> </span>helloWorld)<span style="color:#bbb">
</span></span></span></code></pre></div><p>Go comes with a very powerful HTTP server (and client) out of the box. It is highly configurable and allows you to run anything from a simple hello world to a high-load, high-concurrency, next-facebook-like application.</p>
<p>Luckily, most of the complexity that this entails is hidden until you need it. There are two things you have to do to run a simple web server in Go:</p>
<ol>
<li>Tell Go what do with incoming requests (aka <em>routing</em>)</li>
<li>Tell Go on what address to start the HTTP server on</li>
</ol>
<p>The <code>HandleFunc</code> function from the <code>http</code> package handles the first part: <em>configures the routing of the HTTP server</em>.</p>
<p>For that it requires:</p>
<ul>
<li><em>a path prefix</em>: the chosen <code>/</code> is the root of all paths and thereby accepts any (requested) path</li>
<li><em>a handler function</em>: <code>helloWorld</code> is our handler, we&rsquo;ll get to it soon</li>
</ul>
<p><em>Note: Functions can be passed as arguments the the same way as variables or constants can.</em></p>
<h3 id="start-the-http-server">Start the HTTP server</h3>
<p>Next up in the <code>main</code> function:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>http.<span style="color:#00a000">ListenAndServe</span>(address,<span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span>)<span style="color:#bbb">
</span></span></span></code></pre></div><p>This call to the public function <code>ListenAndServe</code> of the <code>net/http</code> package starts an HTTP server and binds it to the provided address.</p>
<p>The first input parameter <code>address</code> (above declared as a constant with value: <code>127.0.0.1:12345</code>) provides the address the HTTP server must listen on.</p>
<p>The second input parameter <code>nil</code> is commonly seen in Go. This is equivalent to <code>null</code> in many other languages and is an &ldquo;empty value&rdquo; for many (non-primitive) types in Go. As <code>ListenAndServe</code> supports multiple use-cases, it needs that second, optional parameter. We don&rsquo;t need that option here and hence can (or rather have to) provide <code>nil</code>.</p>
<p>The return parameter <code>err</code> (of the type <code>error</code>) will only be returned if the listening and serving fails. This could happen, for example, if the port <code>12345</code> is already in use on the address <code>127.0.0.1</code>. If no error occurs then <code>ListenAndServe</code> will block and keep running until you abort it (i.e. hit <code>ctrl + c</code>).</p>
<h3 id="error-handling">Error handling</h3>
<p>The last code block in the <code>main</code> function will soon become a common occurrence to you:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f">panic</span>(err)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Every language has their own way do deal with errors at runtime. Many do exception handling, which delegates runtime errors until something &ldquo;catches&rdquo; them (like <code>throw &lt;error&gt;</code> and <code>try { something } catch &lt;exception&gt; { handle }</code>).</p>
<p>Go does not have any of that. Instead it <em>solves error handling by convention</em>. This convention is to return any error that happens in the function and then appropriately handle the error in the caller.</p>
<p>Hence you will very often find the <code>if-err-return</code> pattern like so:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">SomeFunction</span>()<span style="color:#bbb"> </span><span style="color:#0b0;font-weight:bold">error</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>value,<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#00a000">someCall</span>()<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">		</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>err<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>}<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>Now, the caller of <code>SomeFunction</code> must take care to delegate the <code>error</code> &ldquo;further up&rdquo; as needed. Usually this means the error is handed up and up, until someone writes a <code>main</code> function and uses <code>panic</code> to act on the error, as we are doing in the example.</p>
<p>The <code>panic</code> function is one of the few built-in functions. It prints out a message (here: the error) then exits the program with a non-zero exit code. Depending on compilation it also prints a stack-trace from the panic location, so that developers - like you - can roll up our their sleeves and dig into debugging with a good idea where to start.</p>
<p>There is also a more condensed form of the <code>if-err-return</code> pattern, which looks like:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">if</span><span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span><span style="color:#00a000">anotherCall</span>();<span style="color:#bbb"> </span>err<span style="color:#bbb"> </span><span style="color:#666">!=</span><span style="color:#bbb"> </span><span style="color:#a2f;font-weight:bold">nil</span><span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#a2f;font-weight:bold">return</span><span style="color:#bbb"> </span>err<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><h3 id="http-handler-function">HTTP handler function</h3>
<p>This last piece of code implements our HTTP handler function, which was associated earlier with <code>http.HandleFunc()</code> call:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">helloWorld</span>(writer<span style="color:#bbb"> </span>http.ResponseWriter,<span style="color:#bbb"> </span>request<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>counter<span style="color:#666">++</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>response<span style="color:#bbb"> </span><span style="color:#666">:=</span><span style="color:#bbb"> </span>fmt.<span style="color:#00a000">Sprintf</span>(<span style="color:#b44">&#34;Hello World (%d)&#34;</span>,<span style="color:#bbb"> </span>counter)<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span>writer.<span style="color:#00a000">Write</span>([]<span style="color:#a2f">byte</span>(response))<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p>In short what is does:</p>
<ul>
<li>increment the global variable <code>counter</code> by 1</li>
<li>render a response string <code>Hello World (&lt;counter&gt;)</code></li>
<li>print the HTTP response</li>
</ul>
<p>The function input parameters refer to custom types declared in the <code>http</code> package. As we are using this function as an argument for <code>http.HandleFunc</code> above it must have this exact form:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a2f;font-weight:bold">func</span><span style="color:#bbb"> </span><span style="color:#00a000">handler</span>(http.ResponseWriter,<span style="color:#bbb"> </span><span style="color:#666">*</span>http.Request)<span style="color:#bbb"> </span>{<span style="color:#bbb">
</span></span></span><span style="display:flex;"><span><span style="color:#bbb">	</span><span style="color:#080;font-style:italic">// body</span><span style="color:#bbb">
</span></span></span><span style="display:flex;"><span>}<span style="color:#bbb">
</span></span></span></code></pre></div><p><strong>Note</strong>: The example code is not concurrency-safe. If you were to send requests to our HTTP server in parallel, it would eventually die and exist with a <code>panic</code>, since concurrent attempts to increment <code>counter</code> and / or read from <code>counter</code> would fail. This can be easily safe-guarded in Go, but I chose not to do it here for the sake of readability and brevity. If you feel like exploring, have a look at the <a href="https://pkg.go.dev/sync#pkg-index"><code>sync</code></a> or <a href="https://pkg.go.dev/sync/atomic#pkg-index"><code>sync/atomic</code></a> packages in the standard library.</p>
<h3 id="calling-methods-on-instances-of-types">Calling methods on instances of types</h3>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>writer.<span style="color:#00a000">Write</span>([]<span style="color:#a2f">byte</span>(response))<span style="color:#bbb">
</span></span></span></code></pre></div><p>The above expression in the body of the <code>helloWorld</code> method shows how a <em>method of a type</em> (=<code>http.ReponseWriter</code>) is called on the <em>instance of a type</em> (=<code>writer</code>).</p>
<p>It would be pronounced like so: <em>calling the <code>Write</code> method on the <code>writer</code> variable, which is an instance of the <code>http.ResponseWriter</code> type.</em></p>
<p>While this looks somewhat similiar to the <code>http.HandleFunc</code> and <code>http.ListenAndServe</code> called in the <code>main</code> function, the difference is that the <code>Write</code> call is &ldquo;executed&rdquo; on an instance (<code>writer</code>), not a package (<code>http</code>). It&rsquo;s a <em>method</em>, not a <em>function</em>.</p>
<p>Without going into too much detail (more on that in the following article of this series), know that custom types can have methods. You can then call these methods on the instances of those custom types. As in many other languages.</p>
<p>To investigate what methods are available for a type, you can again use <code>pkg.go.dev</code> and find out. In the case of the <code>http.ResponseWriter</code> have a look here:</p>
<ul>
<li><a href="https://pkg.go.dev/net/http?tab=doc#ResponseWriter">https://pkg.go.dev/net/http?tab=doc#ResponseWriter</a></li>
</ul>
<h3 id="type-conversion">Type conversion</h3>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>[]<span style="color:#a2f">byte</span>(response)<span style="color:#bbb">
</span></span></span></code></pre></div><p>This expression shows a <em>type conversion</em>. The inner part (<code>response</code>) is a <code>string</code>-type variable. As with in many other languages, strings and byte-arrays are closely related. Hence Go allows you to convert the string on-the-fly into <code>[]byte</code> (which Go calls <em>slice of bytes</em>, not byte array).</p>
<p>The conversion needs to be done because the <code>Write()</code> method expects a single <code>[]byte</code> input parameter and not a <code>string</code>.</p>
<p>Go allows you to convert from and to various built-in types. For example:</p>
<ul>
<li><code>int(2.55)</code> - converts the float number value <code>2.55</code> into an integer value (which changes the value to <code>2</code> of course)</li>
<li><code>uint8(5)</code> - converts the value of <code>5</code> (which Go assumes as <code>int</code>) into an unsigned integer with the (bit) length of 8</li>
<li><code>string([]byte(&quot;foobar&quot;))</code> - converts the string value &ldquo;foobar&rdquo; into a byte slice and back into a string (which is of course redundant, but maybe helps as an illustration)</li>
</ul>
<h2 id="summary">Summary</h2>
<p>Ok, this was quite a bit. You can find the full source code of everything above here: <a href="https://github.com/ukautz/go-intro/tree/master/beginner/http">https://github.com/ukautz/go-intro/tree/master/beginner/http</a></p>
<p>A quick review on what you learned:</p>
<ul>
<li>Running and compiling Go code</li>
<li>Lookup Go packages at <a href="https://pkg.go.dev">https://pkg.go.dev</a></li>
<li>The language basics of Go:
<ul>
<li>Commenting code</li>
<li>Create and import packages</li>
<li>Using constants and variables</li>
<li>Creating and calling functions</li>
<li>Using and casting types</li>
<li>Dealing with errors</li>
</ul>
</li>
<li>Writing an HTTP server
<ul>
<li>Routing to an HTTP handler</li>
<li>Writing an HTTP response to the requestor</li>
</ul>
</li>
</ul>
<p>If you are curious, check out another small command line application, which creates a table of content (toc) for Markdown files: <a href="https://github.com/ukautz/go-intro/tree/master/beginner/mdtoc">https://github.com/ukautz/go-intro/tree/master/beginner/mdtoc</a></p>
<h2 id="next-up">Next up</h2>
<p>Learn writing full fledge command line applications along with diving deeper into the Go language in the <a href="https://ulrichkautz.com/posts/2020-07-03_practical-go-3-of-3/">last article of this series</a>.</p>
]]></content:encoded></item><item><title>Practical introduction to Go: Development environment (1/3)</title><link>https://ulrichkautz.com/posts/2020-06-05_practical-go-1-of-3/</link><pubDate>Fri, 05 Jun 2020 18:00:00 +0200</pubDate><guid>https://ulrichkautz.com/posts/2020-06-05_practical-go-1-of-3/</guid><description>Setup local Go development environment</description><content:encoded><![CDATA[<p>This is the first part of the three part <em><a href="https://ulrichkautz.com/getting-started-with-go">practical introduction to Go</a></em> series. It is written for developers, who have already some experience in other languages and wish to learn and become productive in Go.</p>
<p>This article focuses on setting up a Go development environment, so that you can run and compile Go code locally and are prepared for the next parts of this series, starting with: <a href="https://ulrichkautz.com/posts/2020-06-10_practical-go-2-of-3/">Language basics</a>.</p>
<h2 id="why-go">Why Go?</h2>
<p>I love Go, so my perspective might be a bit biased. I also acknowledge that choice of programming language is heavily influenced by personal preference and suitability for the use-case at hand. Having this said, here is why I think Go is a great tool:</p>
<ul>
<li><strong>Simplicity</strong> by design. This makes it easy to learn and easy to collaborate. Instead of having a multitude of expressions to achieve the same thing (like so many other languages), Go provides only one.</li>
<li><strong>Concurrency</strong>, is a first class citizen! Go offers simple syntax and primitives that allow you to write code that uses all available CPU with little effort or complexity.</li>
<li><strong>Cross Compilation</strong>, is wonderfully easy. Compiling from Linux to Windows, from AMD64 to ARM or vice versa or any combination is a no-brainer.</li>
<li><strong>Dependency Management</strong>, is solved with built-in tooling and works like a charm. The Go authors were not shy to learn from others (mistakes).</li>
<li><strong>Huge and growing Ecosystem</strong>: There are already many very popular (Kubernetes, Docker, ..) software projects in Go, the <a href="https://awesome-go.com/">list keeps growing</a>.</li>
<li><strong>Built-in Tooling</strong>: Go comes with all the tooling you need for compiling, testing, profiing and benchmarking. It&rsquo;s fun to develop in, not a gazillion of needed tooling options like <em>(cough)</em> others..</li>
<li><strong>Extensive Standard Library</strong>: The Go Standard Library, part of every Go setup, provides everything from working with <a href="https://golang.org/pkg/archive/">archives in tar or zip</a>, to <a href="https://golang.org/pkg/encoding/#pkg-subdirectories">encoding/decoding of JSON, CSV, etc</a>, to a fast and powerful <a href="https://golang.org/pkg/net/http/">HTTP server and client</a>, to working with <a href="https://golang.org/pkg/text/template/">smart templates</a> - it&rsquo;s a lot of useful things.</li>
</ul>
<h2 id="go-language-tooling">Go language tooling</h2>
<p>The first thing you need to have to do any local Go development is the <code>go</code> binary. Head over to <a href="https://golang.org/dl/">https://golang.org/dl/</a> and download the installer, then follow the guide for your respective operating system:</p>
<ul>
<li><a href="https://golang.org/doc/install#tarball">Linux, FreeBSD, ..</a></li>
<li><a href="https://golang.org/doc/install#macos">macOS</a></li>
<li><a href="https://golang.org/doc/install#windows">Windows</a></li>
</ul>
<p>Once you followed the steps you should be able to execute <code>go version</code> from your terminal:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-sh" data-lang="sh"><span style="display:flex;"><span>$ go version
</span></span><span style="display:flex;"><span>go version go1.14.6 linux/amd64
</span></span></code></pre></div><p>That&rsquo;s it. Go comes with all you need out-of-the-box. The most important commands, which will be used in the following parts of this series, are:</p>
<ul>
<li><code>go run</code>: Development tooling to execute your source code</li>
<li><code>go build</code>: Compile source code into binary files</li>
<li><code>go test</code>: Run source code tests</li>
<li><code>go get</code>: Download dependencies (3rd party libraries)</li>
<li><code>go mod</code>: Handle module concerns, more on that later</li>
</ul>
<p>Aside from the <code>go</code> binary, the installation also comes with the source code of <a href="https://golang.org/pkg/#stdlib">Go Standard Library</a>, which we&rsquo;ll explore in the following articles.</p>
<h2 id="choose-your-ide">Choose your IDE</h2>
<p>If you already have a favorite IDE, chances are there is a good Go plugin or extension available. If not, or if you wish to try out something new consider the following:</p>
<h3 id="microsoft-visual-studio-code">Microsoft Visual Studio Code</h3>
<p>Relatively lightweight for a full IDE, extremely extensible, huge community &amp; ecosystem.</p>
<ul>
<li><strong>IDE</strong>: <a href="https://code.visualstudio.com/">https://code.visualstudio.com/</a></li>
<li><strong>Plugin</strong>: <a href="https://marketplace.visualstudio.com/items?itemName=golang.go">https://marketplace.visualstudio.com/items?itemName=golang.go</a></li>
<li><strong>HowTo</strong>: <a href="https://code.visualstudio.com/docs/languages/go">https://code.visualstudio.com/docs/languages/go</a></li>
</ul>
<h3 id="intellij-goland-or-idea-with-plugin">IntelliJ: GoLand (or IDEA with plugin)</h3>
<p>Full fledged IDE, first class Go integration, heavy weight.</p>
<p>IntelliJ offers two flavours:</p>
<ul>
<li><strong>Stand-alone</strong>: A Go-only IDE named <a href="https://www.jetbrains.com/go/">GoLand</a></li>
<li><strong>Plugin</strong>: If you already use <a href="https://www.jetbrains.com/idea/">IDEA</a>, use the <a href="https://plugins.jetbrains.com/plugin/9568-go">Go plugin</a></li>
</ul>
<h3 id="vim">VIM</h3>
<p>Battle tested, fast, <em>very</em> opinionated.</p>
<ul>
<li><strong>Plugin</strong>: <a href="https://github.com/fatih/vim-go">https://github.com/fatih/vim-go</a></li>
</ul>
<h3 id="others">Others</h3>
<p>Aside from the above many other editors and IDEs support Go development. To name a few:</p>
<ul>
<li><a href="https://atom.io/">Atom</a> with <a href="https://atom.io/packages/go-plus">go-plus plugin</a></li>
<li><a href="https://www.sublimetext.com/">Sublime Text</a> with <a href="https://github.com/DisposaBoy/GoSublime">GoSublime plugin</a></li>
<li><a href="https://www.eclipse.org/">Eclipse</a> with <a href="https://goclipse.github.io/">Goclipse extension</a></li>
<li><a href="https://www.gnu.org/software/emacs/">Emacs</a> in <a href="https://www.emacswiki.org/emacs/GoLangMode">GoLangMode</a></li>
</ul>
<h2 id="up-next">Up next</h2>
<p>Now that you have an editor of your choice and the Go binaries installed, head over to the next part in the series and get familiar with <a href="https://ulrichkautz.com/posts/2020-06-10_practical-go-2-of-3/">the language basics</a>.</p>
]]></content:encoded></item></channel></rss>