<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Maina Wycliffe on Medium]]></title>
        <description><![CDATA[Stories by Maina Wycliffe on Medium]]></description>
        <link>https://medium.com/@mainawycliffe?source=rss-3162bd0b0ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bpcqaDvoQ2M270VJ_9HUxg.jpeg</url>
            <title>Stories by Maina Wycliffe on Medium</title>
            <link>https://medium.com/@mainawycliffe?source=rss-3162bd0b0ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:15:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mainawycliffe/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build Efficient APIs in Go with GraphQL and gqlgen]]></title>
            <link>https://medium.com/the-godev-corner/build-efficient-apis-in-go-with-graphql-and-gqlgen-d8cbcb5edcfa?source=rss-3162bd0b0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8cbcb5edcfa</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Maina Wycliffe]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 14:12:40 GMT</pubDate>
            <atom:updated>2023-02-20T14:12:40.389Z</atom:updated>
            <content:encoded><![CDATA[<h4>Golang: How To Guide</h4><h4>A step-by-step guide to building robust, flexible APIs in Go</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TuIhh2WXWK02-3X8uwu8WQ.png" /><figcaption>Gopher credit art: @egonelbre | Source: github.com/egonelbre/gophers</figcaption></figure><h3>Introduction: Why gqlgen and GraphQL?</h3><p>Ahhh REST APIs — good ol’ faithful. Simple, straightforward, and easy to use.</p><p>They’ve been the “go-to” option for developers for quite a while. After all, who doesn’t want <em>predictable</em> and <em>consistent</em> APIs?</p><p>However, use cases are becoming more complex, more applications are requiring sophisticated data relationships, and efficient data retrieval is becoming paramount.</p><p>So some of the major drawbacks of using REST API’s are slowly being exposed (e.g., issues with documentation and over/under-fetching of data).</p><figure><img alt="Funny meme expressing interest to be more efficient and not waste time underfetching data" src="https://cdn-images-1.medium.com/max/727/0*6EX09ap39U0PeOSi.jpg" /></figure><p><strong>As a result, </strong><a href="https://graphql.org/"><strong>GraphQL</strong></a><strong> has emerged as a promising alternative by conveniently addressing these concerns.</strong></p><p>In fact, one of the main advantages of GraphQL is that it offers a query language similar to SQL, allowing you to retrieve specific data through a single query, rather than relying on multiple requests to various endpoints. This improves efficiency and reduces network traffic, among other benefits.</p><p>Additionally, GraphQL provides more flexibility for other developers to consume your API, even with deeply nested data.</p><p>There are several libraries available for building GraphQL APIs in Go, each with its own unique set of strengths and weaknesses. But in this article, we’ll be focusing on one of my favorites — <a href="https://gqlgen.com/">gqlgen</a>.</p><p><strong>Gqlgen is a schema-first GraphQL library that allows you to quickly build and deploy GraphQL APIs in Go, all while maintaining reliability and consistency.</strong></p><p>Overall, gqlgen is an excellent tool to leverage when building GraphQL APIs in Go. My goal here is to show you how you can use it to your advantage.</p><p>Ready? Let’s dive in.</p><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>❗️TL;DR</h3><blockquote>While REST APIs have been a popular choice for developers due to their simplicity and predictability, they also have their limitations.</blockquote><blockquote>With the need for more complex use cases and efficient data retrieval, GraphQL has emerged as a promising alternative, offering a more flexible and efficient way to consume APIs.</blockquote><blockquote>Gqlgen, a schema-first GraphQL library, can help you quickly build and deploy high-quality GraphQL APIs in Go, all while ensuring reliability and consistency.</blockquote><blockquote>This is a tutorial on how to use gqlgen to develop GraphQL APIs.</blockquote><h3>Gqlgen: Configuration &amp; Setup</h3><h4>How gqlgen works</h4><p>To build our GraphQL API using gqlgen, we’ll start by creating a GraphQL <a href="https://graphql.org/learn/schema/">schema</a>. From this, gqlgen will automatically generate all the required Go code for resolvers (i.e., type and fields resolvers) and data structures.</p><blockquote><em>👉 Note:</em> After you make changes to the schema, you’ll need to regenerate the code to ensure our resolvers and models remain in sync with it</blockquote><h4>Getting started with gqlgen</h4><p>Assuming you already have an initialized Go project, let’s create a tools.go file with the following content:</p><pre>//go:build tools<br>// +build tools<br><br>package tools<br><br>import (<br> _ &quot;github.com/99designs/gqlgen&quot;<br>)</pre><p>Next, we’ll want to install our dependencies within our source code by running the go mod tidy command:</p><pre>go mod tidy</pre><p>…and scaffold all the necessary configs needed for our gqlgen workspace:</p><pre>go run github.com/99designs/gqlgen init</pre><p>The end result should look like this:</p><figure><img alt="visual representation of scaffolding all the configs" src="https://cdn-images-1.medium.com/max/498/1*eK-IAw2PW3PN-CGyUTQEhg.png" /></figure><p>Next, let’s modify our resolver.go file and add the comment below after the Go imports, which tells the go generate command how to generate our schema when we run the go generate ./… command:</p><pre>//go:generate go run github.com/99designs/gqlgen generate</pre><p>Now, our resolver.go should look something like this:</p><pre>package graph<br><br>// This file will not be regenerated automatically.<br>//<br>// It serves as dependency injection for your app, add any dependencies you<br>// require here.<br><br>//go:generate go run github.com/99designs/gqlgen generate<br><br>type Resolver struct{}</pre><blockquote><strong><em>🎯 Pro Tip:</em> </strong>Our Resolver struct can be used to inject dependencies such as DB Clients, and we can access them inside our resolvers. For instance, let’s say we build a To-Do application; we then can store our list of tasks in a variable and pass it into the struct:</blockquote><pre>type Resolver struct {<br> TodoList []*model.Todo<br>}</pre><blockquote>Then, inside one of our resolvers, we can access our list of tasks:</blockquote><pre>func (r *queryResolver) Todos(ctx context.Context) ([]*model.Todo, error) {<br> return r.TodoList, nil<br>}</pre><h4>Configuring Gqlgen for flexibility</h4><p><strong>The flexibility of gqlgen is virtually limitless, and it allows you to configure nearly everything </strong>from file directories for generated files to more complex tasks, such as linking GraphQL schemas types to existing Go structures.</p><p>This can help you bypass struct generation and link to pre-existing ones, which can provide greater versatility in the development process. You can also configure other items as well, such as:</p><ul><li>Turning on gqlgen tags —i.e., instead of using JSON tags in Go structs, you can use the gqlgen:fieldName tag</li><li>Disabling and enabling slice pointers</li><li>Automatically binding existing Go structures within a package to corresponding GraphQL types<br><em>[This means that if a struct within a “models” directory shares the same name as a GraphQL type, gqlgen will prioritize the existing struct rather than create a new one]</em></li><li>And so much more (see <a href="https://gqlgen.com/config/">here</a> for more information)</li></ul><figure><img alt="meme featuring joey from Friends saying “who likes automation?” this guy" src="https://cdn-images-1.medium.com/max/602/0*MV--KzKOFODdw-61.jpg" /></figure><blockquote><strong><em>🎯 Pro Tip: </em></strong>You can break up your schemas into multiple files with gqlgen to manage your resolvers easier. So, instead of generating a single Go file with all resolvers, let’s say, the resolver code can be spread across multiple files to match the schema layout structure. <br>Note: you can always modify this for your specific needs.</blockquote><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>GraphQL Schema</h3><p>Let’s build a simple To-Do application to demo GraphQL. Since gqlgen is a schema-first tool, we’ll start by building the graphql schema.</p><p>First, let’s define the type. And to keep it simple, we’ll narrow the fields to just id, text and done.</p><pre>type Todo {<br>  id: ID!<br>  text: String!<br>  done: Boolean!<br>}</pre><p>Next, we need a GraphQL query to fetch our To-Do tasks:</p><pre>type Query {<br>  todos: [Todo!]!<br>}</pre><p>And then, we need GraphQL mutations to create, mark as done, and remove our To-Do tasks:</p><pre>type Mutation {<br>  createTodo(input: NewTodo!): Todo!<br>  toggleTodoDone(id: ID!): Todo!<br>  removeTodo(id: ID!): Todo!<br>}</pre><p>One last thing — even though we’re done with our schema, we’ll want to run code generation before we can proceed and implement our To-Do application:</p><pre>go generate ./...</pre><blockquote><em>👉 Note: </em>This will help generate the To-Do struct and resolvers needed for our queries and mutations.</blockquote><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Resolvers</h3><p>If you’re new to <strong>resolvers</strong>, they’re functions that help populate data for our schema from databases, APIs, etc., then return it to the caller.</p><p><strong>In our case, we’ll need four unique resolvers</strong>:</p><ul><li>todos — a resolver that will fetch all our To-Do tasks</li><li>createTodo — a mutation that will add new To-Do tasks</li><li>toggleTodoDone — a mutation that will mark To-Do tasks as complete (or not)</li><li>removeTodo — a mutation that will remove To-Do tasks</li></ul><p>Let’s go ahead and implement them.</p><h4>Todos Resolver — Fetching our To-Do tasks</h4><p>To keep things simple, let’s store our “To-Do” in an array that will be passed to our resolver struct:</p><pre>type Resolver struct {<br> TodoList []*model.Todo<br>}</pre><p>We’ll also want to create a To-Do variable and pass it to our struct when we initialize our graphql server inside our server.go (where our main function is currently located).</p><pre>func main() {<br> // ... other code generated by our todo<br><br> // ... our fake DB<br> todos := []*model.Todo{}<br><br> srv := handler.NewDefaultServer(graph.NewExecutableSchema(<br>  graph.Config{<br>   Resolvers: &amp;graph.Resolver{<br>    TodoList: todos,<br>   },<br>  },<br> ))<br><br> // ... move code for starting http server<br>}</pre><blockquote><em>👉 Note: </em>Feel free to replace the basic implementation of the DB here with your DB Client, as well as any other dependencies that your resolvers may require.</blockquote><p>Now that that&#39;s out of the way, let’s fetch our To-Do list by returning to our application:</p><pre>func (r *queryResolver) Todos(ctx context.Context) ([]*model.Todo, error) {<br> return r.TodoList, nil<br>}</pre><p>If we were using a database, this is where our business logic would go to fetch and do any necessary data transformation ☝️</p><p>Ok, let’s move on to mutations.</p><h4>CreateTodo Resolver — Adding new tasks</h4><p>Let’s create a new To-Do struct. We need to generate an id:</p><pre>id := uuid.New().String()<br>todo := &amp;model.Todo{<br> ID:   id,<br> Text: input.Text,<br> Done: false,<br>}</pre><p>…and push the To-Do item to our list:</p><pre>r.TodoList = append(r.TodoList, todo)</pre><p>Finally, let’s return our To-Do item:</p><pre>return todo, nil</pre><p>Our mutation resolver code should now look like this:</p><pre>func (r *mutationResolver) CreateTodo(ctx context.Context, input model.NewTodo) (*model.Todo, error) {<br> id := uuid.New().String()<br> todo := &amp;model.Todo{<br>  ID:   id,<br>  Text: input.Text,<br>  Done: false,<br> }<br> r.TodoList = append(r.TodoList, todo)<br> return todo, nil<br>}</pre><h4>ToggleTodoDone Resolver— Mark tasks as complete</h4><p>For our toggleTodoDone mutation, we need to find the task matching the provided id, then toggle and return the Done field:</p><pre>func (r *mutationResolver) ToggleTodoDone(ctx context.Context, id string) (*model.Todo, error) {<br> for _, todo := range r.TodoList {<br>  if todo.ID == id {<br>   todo.Done = !todo.Done<br>   return todo, nil<br>  }<br> }<br> return nil, nil<br>}</pre><h4>RemoveTodo Resolver — Remove tasks</h4><p>Similarly, for our removeTodo mutation, we need to find the task matching the provided id, remove it from the list, and return the removed task.</p><pre>func (r *mutationResolver) RemoveTodo(ctx context.Context, id string) (*model.Todo, error) {<br> for i, todo := range r.TodoList {<br>  if todo.ID == id {<br>   r.TodoList = append(r.TodoList[:i], r.TodoList[i+1:]...)<br>   return todo, nil<br>  }<br> }<br> return nil, nil<br>}</pre><p>And that’s it! Now we can test our application by running the Go server.</p><pre>go run server.go</pre><p>You can access the GraphiQL playground via the URL <a href="http://localhost:8000/">http://localhost:8000/</a> on your local server and the API endpoint via <a href="http://localhost:8000/">http://localhost:8000/</a>query</p><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Conclusion</h3><p>In this post, we built a simple To-Do application in GraphQL API using Go and gqlgen, then explored how we can customize different configurations for gqlgen.</p><p>In the next few articles, we’ll build more complex applications with field resolvers, data loaders, GraphQL custom scalers, etc., which will help us create production ready GraphQL APIs. Stay tuned</p><h4>Main Takeaways</h4><ol><li>gqlgen is a schema-first tool that automatically generates the required Go code for resolvers and data structures from a GraphQL schema</li><li>gqlgen is highly configurable and allows you to bypass struct generation and link to pre-existing structures, which can provide greater versatility in the development process</li><li>To build a Go application using gqlgen, you need to create a GraphQL schema, generate resolvers using gqlgen, then implement the code for resolvers (i.e., in our case — to fetch, create, update, and remove To-Do tasks) that will run queries <a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> queries against our database.</li></ol><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Other Articles To Consider</h3><ul><li><a href="https://medium.com/the-godev-corner/simplify-your-configurations-in-go-b7747c45ebf7">Simplify Your Configurations in Go</a></li><li><a href="https://medium.com/the-godev-corner/expand-web-app-development-with-go-fc07d55b41f6">Build Powerful Client-Side Web Apps Using Go</a></li></ul><p><em>Disclosure: In accordance with Medium.com’s rules and guidelines, I publicly acknowledge financial compensation from </em><a href="http://www.unidoc.io/"><em>UniDoc</em></a><em> for this article. All thoughts, opinions, code, pictures, writing, etc. are my own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8cbcb5edcfa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-godev-corner/build-efficient-apis-in-go-with-graphql-and-gqlgen-d8cbcb5edcfa">Build Efficient APIs in Go with GraphQL and gqlgen</a> was originally published in <a href="https://medium.com/the-godev-corner">The GoDev Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify Your IaC Provisioning with AWS CDK]]></title>
            <link>https://medium.com/the-godev-corner/simplify-your-iac-provisioning-with-aws-cdk-2faea805c760?source=rss-3162bd0b0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/2faea805c760</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Maina Wycliffe]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 16:40:33 GMT</pubDate>
            <atom:updated>2023-01-26T16:40:33.189Z</atom:updated>
            <content:encoded><![CDATA[<h4>Golang: How To Guide</h4><h4>Eliminate the complexity of managing your config files in YAML/JSON</h4><figure><img alt="Visualization of the golang gopher dreaming about IaC and how it relates to AWS CDK" src="https://cdn-images-1.medium.com/max/957/1*jfKYYllIdfsiengTIMsQ4A.png" /></figure><h3>Introduction</h3><p>Let’s face it — managing <a href="https://www.redhat.com/en/topics/automation/what-is-infrastructure-as-code-iac">infrastructure as code (IaC)</a> has its pros and cons.</p><p>On one hand, IaC lets you automate infrastructure provisioning, which saves you a lot of time and improves overall efficiency. It also makes tracking changes a lot easier and adds more precision to your ability to version control the infrastructure. For instance, if you make a mistake, just run git revert and redeploy.</p><p>On the other hand, <strong>you might face some really tough uphill battles, especially in dealing with large and complex config files written in YAML/JSON</strong>. Trying to shoe-horn YAML/JSON to accommodate things such as variables, expressions, etc., pushes them to a DSL territory unique to IaC. This creates difficulty in reading and modifying config files, and often forces developers to tip-toe around, even when making the smallest of changes.</p><p>Luckily, there’s <a href="https://aws.amazon.com/cdk/">AWS Cloud Development Kit (CDK)</a>, which can make a lot of the complexity disappear into thin air.</p><p><strong>AWS CDK is an open-source framework by AWS that allows you to use any programming language to write code to provision your infrastructure.</strong> This means you can write code in a more familiar and idiomatic way, plus better test and abstract shared resources (or even distribute them as shared libraries).</p><p>Today, we’ll walk through how to use AWS CDK and Go to provision your AWS infrastructure. We’ll cover everything from writing code to testing to deploying changes. I’ll also share some tips and best practices along the way for working with Go in the context of IaC.</p><p>Ready? Let’s get started</p><p><strong>❗️TL;DR</strong></p><blockquote>Using AWS CDK and Go, you can more easily manage and provision the infrastructure for your code by:</blockquote><blockquote>1. Writing code that’s in your preferred language (e.g., Go), improving general efficiency</blockquote><blockquote>2. Writing unit tests that can automatically test the code before deploying changes (to better ensure everything is working as expected)</blockquote><blockquote>3. Abstracting code more smoothly, making it easier to reuse and share across teams and projects</blockquote><blockquote>4. Controlling your infrastructure better, and roll back changes more quickly if needed</blockquote><blockquote>Here’s the big takeaway: Managing and provisioning your infrastructure through YAML/JSON files is cumbersome, time-consuming, and error-prone. AWS CDK simplifies this.</blockquote><figure><img alt="Unique separator for The GoDev Corner articles" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Short Preface</h3><h4>What you will learn</h4><ul><li><a href="#7276">How to install and set up your infrastructure</a> using AWS CDK</li><li><a href="#03a2">How to build the infrastructure</a> (via “stacking,” a DynamoDB table, and lambda functions)</li><li><a href="#5b36">How to deploy the infrastructure</a> to the cloud</li><li><a href="#2649">How to unit test the infrastructure</a> to confirm configurations are set up properly</li><li>Overall, you’ll learn how to use AWS CDK to provision and manage your infrastructure and how to write IaC using Golang.</li></ul><h4>Prerequisites</h4><ul><li>Required: Moderate understanding of Go and how to write unit tests</li><li>Required: Go version 1.18+ (to use AWS CDK)</li><li>Required: NodeJS v10.18.0+<br><em>Recommended: NodeJS v18 (LTS)</em></li><li>Helpful: Basic understanding of Amazon Web Services (AWS)</li></ul><blockquote>📌 <strong><em>Disclaimer</em></strong>: This is the first of a series of articles on the topic of how to use Go with IaC. Next week we will take a look at <a href="https://github.com/hashicorp/terraform-cdk">Terraform CDK</a>, and when you should use it instead of AWS CDK</blockquote><figure><img alt="Unique separator for The GoDev Corner articles" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Getting Started</h3><h4>Installation and setup</h4><p>Let’s start by installing AWS CDK locally to scaffold a new AWS CDK project. At this point, we will need to have NodeJS v10.18.0 (at least) installed, though I recommend going with <a href="https://nodejs.org/en/download/">v18 (LTS)</a>.</p><p>NodeJS comes bundled with the NPM package manager, which is what we need to install AWS CDK, as shown below:</p><pre>npm install -g aws-cdk</pre><p>After that has completed running, I would encourage you to confirm that AWS CDK was installed successfully:</p><pre>cdk --version</pre><p>Next, ensure you have AWS Credentials set up locally to deploy the infrastructure using AWS CDK. A couple of options here:</p><ol><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">Install AWS CLI locally</a>. Then configure your AWS Account Credentials by running the command aws configure . There, enter the AWS Keys for your AWS Account IAM user as requested. AWS CDK will use the above credentials during the deployment process.</li><li>Set the environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_DEFAULT_REGION, which can be used to pass credentials to AWS CDK.</li></ol><p>Finally, we need to bootstrap our AWS Account. AWS CDK requires dedicated AWS S3 buckets and other containers to be available to AWS CloudFormation during deployment. These are created during the bootstrapping process, which can be done using the command below.</p><pre>cdk bootstrap aws://[AWS_ACCOUNT_NO]/[AWS_REGION]</pre><h4>Scaffolding the AWS CDK Application for Go</h4><p>Let’s create a new directory for our project and then run cdk init --language go(with Go as the language flag) to create the Go files necessary for our project:</p><pre>cdk init --language go</pre><p>The above command will scaffold a new CDK project which should look like this:</p><figure><img alt="New CDK project visualization" src="https://cdn-images-1.medium.com/max/543/1*m4akk6elN1rKhmCSN06ZPw.png" /></figure><blockquote><em>👉 </em><strong><em>Note</em></strong>: Just a heads up, you will need to run go get ./... to install dependencies after this</blockquote><p>A CDK project is a run-of-the-mill Go project, meaning other than its CloudFormation templated output, this will be just another normal Go project.</p><p>I bring this up because AWS CDK uses a custom command to run your Go CDK app, which runs only a single file: golang_aws_cdk_demo-app.go in our case.</p><p>If you split your application into multiple files, you might want to customize this. This can be done by changing the app property inside the cdk.json config file, as shown below:</p><figure><img alt="Visualization of changing the app property inside the cdk.json config file" src="https://cdn-images-1.medium.com/max/1024/1*-8nhOK4fWRYNWMboA5uZ_w.png" /></figure><figure><img alt="Unique separator for The GoDev Corner articles" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Building The Infrastructure</h3><p>Now that that’s completed, let’s construct our infrastructure for the CRUD app. To keep things simple, we’ll focus on how to set up the table, lambda functions, and IAM permissions we’ll need.</p><blockquote><em>👉 </em><strong><em>Note</em></strong>: Getting into the details of lambda functions with regard to CRUD functionality against DynamoDB is a bit outside the scope of this article. Also, before we go any further, I want to note that we are using <strong>Version 2 </strong>of AWS CDK, and stress that your Go imports should look like this: github.com/aws/aws-cdk-go/awscdk/v2/**</blockquote><h4>Creating a Stack</h4><p>First, we’ll need a stack to put our resources in. A <strong>stack</strong> is a unit of deployment, and all resources defined within a stack are deployed or deleted together as a unit.</p><p>AWS CDK Stacks are built on top of CloudFormation Stacks, and all rules from CloudFormation apply to CDK Stacks.</p><blockquote><em>📖 </em><strong><em>Further Reading</em></strong><em>:</em> You can read more about CloudFormation Stacks <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html">here</a></blockquote><p>To create a stack using AWS CDK, we’ll need to create a CDK Application using the awscdk.NewApp function, which accepts <a href="https://pkg.go.dev/github.com/aws/aws-cdk-go/awscdk/v2#AppProps">AppProps</a> as the only argument:</p><pre>app := awscdk.NewApp(nil)</pre><p>Then, we will use awscdk.NewStack, which accepts one of the following:</p><ul><li>app — a CDK App as the first argument (the one we just created previously)</li><li>id — a unique identifier of the stack</li><li><a href="https://pkg.go.dev/github.com/aws/aws-cdk-go/awscdk/v2#StackProps">StackProps</a></li></ul><blockquote><em>📖 </em><strong><em>Further Reading</em></strong><em>: </em>For different ways to configure your AWS CDK stack, please refer to the <a href="https://docs.aws.amazon.com/cdk/v2/guide/stacks.html">official documentation</a></blockquote><pre>props := awscdk.StackProps{}<br>stack := awscdk.NewStack(scope, jsii.String(&quot;GolangAwsCdkDemoStack&quot;), &amp;sprops)</pre><p>Setting up the stack is pretty simple. Now we can put everything together nicely:</p><pre>package main<br><br>import (<br> &quot;github.com/aws/aws-cdk-go/awscdk/v2&quot;<br> &quot;github.com/aws/constructs-go/constructs/v10&quot;<br> &quot;github.com/aws/jsii-runtime-go&quot;<br>)<br><br>// NewGolangAwsCdkDemoStack makes it easy to test the whole stack<br>func NewGolangAwsCdkDemoStack(scope constructs.Construct, id string, props *awscdk.StackProps) awscdk.Stack {<br> stack := awscdk.NewStack(scope, jsii.String(id), props)<br><br> // CODE FOR INFRASTRUCTURE GOES HERE<br><br> return stack<br>}<br><br>func main() {<br> defer jsii.Close()<br><br> app := awscdk.NewApp(nil)<br><br> NewGolangAwsCdkDemoStack(app, &quot;GolangAwsCdkDemoStack&quot;, &amp;awscdk.StackProps{})<br><br> app.Synth(nil)<br>}</pre><h4>Setting up a DynamoDB table</h4><p>Next, let’s set up a DynamoDB table, which we’ll name Members.</p><blockquote><em>👉 </em><strong><em>Note</em></strong>: We’ll have to create a Go function to help us with this (see below). For the imports, we need to remember to import v2 of AWS CDK.</blockquote><p>We can do this by using the awsdynamodb.NewTable function, which accepts:</p><ul><li>A stack — which we created in the previous section,</li><li>An ID for our resource needs to be unique within the stack, and</li><li>Stack properties, where we can configure things such as: TableName, Primary Keys, etc.</li></ul><blockquote><strong><em>📖 Further Reading</em></strong>: More information can be found <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html">here</a>.</blockquote><p>Our function returns an instance of the created table, which we’ll use to easily grant permissions to our lambdas and access properties, such as names.</p><pre>package main<br><br>import (<br> &quot;github.com/aws/aws-cdk-go/awscdk/v2&quot;<br> &quot;github.com/aws/aws-cdk-go/awscdk/v2/awsdynamodb&quot;<br> &quot;github.com/aws/jsii-runtime-go&quot;<br>)<br><br>func MembersDynamoDBTable(stack awscdk.Stack) awsdynamodb.Table {<br> table := awsdynamodb.NewTable(stack,<br>  jsii.String(&quot;membersDynamoDBTable&quot;),<br>  &amp;awsdynamodb.TableProps{<br>   PartitionKey: &amp;awsdynamodb.Attribute{<br>    Name: jsii.String(&quot;id&quot;),<br>    Type: awsdynamodb.AttributeType_STRING,<br>   },<br>   TableName:   jsii.String(&quot;Members&quot;),<br>  },<br>  // ... OTHER PROPERTIES FOR THE TABLE ...<br> )<br> return table<br>}</pre><p>To create our DynamoDB table, we can call the function from NewGolangAwsCdkDemoStack , and pass it in the stack we created earlier:</p><pre>func NewGolangAwsCdkDemoStack(scope constructs.Construct, id string, props *awscdk.StackProps) awscdk.Stack {<br> stack := awscdk.NewStack(scope, jsii.String(id), props)<br><br> dynamodbTable := MembersDynamoDBTable(stack)<br><br> return stack<br>}</pre><h4>Using lambda functions to delete members</h4><p>Ok, now we need to create a lambda function that will delete members from DynamoDB. In this case, on top of our function accepting a stack parameter, it should also accept the DynamoDB table we created previously as the second parameter.</p><p>To create our lambda function, let’s use the awscdklambdagoalpha.NewGoFunction, which accepts:</p><ul><li>stack as the first argument</li><li>id as the id of the resource, which needs to be unique across the stack, and</li><li>GoFunctionsProps— which allows us to configure our lambda function</li></ul><p>With this function, we’ll also need to complete two subtasks:</p><ol><li>Set up the runtime environment. In our case, we are using Go — awslambda.Runtime_GO_1_X — but lambda functions support several <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html">languages</a></li><li>Obtain the path to the source file of our lambda function, which is the lambdas/delete directory in our case</li></ol><pre>function := awscdklambdagoalpha.NewGoFunction(stack,<br>  jsii.String(&quot;deleteMemberLambdaFunction&quot;),<br>  &amp;awscdklambdagoalpha.GoFunctionProps{<br>   Entry:   jsii.String(&quot;./lambdas/delete&quot;),<br>   Runtime: awslambda.Runtime_GO_1_X(),<br>   Environment: &amp;map[string]*string{<br>    // Pass the table name to the lambda function<br>    &quot;MEMBERS_TABLE_NAME&quot;: membersTable.TableName(),<br>   },<br>  },<br> )</pre><blockquote><em>👉 </em><strong><em>Note</em></strong><em>:</em> To deploy Go applications using AWS CDK, you will need to have Go installed into the system you are running AWS CDK on</blockquote><p>We’ll use the DynamoDB table to get the table name and then grant the lambda function permission to read and write our DynamoDB table. <strong>Essentially, we’re passing the table name for </strong><strong>Members as the environment variable so that we can use it within our lambda.</strong></p><p>Lastly, we need to grant the lambda function permission to delete items from our table. For this, we can use the tableInstance.GrantReadWriteData helper method:</p><pre>membersTable.GrantReadWriteData(function)</pre><blockquote><strong><em>🎯 Pro Tip</em></strong>: While the above provides broad permissions for our lambda function, you might want to be more specific with your permissions</blockquote><p>To grant our lambda function permissions, use the function tableInstance.Grant (or AWS Resource to grant permissions for) and an array of strings containing that contains the permissions:</p><pre>membersTable.Grant(function, jsii.String(&quot;dynamodb:DeleteItem&quot;), jsii.String(&quot;dynamodb:Scan&quot;))</pre><p>Here’s the output:</p><pre>package main<br><br>import (<br> &quot;github.com/aws/aws-cdk-go/awscdk/v2&quot;<br> &quot;github.com/aws/aws-cdk-go/awscdk/v2/awsdynamodb&quot;<br> &quot;github.com/aws/aws-cdk-go/awscdk/v2/awslambda&quot;<br> &quot;github.com/aws/aws-cdk-go/awscdklambdagoalpha/v2&quot;<br> &quot;github.com/aws/jsii-runtime-go&quot;<br>)<br><br>func deleteMemberLambdaFunction(stack awscdk.Stack, membersTable awsdynamodb.Table) awslambda.Function {<br> function := awscdklambdagoalpha.NewGoFunction(stack,<br>  jsii.String(&quot;deleteMemberLambdaFunction&quot;),<br>  &amp;awscdklambdagoalpha.GoFunctionProps{<br>   Entry:   jsii.String(&quot;./lambdas/delete&quot;),<br>   Runtime: awslambda.Runtime_GO_1_X(),<br>   Environment: &amp;map[string]*string{<br>    // Pass the table name to the lambda function<br>    &quot;MEMBERS_TABLE_NAME&quot;: membersTable.TableName(),<br>   },<br>  },<br> )<br><br> // Grant the lambda function read/write permissions to our table<br> membersTable.GrantReadWriteData(function)<br> return function<br>}</pre><p>Now, create our lambda function by calling it from the NewGolangAwsCdkDemoStack function as shown below:</p><pre>func NewGolangAwsCdkDemoStack(scope constructs.Construct, id string, props *awscdk.StackProps) awscdk.Stack {<br> stack := awscdk.NewStack(scope, jsii.String(id), props)<br><br> dynamodbTable := MembersDynamoDBTable(stack)<br><br> deleteMemberLambdaFunction(stack, dynamodbTable)<br><br> return stack<br>}</pre><blockquote><strong><em>📖 Further Reading</em></strong>: For the delete members’ lambdas, see this <a href="https://github.com/mainawycliffe/golang-aws-cdk-demo/blob/main/lambdas/delete/delete.go">code</a></blockquote><h4>Using lambda functions to upsert members</h4><p>Ok, let’s create a lambda function to upsert members to DynamoDB. Just like in the previous section, we’ll use the function awscdklambdagoalpha.NewGoFunction to do so.</p><p>The upsert lambda will be similar to the previous “delete” one but with a different entry file for the source code of our application:</p><pre>func upsertMemberLambdaFunction(stack awscdk.Stack, membersTable awsdynamodb.Table) awslambda.Function {<br> function := awscdklambdagoalpha.NewGoFunction(stack,<br>  jsii.String(&quot;upsertMemberLambdaFunction&quot;),<br>  &amp;awscdklambdagoalpha.GoFunctionProps{<br>   Entry:   jsii.String(&quot;./lambdas/upsert&quot;),<br>   Runtime: awslambda.Runtime_GO_1_X(),<br>   Environment: &amp;map[string]*string{<br>    // Pass the table name to the lambda function<br>    &quot;MEMBERS_TABLE_NAME&quot;: membersTable.TableName(),<br>   },<br>  },<br> )<br> // ... MORE CODE<br>}</pre><p>This lambda function will need Read and Write permissions for our DynamoDB, so let’s add them:</p><pre> membersTable.GrantReadWriteData(function)</pre><p>And this is what our AWS CDK lambda function should look like now:</p><pre>package main<br><br>import (<br> &quot;github.com/aws/aws-cdk-go/awscdk/v2&quot;<br> &quot;github.com/aws/aws-cdk-go/awscdk/v2/awsdynamodb&quot;<br> &quot;github.com/aws/aws-cdk-go/awscdk/v2/awslambda&quot;<br> &quot;github.com/aws/aws-cdk-go/awscdklambdagoalpha/v2&quot;<br> &quot;github.com/aws/jsii-runtime-go&quot;<br>)<br><br>func upsertMemberLambdaFunction(stack awscdk.Stack, membersTable awsdynamodb.Table) awslambda.Function {<br> function := awscdklambdagoalpha.NewGoFunction(stack,<br>  jsii.String(&quot;upsertMemberLambdaFunction&quot;),<br>  &amp;awscdklambdagoalpha.GoFunctionProps{<br>   Entry:   jsii.String(&quot;./lambdas/upsert&quot;),<br>   Runtime: awslambda.Runtime_GO_1_X(),<br>   Environment: &amp;map[string]*string{<br>    // Pass the table name to the lambda function<br>    &quot;MEMBERS_TABLE_NAME&quot;: membersTable.TableName(),<br>   },<br>  },<br> )<br><br> // Grant the lambda function read/write permissions to our table<br> membersTable.GrantReadWriteData(function)<br> return function<br>}</pre><p>And then, we can call our function as we did with upsertMemberLambdaFunction from NewGolangAwsCdkDemoStack to create our second lambda function:</p><pre>func NewGolangAwsCdkDemoStack(scope constructs.Construct, id string, props *awscdk.StackProps) awscdk.Stack {<br> stack := awscdk.NewStack(scope, jsii.String(id), props)<br><br> dynamodbTable := MembersDynamoDBTable(stack)<br><br> upsertMemberLambdaFunction(stack, dynamodbTable)<br><br> return stack<br>}</pre><h4>Using lambda functions to get members</h4><p>Finally, for our last lambda function, let’s create one where it only contains read-only (no write) IAM permissions:</p><pre>package main<br><br>import (<br> &quot;github.com/aws/aws-cdk-go/awscdk/v2&quot;<br> &quot;github.com/aws/aws-cdk-go/awscdk/v2/awsdynamodb&quot;<br> &quot;github.com/aws/aws-cdk-go/awscdk/v2/awslambda&quot;<br> &quot;github.com/aws/aws-cdk-go/awscdklambdagoalpha/v2&quot;<br> &quot;github.com/aws/jsii-runtime-go&quot;<br>)<br><br>func getMemberLambdaFunction(stack awscdk.Stack, membersTable awsdynamodb.Table) awslambda.Function {<br><br> function := awscdklambdagoalpha.NewGoFunction(stack,<br>  jsii.String(&quot;getMemberLambdaFunction&quot;),<br>  &amp;awscdklambdagoalpha.GoFunctionProps{<br>   Entry:   jsii.String(&quot;./lambdas/get&quot;),<br>   Runtime: awslambda.Runtime_GO_1_X(),<br>   Environment: &amp;map[string]*string{<br>    // Pass the table name to the lambda function<br>    &quot;MEMBERS_TABLE_NAME&quot;: membersTable.TableName(),<br>   },<br>  },<br> )<br><br> // Grant the lambda function read/write permissions to our table<br> membersTable.GrantReadData(function)<br> return function<br>}</pre><p>And just like the other two, we can call the function from NewGolangAwsCdkDemoStack to create it:</p><pre>func NewGolangAwsCdkDemoStack(scope constructs.Construct, id string, props *awscdk.StackProps) awscdk.Stack {<br> stack := awscdk.NewStack(scope, jsii.String(id), props)<br><br> dynamodbTable := MembersDynamoDBTable(stack)<br><br> getMemberLambdaFunction(stack, dynamodbTable)<br><br> return stack<br>}</pre><p>And with the exception of deploying our infrastructure, that’s it.</p><figure><img alt="Unique separator for The GoDev Corner articles" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Deploying</h3><p>There’s no point in creating this beautiful infrastructure and not deploying it, so let’s get this going.</p><p><strong>Simply use the </strong><strong>cdk deploy command to deploy the CDK app, which will create all the resources we need for our application</strong>:</p><pre>cdk deploy</pre><p>And boom — deployed.</p><figure><img alt="Unique separator for The GoDev Corner articles" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Unit Testing the Infrastructure</h3><p>One of the best parts of the AWS CDK is being able to unit test our infrastructure code, just like any other Go code. Here, I want to focus on testing the following in relation to the infrastructure we created above:</p><ul><li>Our DynamoDB table, to ensure it was configured correctly</li><li>Our AWS lambdas, to ensure we have configured their functions accurately, and</li><li>Our IAM policies, to ensure they’re configured with the correct permissions</li></ul><h4>Testing the DynamoDB table</h4><p>To test our table, the first thing we’ll do is check whether it contains the properties that we expect it to.</p><p>To do this, let’s define a test stack containing <strong><em>only our table</em></strong> and nothing else:</p><pre>func TestMembersDynamoDBTable(t *testing.T) {<br> app := awscdk.NewApp(nil)<br> stack := NewGolangAwsCdkDemoStack(app, &quot;TestStack&quot;, nil)<br><br> MembersDynamoDBTable(stack)<br><br> // more code to follow ....<br>}</pre><p>Next, let’s synthesize a CloudFormation template using the assertions.Template_FromStack function. This will take our stack as the first argument, and different parsing options (i.e., <a href="https://pkg.go.dev/github.com/aws/aws-cdk-go/awscdk/v2@v2.59.0/assertions#TemplateParsingOptions">template assertion parsing options</a>) as the second (or nil in our case):</p><pre>template := assertions.Template_FromStack(stack, nil)</pre><p>Next, we can finally check whether the stack contains our table with specific properties using the template.HasResourceProperties method. Here, we only care about the table name and primary keys, but we can use any property from <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html">CloudFormation</a>:</p><pre>template.HasResourceProperties(jsii.String(&quot;AWS::DynamoDB::Table&quot;), map[string]interface{}{<br>  &quot;TableName&quot;: &quot;Members&quot;,<br>  &quot;KeySchema&quot;: []map[string]interface{}{<br>   {<br>    &quot;AttributeName&quot;: &quot;id&quot;,<br>    &quot;KeyType&quot;:       &quot;HASH&quot;,<br>   },<br>  },<br>})</pre><blockquote><em>👉 </em><strong><em>Note</em></strong><em>: </em>You can run the test just like any other Go test.</blockquote><h4>Testing the lambda functions</h4><p>Once completed, let’s test our lambda functions; we want them to have the correct properties and permissions.</p><p>Just like before, let’s start by defining a test stack for testing them. We will need a DynamoDB table, which our lambda functions require for name and permission purposes. For simplicity’s sake, let’s re-use the one we had previously (though, it’s a much better practice to create a separate table for testing).</p><p>Next, use the Template_FromStack function to get a CloudFormation template to run assertions against:</p><pre>app := awscdk.NewApp(nil)<br>stack := NewGolangAwsCdkDemoStack(app, &quot;TestStack&quot;, nil)<br><br>// you can create a test table here instead<br>table := MembersDynamoDBTable(stack)<br>getMemberLambdaFunction(stack, table)<br><br>template := assertions.Template_FromStack(stack, nil)</pre><blockquote><em>👉 </em><strong><em>Note</em></strong><em>: </em>AWS CDK assertions library ensures you can write tests that don’t exactly match your CloudFormation template, so you only test things that you truly care about</blockquote><p>Now, for our actual lambda function, let’s check whether it has the correct runtime environment (i.e., in our case, Go) and whether we’re setting the member table environment variable accurately:</p><pre>template.HasResourceProperties(jsii.String(&quot;AWS::Lambda::Function&quot;), map[string]interface{}{<br> &quot;Runtime&quot;: &quot;go1.x&quot;,<br> &quot;Environment&quot;: map[string]interface{}{<br>  &quot;Variables&quot;: map[string]interface{}{<br>   &quot;MEMBERS_TABLE_NAME&quot;: map[string]interface{}{<br>    &quot;Ref&quot;: assertions.Match_StringLikeRegexp(jsii.String(&quot;membersDynamoDBTable*&quot;)),<br>   },<br>  },<br> },<br>})</pre><blockquote><strong><em>🎯 Pro Tip: </em></strong>assertions.Match_StringLikeRegexp allows us to match the environment variable to regex instead of the environment variable. You can learn more about this <a href="https://pkg.go.dev/github.com/aws/aws-cdk-go/awscdk/v2@v2.59.0/assertions#Matcher">here</a>.</blockquote><h4>Testing the IAM policies</h4><p>Next, we need to ensure that we can read data inside our table by looking for the AWS::IAM::Policy resource that has the correct policy document associated with our lambda function and table.</p><pre>template.HasResourceProperties(jsii.String(&quot;AWS::IAM::Policy&quot;), map[string]interface{}{<br>  &quot;PolicyDocument&quot;: map[string]interface{}{<br>   &quot;Statement&quot;: []map[string]interface{}{<br>    {<br>     &quot;Action&quot;: assertions.Match_ArrayWith(&amp;[]interface{}{<br>      &quot;dynamodb:GetItem&quot;,<br>     }),<br>     &quot;Effect&quot;: &quot;Allow&quot;,<br>     &quot;Resource&quot;: assertions.Match_ArrayWith(<br>      &amp;[]interface{}{<br>       map[string]interface{}{<br>        &quot;Fn::GetAtt&quot;: []interface{}{<br>         assertions.Match_StringLikeRegexp(jsii.String(&quot;membersDynamoDBTable*&quot;)),<br>         &quot;Arn&quot;,<br>        },<br>       },<br>      },<br>     ),<br>    },<br>   },<br>  },<br>  &quot;Roles&quot;: assertions.Match_ArrayWith(<br>   &amp;[]interface{}{<br>    map[string]interface{}{<br>     &quot;Ref&quot;: assertions.Match_StringLikeRegexp(jsii.String(&quot;getMemberLambdaFunctionServiceRole*&quot;)),<br>    },<br>   },<br>  ),<br> })</pre><blockquote><strong><em>🎯 Pro Tip:</em></strong><em> T</em>he assertions.Match_ArrayWith matcher method allows us to find an array that contains only our actions (instead of listing everything else)</blockquote><p>The same can be done for the rest of our lambda functions, with tweaks to match as needed.</p><figure><img alt="Unique separator for The GoDev Corner articles" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Conclusion</h3><p>In this article, we learned how to use Golang to write IaC for our infrastructure. In a nutshell, we can use AWS CDK to manage our infrastructure instead of writing everything in YAML/JSON, which for large projects, can be a nightmare to maintain.</p><h4>Main Takeaways</h4><ul><li>With AWS CDK, you can write code that is familiar to you — idiomatic Go code, just as if you were writing code for any other Go application</li><li>This also means you can control your infrastructure better, allowing you to spot errors easier, abstract code more smoothly, and quickly identify where you can improve</li><li>Lastly, with AWS CDK, you can write unit tests that automatically test your code before deploying changes to your infrastructure, which simultaneously guards against regressions</li></ul><figure><img alt="Unique separator for The GoDev Corner articles" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Other Articles You Might Like</h3><ul><li><a href="https://medium.com/the-godev-corner/expand-web-app-development-with-go-fc07d55b41f6">Build Powerful Client-Side Web Apps Using Go</a></li><li><a href="https://medium.com/the-godev-corner/simplify-your-configurations-in-go-b7747c45ebf7">Simplify Your Configurations in Go</a></li></ul><p><em>Disclosure: In accordance with Medium.com’s rules and guidelines, I publicly acknowledge financial compensation from </em><a href="http://www.unidoc.io/"><em>UniDoc</em></a><em> for this article. All thoughts, opinions, code, pictures, writing, etc. are my own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2faea805c760" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-godev-corner/simplify-your-iac-provisioning-with-aws-cdk-2faea805c760">Simplify Your IaC Provisioning with AWS CDK</a> was originally published in <a href="https://medium.com/the-godev-corner">The GoDev Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your Go Application Builds & Releases]]></title>
            <link>https://medium.com/the-godev-corner/supercharge-your-go-application-releases-36c47894fc1f?source=rss-3162bd0b0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/36c47894fc1f</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Maina Wycliffe]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 20:22:29 GMT</pubDate>
            <atom:updated>2023-01-06T20:25:34.169Z</atom:updated>
            <content:encoded><![CDATA[<h4>Golang: How To Guide</h4><h3>Supercharge Your Go Application Builds and Releases</h3><h4>Learn to automate your Go builds and release pipelines for different target environments</h4><figure><img alt="golang gopher demonstrating the fact that you can supercharge releases with GoReleaser and GitHub Actions" src="https://cdn-images-1.medium.com/max/1024/1*HQjnm5gvU1TwMhA3-qoCrA.jpeg" /></figure><h3>Introduction</h3><p>Manually cross-compiling Go applications for different environments (i.e., operating systems, architectures, etc.) isn’t necessarily <em>hard</em>; the problem is, it can just get….“messy.” And fast.</p><p>In fact, a single mistake could mean publishing an incorrect version, or even the wrong program.</p><p>I’m probably preaching to the choir here, but the question remains — why do so many developers continue to do it the <em>hard way</em>? Why continue to create and maintain custom build scrips? Or continue double-(or triple-)checking your work while you can automate it?</p><p>If you haven’t heard about it, let me introduce <a href="https://goreleaser.com/"><strong>GoReleaser</strong></a>, <strong>an open-source tool that allows you to build, release and publish applications across all your intended target environments with a single command</strong>.</p><p>Combine that with <a href="https://github.com/features/actions"><strong>GitHub Actions</strong></a>, and now <strong>your releases can be automated too</strong>. Plus, you can build, test, and deploy your code right from GitHub.</p><p>All you need to do is ensure you have the <a href="https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_dispatch">correct event</a> and <a href="https://docs.github.com/en/actions/using-workflows/triggering-a-workflow">trigger</a>, which could be a Git push commit, tag, or click of a button.</p><blockquote><em>📌 Disclaimer</em>: GitHub Actions offers a Free version (up to 2000 minutes), which we will use here, and other <a href="https://github.com/features/actions#pricing-details">paid ones</a>. This is not an endorsement or sponsorship — I’m just trying to raise your awareness on helpful, available options at your disposal. You can replace GitHub actions with your CI tool of choice.</blockquote><p>This article will walk you through how to automate your builds using both GitHub Actions and GoReleaser. <strong>Specifically, we will use GoReleaser to help us manage the process of building an application (for multiple target environments), releasing it, and finally publishing it to GitHub Releases</strong>.</p><p><strong>❗️TL;DR</strong></p><blockquote>You can easily automate your builds with GoReleaser and GitHub Actions, and subsequently reduce having to manually cross compile your Go applications into different environments.</blockquote><blockquote>The process both reduces risk and increases your capacity for efficiency by allowing you to build, release, and publish, applications with a single click.</blockquote><blockquote>Both GoReleaser and GitHub Actions offer Free versions, which we’ll use here in this article. Follow along to see how.</blockquote><p>Let’s get started!</p><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Short Preface</h3><h4>Pre-requisites</h4><ul><li>Go: Moderate understanding</li><li>Git, GitHub, GitHub Releases, and GitHub Actions: Basic understanding</li></ul><h4>What you’ll learn</h4><ul><li><a href="#2f00">How GoReleaser ensures your Go app releases are predictable</a></li><li><a href="#6344">How to test that GoReleaser is setup correctly</a></li><li><a href="#ab8d">How to use GitHub Actions to automate Go Builds targeting all the required environments</a></li><li><a href="#8b86">How to use GoReleaser to configure build instructions for different target environments in Go</a></li><li><a href="#1a0a">How to use tags to create GitHub Releases using GoReleaser</a></li><li><a href="#3d78">How we can use GitHub Actions to automate these</a></li></ul><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>GoReleaser</h3><h4>What is it, and how can it help me?</h4><p>GoReleaser helps automate the process of releasing Go applications (i.e., building, releasing, and publishing). You can use it locally, however it’s mainly meant for CI environments where you can automate the deployment pipeline.</p><blockquote><em>💡 Big Idea:</em> GoReleaser aims to make all these scripts obsolete. Instead of writing scripts, you can write a simple YAML configuration file. And instead of many tools, you (usually) only need a single goreleaser binary.</blockquote><p>With GoReleaser, you can configure your publishing and releasing pipelines, then simply forget about them. This covers the whole process, including the building process, identifying where the artifacts are published, packaging, changelog generations, etc.</p><p>On top of that, it comes with sensible defaults for each step, meaning that unless you want to configure something different, you probably don’t need to do much.</p><p><strong>This makes the process of releasing your Go application across multiple environments very predictable and routine</strong>.</p><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Running GoReleaser Locally</h3><p>I know we mentioned that GoReleaser is mainly meant for CI environments, but before we can see it there— <a href="https://github.com/features/actions">GitHub Actions</a> in our case — let’s see how it works locally and move on from there.</p><h4>Installation</h4><p>First, we will need to install GoReleaser. The easiest way to do that is to use the <a href="https://github.com/NanXiao/golang-101-hacks/blob/master/posts/go-build-vs-go-install.md">go install</a> command:</p><pre>go install github.com/goreleaser/goreleaser@latest</pre><blockquote><em>📖 Further Reading:</em> There are several other ways you can install GoReleaser into your system, which you can find in the official docs <a href="https://goreleaser.com/install/">here</a>.</blockquote><h4>Configuring GoReleaser</h4><p>GoReleaser needs a .goreleaser.yaml file at the root of our project which will contain the necessary configuration to build and publish our application targeting different runtime environments (e.g., OS’s)</p><p>To get started, GoReleaser provides an initialization command that you can use to get things moving quickly. This is going to generate the .goreleaser.yaml file with sensible defaults:</p><pre>goreleaser init</pre><p>The generated .goreleaser.yaml file will look like this (excluding comments):</p><pre>before:<br>  hooks:<br>    - go mod tidy<br>    - go generate ./...<br>builds:<br>  - env:<br>      - CGO_ENABLED=0<br>    goos:<br>      - linux<br>      - windows<br>      - darwin<br>archives:<br>  - replacements:<br>      darwin: Darwin<br>      linux: Linux<br>      windows: Windows<br>      386: i386<br>      amd64: x86_64<br>checksum:<br>  name_template: &#39;checksums.txt&#39;<br>snapshot:<br>  name_template: &quot;{{ incpatch .Version }}-next&quot;<br>changelog:<br>  sort: asc<br>  filters:<br>    exclude:<br>      - &#39;^docs:&#39;<br>      - &#39;^test:&#39;</pre><p>As you can see from the above default config file, GoReleaser will cover a variety of areas:</p><p><strong>Hooks<br></strong><a href="https://goreleaser.com/customization/hooks/">Hooks</a> allow you to execute custom commands or scripts at various points in the release process, sometimes before a release is done. This is common when you want to set up things necessary for your build to succeed. Common hooks include:</p><ul><li>pre_build: Executed before building the binaries</li><li>post_build: Executed after building the binaries</li><li>pre_release: Executed before releasing the binaries</li><li>post_release: Executed after releasing the binaries</li></ul><p>When a hook fails, the release process will be aborted.</p><p><strong>Builds<br></strong>Builds allow you to configure how your Go applications will be built from the target binary via GOOS, GOARCH, and GOARM settings — which are standard in Go. They can help you compile source code, create package files (e.g., ZIP archives), generate documentation, and more.</p><p>With builds, you can tell GoReleaser to build your application for every platform supported by Go that you want to target.</p><blockquote><em>📖 Further Reading: </em>You can learn more about Builds <a href="https://goreleaser.com/customization/build/">here</a></blockquote><p><strong>Archives<br></strong>Archives help you to customize the archive name, additional files, and format as you see fit. They contain the binary files (and/or other elements) produced by the build process and allow you to conveniently package them to be further distributed and installed.</p><blockquote><em>📖 Further Reading: </em>You can learn more about Archives <a href="https://goreleaser.com/customization/archive/">here</a></blockquote><p><strong>Checksum<br></strong>With <a href="https://en.wikipedia.org/wiki/Checksum">Checksum</a>, we can customize the checksum details of our releases, and verify a file’s authenticity by comparing it to a known value. This allows users to verify whether the files they downloaded are correct, and have not been corrupted and/or modified during the release.</p><p><strong>Changelog<br></strong>Finally <a href="https://goreleaser.com/customization/changelog/">Changelog</a> helps you identify any new features, edits, and bug fixes inherent in each new release. You can even customize how it’s generated inside the release. Any commits starting with docs and tests are ignored by default, but you can tailor this to your needs.</p><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Releasing Application Locally</h3><p>Now that we have our GoReleaser setup, we can test whether it’s working by running the goreleaser release --snapshot command.</p><pre>goreleaser release --snapshot --rm-dist</pre><blockquote><em>💡 Big Idea:</em> The --rm-dist flag informs GoReleaser to delete the previous dist directory that was created by prior releases. The --snapshot flag allows us to release it locally based on the last commit, without a git tag.</blockquote><p>In your dist directory, you should be able to see all the binaries that were created in your directory. Here is an example of the default GoReleaser config output:</p><figure><img alt="Builds generated by GoReleaser from the default config" src="https://cdn-images-1.medium.com/max/804/1*NlsQyZpK7osSUDBOZfByJA.png" /><figcaption>Builds generated by GoReleaser from the default config</figcaption></figure><blockquote><em>👉 Note: </em>We generated Go executable binaries for our application for all major OSs with a single command</blockquote><p>As mentioned previously, you can customize your GoReleaser configs to build your Go application the way you see fit</p><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Distributing via GitHub Releases</h3><h4>Moving out of the local environment</h4><p>Ok, so we covered how to <em>run</em> releases locally. But unfortunately, we are not going to <em>distribute</em> our releases that way; instead, we’ll distribute them via GitHub Releases</p><blockquote><em>👉 Note: </em>GoReleaser also supports several release channels, including Docker, GitHub, and GitLab releases</blockquote><p>By default, GoReleaser will try and figure out as much information without you needing to specify it.</p><p>If you run the goreleaser release command inside a repository hosted on GitHub, the release created will be on GitHub Releases. The same applies to Gitlab and so on. Of course, you can customize this information by going to the official docs <a href="https://goreleaser.com/customization/release/">here</a> if you’d like.</p><h4>Creating a Git Tag and Token</h4><p>To create a release on GitHub, let’s start by creating a Git Tag in our repo and pushing it remotely:</p><pre>git tag -a v0.).1 -m &quot;Release message - could be anything&quot;<br>git push origin v0.1.1</pre><p>In our case above, we will tag it as v0.0.1 .</p><p>Next, we’ll need a token that GoReleaser will use to create a release with. You can create one <a href="https://github.com/settings/tokens/new">here</a>.</p><blockquote><em>❗️ Important: </em>Please ensure you keep the token secret and scope it correctly using the <a href="https://en.wikipedia.org/wiki/Principle_of_least_privilege">Principle of Least Privilege</a>.</blockquote><p>Once you have the token, set it as an environment variable — let’s call it GITHUB_TOKEN so GoReleaser can use it.</p><pre>export GITHUB_TOKEN=&quot;TOKEN HERE&quot;</pre><h4>Creating the release</h4><p>Next, let’s run thegoreleaser release command to create a release. We will also specify the --rm-dist directory to clear up the dist directory, as the release will fail if it’s empty.</p><pre>goreleaser release --rm-dist </pre><p>☝️ This will build our application, create a release in GitHub Releases and upload the binaries. It will also append a changelog for the release using the commits between the current and last tag.</p><p>As mentioned previously, you can customize the changelog generation behavior by referring to these docs <a href="https://goreleaser.com/customization/changelog/">here</a>.</p><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Running on GitHub Actions</h3><h4>Automating releases via version tags</h4><p>So far, we have been doing everything manually, which isn’t ideal. Our goal is to automate the process and reduce the likelihood of making future mistakes.</p><p>There are several available CI’s to work with, but one I particularly like is GitHub Actions. We’ll use it here to create a release every time a new version tag is created. This will allow us to release our Go application by just creating a tag and pushing it remotely.</p><p>Now, you can change this behavior by creating a release on commits for things such as releases, but that goes beyond the scope of this article.</p><p>So first, let’s run our workflow only when tags are pushed; we will use globs to ensure we target tags starting with v for version:</p><pre>on:<br>  push:<br>    tags:<br>      - &quot;v*&quot;</pre><blockquote><em>📖 Further Reading: </em>See <a href="https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows">here</a> for more on GitHub Actions triggers</blockquote><p>Next, let’s create a release job, which should probably run after linting, and testing jobs are done to ensure we’re not releasing anything that’s regressing.</p><p>Inside the release job, we’ll git checkout the repo and set up Go using <a href="https://github.com/marketplace/actions/setup-go-environment">actions/setup-go</a>:</p><pre>jobs:<br>  # the workflow can contain other jobs, such as linting, testing, etc.<br>  release:<br>    runs-on: ubuntu-latest<br>    steps:<br>      # run git checkout<br>      - name: Checkout<br>        uses: actions/checkout@v3<br>        with:<br>          fetch-depth: 0<br><br>      # setup go<br>      - name: Set up Go<br>        uses: actions/setup-go@v3<br>        with:<br>          go-version: 1.19.x</pre><h4>Releasing our Go app</h4><p>Lastly, let’s use the <a href="https://github.com/marketplace/actions/goreleaser-action">goreleaser/goreleaser-action</a> action to release our Go application. This should create a GitHub Release with all the build artifacts uploaded:</p><pre>jobs:<br>  # ...<br>  release:<br>    # ...<br>    steps:<br>      # ... other steps specified above<br><br>      # run goreleaser<br>      - name: Run GoReleaser<br>        uses: goreleaser/goreleaser-action@v4<br>        with:<br>          version: latest<br>          args: release --rm-dist<br>          distribution: goreleaser<br>        env:<br>          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}</pre><p>And that’s it for our GitHub Action! This is what our workflow should look like now:</p><pre>name: Release<br><br>on:<br>  push:<br>    tags:<br>      - &quot;v*&quot;<br>jobs:<br>  # the workflow can contain other jobs, such as linting, testing, etc.<br>  release:<br>    runs-on: ubuntu-latest<br>    steps:<br>      # run git checkout<br>      - name: Checkout<br>        uses: actions/checkout@v3<br>        with:<br>          fetch-depth: 0<br><br>      # setup go<br>      - name: Set up Go<br>        uses: actions/setup-go@v3<br>        with:<br>          go-version: 1.19.x<br><br>      # run goreleaser<br>      - name: Run GoReleaser<br>        uses: goreleaser/goreleaser-action@v4<br>        with:<br>          version: latest<br>          args: release --rm-dist<br>          distribution: goreleaser<br>        env:<br>          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}</pre><h4>Triggering the action</h4><p>Finally — one more thing. To trigger our GitHub Action, let’s create a new tag (beginning with v for version) and push it to our repo. That way, our Github action should run and create a release for the corresponding tag.</p><pre>git tag -a v0.1.3 -m &quot;Release notes&quot;<br>git push origin v0.0.3</pre><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Conclusion</h3><p>In this post, we looked into how we can improve the process of releasing Go applications using GoReleaser, making the process less painful and less of a hustle. We also learned how to use GitHub Actions to automate the release process whenever a new tag is pushed to the remote repository.</p><h4>Main Takeaways</h4><ul><li>GoReleaser is a tool that helps automate the process of releasing Go applications by building, releasing, and publishing them.</li><li>It can also help with other aspects of the process, such as generating changelogs and publishing them to GitHub Releases</li><li>It is configured using a YAML file, and comes with default settings for each step of the release process</li><li>GoReleaser is mainly intended for use in CI environments, but can also be used locally. To use GoReleaser locally, it must be installed and a configuration file must be created. The goreleaser release --snapshot command can then be used to test the release process</li><li>GitHub actions and Git Tags can help you automate your Go app releases by reducing the likelihood of errors when running multiple commands in sequence. You can also create a tag and push it remotely to release the application</li></ul><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Other Articles You Might Be Interested In</h3><ul><li><a href="https://medium.com/the-godev-corner/expand-web-app-development-with-go-fc07d55b41f6">Build Powerful Client-Side Web Apps Using Go</a></li><li><a href="https://medium.com/the-godev-corner/simplify-your-configurations-in-go-b7747c45ebf7">Simplify Your Configurations in Go</a></li></ul><p><em>Disclosure: In accordance with Medium.com’s rules and guidelines, I publicly acknowledge financial compensation from </em><a href="http://www.unidoc.io/"><em>UniDoc</em></a><em> for this article. All thoughts, opinions, code, pictures, writing, etc. are my own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36c47894fc1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-godev-corner/supercharge-your-go-application-releases-36c47894fc1f">Supercharge Your Go Application Builds &amp; Releases</a> was originally published in <a href="https://medium.com/the-godev-corner">The GoDev Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Powerful Client-Side Web Apps Using Go]]></title>
            <link>https://medium.com/the-godev-corner/expand-web-app-development-with-go-fc07d55b41f6?source=rss-3162bd0b0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc07d55b41f6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Maina Wycliffe]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 17:43:51 GMT</pubDate>
            <atom:updated>2023-01-05T04:36:44.088Z</atom:updated>
            <content:encoded><![CDATA[<h4>Golang: How To Guide</h4><h4>Learn how to write and run Go code for a web browser with Web Assembly (WASM), and minimize the size of client-side code using TinyGo</h4><figure><img alt="Picture of the Golang gopher on a raft with a chalkboard saying “Using Go with WASM: What You Need To Know”" src="https://cdn-images-1.medium.com/max/1024/1*Q6qAYiJjltD0tZcG88t9gQ.jpeg" /></figure><p>From the beginning, web browsers have always been strict on what languages they support (i.e., HTML, CSS, and Javascript), naturally limiting the ability to build apps targeting web browsers.</p><p>But even though Javascript has evolved quite admirably into a modern general-purpose language (see <a href="https://nodejs.org/en/">NodeJS</a> and <a href="https://deno.land/">Deno</a>), it still has inherent weaknesses, <strong>ultimately restricting its ability to create web apps that are powerful and performant</strong>.</p><p>Subsequently, the <a href="https://webassembly.org/">Web Assembly</a> standard (WASM) by <a href="https://tc39.es/">TC39</a> was created a few years ago, allowing developers to compile code from any programming language (such as Go) to run in the web browser.</p><p><strong>WASM burst the doors wide open for the number of languages supported by web browsers.</strong> With it, you can now write applications that run in near-native performance, creating web apps that are both powerful and performant.</p><blockquote><em>👉</em> <em>Note</em>: Web Assembly is a binary instruction format for a stack-based virtual machine. It was designed as a portable compilation target for programming languages, enabling deployment on the web for client and server applications.</blockquote><p>Currently, it is supported by all the major browsers — Chromium-based browsers (Chrome, Edge, Brave, etc.), Mozilla, and Safari.</p><p>The number of possibilities to create web apps in the browser suddenly became exponential, and languages like Rust, Python, and Blazor all shared in massive usage increases, especially over the last year. (<a href="https://blog.scottlogic.com/2022/06/20/state-of-wasm-2022.html">Source</a>)</p><p><strong>But there’s also another language climbing the chart in popularity — Go.</strong></p><p>So in this article, we’ll run through how to write Go code that optimally runs in the browser using WASM and give a little insight into how best to approach it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSJKIH-FZn6_1ju3SGGcMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfValGG4-oUfVaCBAOAiCw.png" /><figcaption><a href="https://blog.scottlogic.com/2022/06/20/state-of-wasm-2022.html">Survey Question</a>s: (Left) Which language do you <strong>currently use</strong> for WebAssembly development?; (Right) Which language do you most <strong>want to use</strong> for WebAssembly development? (n=299)</figcaption></figure><p><strong>❗️TL;DR</strong></p><blockquote>Web Assembly (WASM) can be used to build web apps that are powerful and performant as they run at near native speed. This opens up the door for powerful web apps such as video and photo editors to run on the web browser similar to their native counterparts.</blockquote><blockquote>Now, you can write those same applications in Go with the help of WASM, helping you prioritize the requirements for web app success and future growth. This article walks you through the process of using Go with WASM.</blockquote><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Short Preface</h3><h4>What you’ll learn</h4><ul><li><a href="#ec94">How to cross-compile Go applications in Web Assembly (WASM) to run in the web browser</a></li><li><a href="#66ef">How to expose Go functions and call them from the browser using Javascript, ensuring that your code is fully interactive with the browser</a></li><li><a href="#f9d4">How to use TinyGo to reduce the WASM compiled size so it’s more compact</a></li></ul><h4>Requirements</h4><ul><li><a href="https://tinygo.org/getting-started/install/">Download TinyGo</a> if you’d like to follow along. Otherwise, we’ll walk through everything.</li></ul><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Getting Started</h3><h4>Cross-compiling the WASM/Go application</h4><p>Let’s start by creating a simple Go application that just prints &quot;Hello World from Go” with WASM in the browser console:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3734a3bbfe926a954cf18655d5ebe2a0/href">https://medium.com/media/3734a3bbfe926a954cf18655d5ebe2a0/href</a></iframe><blockquote><em>👉</em> <em>Note</em>: Feel free to test this by running go run main.go in your terminal</blockquote><p>To actually run this in the browser, though, we need to do a few things. First, we need some Javascript glue code that will import the web assembly binary into our browser to then execute it.</p><p>To do so, we can copy the code below from our Go installation, as it comes standard in the misc/wasm/wasm_exec.js directory inside GOROOT (the location of the Go SDK).</p><p>Let’s copy it into a directory called “public” in our project directory:</p><pre>cp &quot;$(go env GOROOT)/misc/wasm/wasm_exec.js&quot; ./public/</pre><blockquote><em>👉</em> <em>Note</em>: To see what the Javascript glue code we copied looks like, click <a href="https://github.com/mainawycliffe/go-wasm/blob/main/public/wasm_exec.js">here</a>.</blockquote><p>Then, we will need to cross-compile our WASM/Go application by setting the environment variables GOOS to js , and GOARCH to WASM. This allows us to compile our Go application for WASM to run within the WASM environment.</p><p>Now let’s save our WASM binary in the same public directory we saved our JS glue code, naming it wasm.wasm.</p><pre>GOOS=js GOARCH=wasm go build -o public/wasm.wasm</pre><p>Lastly, we need to create an index.html file for our server. Inside it, we need to load the Javascript glue code we copied from GOROOT and then load out the cross-compiled WASM file. Then can we execute it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4933579c9e9ee9f10304a42580dd969d/href">https://medium.com/media/4933579c9e9ee9f10304a42580dd969d/href</a></iframe><blockquote><em>👉</em> <em>Note</em>: The important part is the <strong>second script</strong>, which is going to fetch our WASM binary and then execute it by calling the go.run function. That will subsequently fire up the go.main function.</blockquote><p>Once you do this, you should seeHello World from Go (from our Go code earlier) written into the browser console.</p><h4>Creating and running a Go web server</h4><p>Next, we need a web server to serve our web app so that we can view the results in the browser. There are several ways we can do this, but the most straightforward way is to create a Go web server that serves our public directory. We will place the code for the server in the servers directory within our project directory.</p><p>Here’s what that looks like:</p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;net/http&quot;<br>)<br><br>func main() {<br> fs := http.FileServer(http.Dir(&quot;../public&quot;))<br> http.Handle(&quot;/&quot;, fs)<br><br> log.Print(&quot;Listening on :3000...&quot;)<br> err := http.ListenAndServe(&quot;:3000&quot;, nil)<br> if err != nil {<br>  log.Fatal(err)<br> }<br>}</pre><p>And then, we can run the Go web server by using the go run server/main.go command and then visit the URL <a href="http://localhost:3000/">http://localhost:3000</a> to view the results.</p><p>If you open the browser console, you should see our “Hello World From Go” message printed there:</p><figure><img alt="Picture of an output reading “Hello world from Go”" src="https://cdn-images-1.medium.com/max/1016/1*VZ5ycwqhq8hzxY2aSigFMw.png" /></figure><p>Congratulations! Now you’ve created a Go application that runs in the browser.</p><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Calling Go Functions From Our Browser</h3><h4>Example: Setting up a simple calculator</h4><p>Now that we’ve created a simple application let’s execute some Go functions and use Go to perform some functionality in our browser.</p><p>To demonstrate, we can start by creating a simple calculator, for example, that can help us square and cube a number. The functions to do so will be written in Go.</p><p>Here is what the UI looks like:</p><figure><img alt="UI for the example calculator we created as a Go application" src="https://cdn-images-1.medium.com/max/513/1*HUmm_LPaXLz7dyN5FChghg.png" /></figure><p>From our browser, we’ll be able to call the functions and execute the code, just like any other JS code and browser APIs.</p><p>Here’s what our functions should look like:</p><pre>func calculateSquare(x int) int {<br> return x * x<br>}<br><br>func calculateCube(x int) int {<br> return x * x * x<br>}</pre><p>Next, we can expose our functions to Javascript so they are callable using the <a href="https://pkg.go.dev/syscall/js">syscall/js</a> package. This will give our Go application access to the WASM host environment, which in our case, is the browser.</p><h4>Using js.Func</h4><p>Now we need to create a new function that returns js.Func, a wrapped Go function to be called by JavaScript. That will then return js.FuncOf, which will accept a callback function as an argument.</p><p>The callback will receive the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">Javascript</a> “<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">this” object</a> as the first argument, then any function arguments when the function itself is called as an array.</p><p>So, for example, if we called calculateSquare(5), the second parameter will contain an array with “5” as the first index.</p><p>Inside the callback function, let’s define the number as an integer and call calculateSquare:</p><pre><br>func calculateSquareWrapper() js.Func {<br> return js.FuncOf(func(this js.Value, args []js.Value) any {<br>  if len(args) != 1 {<br>   return &quot;Invalid no of arguments passed&quot;<br>  }<br>  x := args[0].Int()<br>  return calculateSquare(x)<br> })<br>}</pre><p>Then, let’s do the same for the calculateCube function:</p><pre>func calculateCubeWrapper() js.Func {<br> return js.FuncOf(func(this js.Value, args []js.Value) any {<br>  if len(args) != 1 {<br>   return &quot;Invalid no of arguments passed&quot;<br>  }<br>  x := args[0].Int()<br>  return calculateCube(x)<br> })<br>}</pre><blockquote><em>❗️</em> <em>Remember:</em> Double-check that the callback function is called with the correct number of arguments</blockquote><p><strong>This will wrap up our Go functions so they’re callable by Javascript, but we still need to expose them to our browser.</strong></p><p>To do so, add both functions to the <a href="https://developer.mozilla.org/en-US/docs/Glossary/Global_object#:~:text=A%20global%20object%20is%20an,members%20of%20the%20global%20object.">Javascript “global” object</a> using the js.Global().Set()function, which accepts two arguments: (1) the name of the function; and (2) the function to be called. Here’s what that looks like:</p><pre>func main() {<br> js.Global().Set(&quot;calculateCube&quot;, calculateCubeWrapper())<br> js.Global().Set(&quot;calculateSquare&quot;, calculateSquareWrapper())<br>}</pre><p>Now let’s open a channel to <em>block our Go application from exiting</em>, as we need to ensure our functions from Javascript are called <strong><em>first</em></strong>.</p><pre>func main() {<br> js.Global().Set(&quot;calculateCube&quot;, calculateCubeWrapper())<br> js.Global().Set(&quot;calculateSquare&quot;, calculateSquareWrapper())<br><br> // make sure the program doesn&#39;t exit<br> &lt;-make(chan bool)<br>}</pre><p>Lastly, cross-compile the Go application targeting WASM. Here, we’ll save the WASM binaries in the public directory and name it calculator.wasm:</p><pre>GOOS=js GOARCH=wasm go build -o public/calculator.wasm ./wasm/main.go</pre><h4>Implementing the UI</h4><p>The next step here is to modify our index.html. <strong>We want to add both the form and the function necessary for the calculations.</strong></p><p>Let’s keep it simple — a single input and two buttons should do:</p><pre>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;script src=&quot;wasm_exec.js&quot;&gt;&lt;/script&gt;<br>    &lt;script&gt;<br>      const go = new Go();<br>      &lt;!-- please note the wasm file name is calculator.wasm --&gt;<br>      WebAssembly.instantiateStreaming(fetch(&#39;calculator.wasm&#39;), go.importObject).then((result) =&gt; {<br>        go.run(result.instance);<br>      });<br>    &lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Calculator&lt;/h1&gt;<br>    &lt;input type=&quot;text&quot; id=&quot;input&quot; /&gt;<br>    &lt;button id=&quot;calculateSquare&quot;&gt;Calculate Square&lt;/button&gt;<br>    &lt;button id=&quot;calculateCube&quot;&gt;Calculate Cube&lt;/button&gt;<br>  &lt;/body&gt;<br><br>&lt;/html&gt;</pre><p>Then, let’s attach “event listeners” to our two buttons above ☝️. This will call the Go functions whenever the buttons are clicked.</p><p>For instance, to calculate the square of the input, attach the “event listener” to the calculateSquarebutton, read the input value, and then call the calculateSquare function passing the input to it.</p><blockquote><em>❗️</em> <em>Remember:</em> Make sure the data type passed to the Go application is correct, as the Go application will panic if the type do not match the expected type.</blockquote><pre>&lt;script&gt;<br>  document.getElementById(&#39;calculateSquare&#39;).addEventListener(&#39;click&#39;, () =&gt; {<br>    console.log(&#39;Hello from JS&#39;);<br>    const input = parseInt(document.getElementById(&#39;input&#39;).value);<br>    const result = calculateSquare(input);<br>    alert(`Square of ${input} is ${result}`);<br>  });<br><br>&lt;/script&gt;</pre><p>Rinse and repeat for calculating the cube of the input:</p><pre>&lt;script&gt;<br>  // ... <br><br>  document.getElementById(&#39;calculateCube&#39;).addEventListener(&#39;click&#39;, () =&gt; {<br>    console.log(&#39;Hello from JS&#39;);<br>    const input = parseInt(document.getElementById(&#39;input&#39;).value);<br>    // this is where the go code is called<br>    const result = calculateCube(input);<br>    alert(`Cube of ${input} is ${result}`);<br>  });<br>&lt;/script&gt;</pre><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Reducing our WASM Final Bundle Size using TinyGo</h3><p>So far, we have managed to get WASM working as expected using Go’s built-in tools. <em>However, there is a downside…</em></p><p>The emitted WASM code of our small calculator app above is very huge — over 2 MBs, as shown below:</p><figure><img alt="Original code input into TinyGo which turned out to be over 2MBs" src="https://cdn-images-1.medium.com/max/957/1*kSqATU53GXDIX2lc0dCqJA.png" /><figcaption>Original code over 2MB</figcaption></figure><p>Fortunately, there’s an easy solution — <a href="https://tinygo.org/">TinyGo</a>, a Go compiler. <strong>With it, we can likely reduce the final build size by over 70% (shown below) without changing a single line of code:</strong></p><figure><img alt="Updated code using TinyGo" src="https://cdn-images-1.medium.com/max/934/1*U9VoY1YPNnuHRKygZQm-Ow.png" /><figcaption>Updated code using TinyGo</figcaption></figure><p>Let’s see how it works…</p><p>[To follow along, you can install TinyGo on your computer using the instructions <a href="https://tinygo.org/getting-started/install/">here</a>.]</p><blockquote><em>👉</em> <em>Note:</em> TinyGo can also produce <a href="https://webassembly.org/">WebAssembly (WASM)</a> code which is very compact in size. You can compile programs for web browsers, as well as for server and edge computing environments that support the <a href="https://github.com/WebAssembly/WASI">WebAssembly System Interface (WASI)</a> family of interfaces.</blockquote><h4>Using TinyGo</h4><p>Let’s use the TinyGo version of the glue code instead of the Go code we are using.</p><blockquote><em>💡</em> <em>Big Idea: </em>Since the emitted WASM code of our app will be completely different from the version emitted when using the Go compiler, it only makes sense that we need a different mechanism to load and run our compiled WASM code.</blockquote><p>To get started, head to /targets/wasm_exec.js inside the TINYROOT directory. We want to copy our JS glue code to the same directory we copied our Go glue code (public/wasm_exec.js), and overwrite what’s there:</p><pre>cp $(tinygo env TINYGOROOT)/targets/wasm_exec.js public/wasm_exec.js</pre><p>Now it’s time to use TinyGo — we’ll target WASM, and save the output in the same public directory as we did before with the Go compiler.</p><p>To do so, use the tinygo build command, as shown below:</p><pre>tinygo build -o public/calculator.wasm -target wasm ./wasm/main.go</pre><blockquote><em>📖 Further Reading: </em>You can read more about using the tinygo build command <a href="https://tinygo.org/docs/reference/usage/important-options/">here</a></blockquote><p>And that’s it!</p><p><strong>We can now run the Go server we had created earlier using the </strong>go run server/main.go<strong> command and then visiting the URL </strong><a href="http://localhost:300/">http://localhost:300</a>0<strong> to view the results; no other changes are needed.</strong></p><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Conclusion</h3><p>In this article, we learned what Web Assembly is and, in the big picture, why it matters for writing applications for the web browser.</p><p>We learned how to cross-compile Go applications and run Go code in WASM. Then we ensured our code was fully interactive with the browser by exposing the relative Go functions and calling them using Javascript.</p><p>Finally, we used TinyGo to reduce the WASM build size by over 70%, allowing for enhanced speed and performance.</p><h4>Key Takeaways</h4><ul><li>Web Assembly (WASM) allows you to write web apps that are powerful and performant, opening the door for the kind of apps that can be built for the Web.</li><li>With WASM, you can write high-performance applications in Go and run them in the browser, reducing the number of resources used and adding the necessary speed, scalability, and security for future growth</li><li>Along with Rust, Python, and Blazor, Go is one of the most sought-after languages to use for Web Assembly development</li></ul><h4>Source Code</h4><p>You can find the project where all the code snippets from above came from <a href="https://github.com/mainawycliffe/go-wasm">here</a>.</p><figure><img alt="The GoDev Corner unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Other Articles To Consider</h3><ul><li><a href="https://medium.com/the-godev-corner/simplify-your-configurations-in-go-b7747c45ebf7">Simplify Your Configurations in Go</a></li><li><a href="https://medium.com/the-godev-corner/manage-configurations-from-local-sources-in-go-4e55146c37c2">Manage Configurations From Local Sources in Go</a></li><li><a href="https://medium.com/the-godev-corner/how-to-create-a-go-private-module-with-docker-b705e4d195c4">How To Create a Go Private Module With Docker</a></li></ul><p><em>Disclosure: In accordance with Medium.com’s rules and guidelines, I publicly acknowledge financial compensation from </em><a href="http://www.unidoc.io/"><em>UniDoc</em></a><em> for this article. All thoughts, opinions, code, pictures, writing, etc. are my own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc07d55b41f6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-godev-corner/expand-web-app-development-with-go-fc07d55b41f6">Build Powerful Client-Side Web Apps Using Go</a> was originally published in <a href="https://medium.com/the-godev-corner">The GoDev Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify Your Configurations in Go]]></title>
            <link>https://medium.com/the-godev-corner/simplify-your-configurations-in-go-b7747c45ebf7?source=rss-3162bd0b0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7747c45ebf7</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Maina Wycliffe]]></dc:creator>
            <pubDate>Wed, 09 Nov 2022 22:44:30 GMT</pubDate>
            <atom:updated>2022-11-10T20:17:13.897Z</atom:updated>
            <content:encoded><![CDATA[<h4>GOLANG: HOW TO GUIDE</h4><h3>Simplify Your App Configurations in Go</h3><h4>Easily read, write, and manage your app configurations from remote sources using Viper (Go open-source)</h4><figure><img alt="Picture of the Golang gopher coming over with a Viper to investigate how to manage configurations from remote stores in Go using Viper" src="https://cdn-images-1.medium.com/max/1024/1*vrTrFCbflt1Qpqv37DZhdQ.png" /><figcaption>Gopher art credit to <a href="https://medium.com/u/c01f387bc9f4?source=post_page-----4e55146c37c2--------------------------------">Egon Elbre</a> at <a href="http://www.github.com/egonelbre/gophers">www.github.com/egonelbre/gophers</a></figcaption></figure><h3>Introduction</h3><p>Manually copying configurations across different computer systems is a <em>needless risk.</em></p><p>Think about it — how many times has a colleague created a program that required a config but didn’t post it anywhere? Or had something configured differently in different places?</p><p>Or forgot to update a system along the way?</p><p><strong>Personally, if I can pull up a configuration and see it myself without asking another developer, that’s a big win and saves me time.</strong></p><p>Centralizing how your applications can read all their configurations simultaneously is huge, especially when all you have to do is update the configurations <em>once</em>, and boom! You’re done.</p><p>Distributed processing, team collaboration and visibility, and accessibility improve almost overnight.</p><p>Remote stores, such as databases or specialized config services (e.g., <a href="https://www.consul.io/">Consul</a>; <a href="https://etcd.io/">etcd</a>) can help with that, but the configs inside them still need to be fetched and made available to our application for use.</p><p>Instead, let me introduce <a href="https://github.com/spf13/viper"><strong>Viper</strong></a><strong> —</strong> <strong>an open-source tool that can help you easily manage your Go application&#39;s configuration from different sources</strong>. It’ll help save you time, money, and future headaches.</p><p><a href="https://github.com/spf13/viper">GitHub - spf13/viper: Go configuration with fangs</a></p><p><strong>❗️TL;DR:</strong></p><blockquote>Viper is an open-source configuration management library for Go that allows you to consume configurations from different sources and use them within your application(s) in a standard way.</blockquote><blockquote>Regardless of your configuration source, Viper simplifies your application’s configurations, ensuring the latest ones are used as soon as any changes are made.</blockquote><blockquote>If you have a large Go application, or distributed Go applications where consistency is required, Viper becomes a breeze. It decouples your application(s) from its configurations, allowing you to conveniently scale.</blockquote><figure><img alt="The GoDev Corner’s unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Short Preface</h3><h4>What you’ll learn</h4><p>By the end of this article, you should be able to:</p><ul><li>Read and access configs from remote sources, and use them within your Go application</li><li>Feed them to Viper so that all your configurations are standardized, accessed, and managed in a central location</li><li>Watch config changes from a remote source and provide the latest configs to your application as soon as the changes are made</li></ul><h4>Prerequisites</h4><p>To follow along, you’ll likely need:</p><ul><li>A moderate understanding of Go</li><li>Familiarity with Firebase and Cloud Firestore (<em>recommended</em>)</li></ul><blockquote><em>📌 Disclaimer: </em>This is the second of two articles. In the previous article, we focused on Viper’s features and how to use them to manage configs from local sources (and environment variables). To read more, see the article below:</blockquote><p><a href="https://medium.com/the-godev-corner/manage-configurations-from-local-sources-in-go-4e55146c37c2">Manage Configurations From Local Sources in Go</a></p><figure><img alt="The GoDev Corner’s unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Getting Started</h3><h4>Reading remote key-value stores using Viper</h4><p>The good news is, Viper provides us with tools to read configurations from remote stores, such as <a href="https://firebase.google.com/docs/firestore">Cloud Firestore</a>, <a href="https://www.consul.io/">Consul</a>, <a href="https://etcd.io/">etcd</a>, etc. These are baked into Viper and take just a few lines to set up.</p><blockquote><em>📖 Further Reading:</em> You can learn more <a href="https://github.com/spf13/viper#remote-keyvalue-store-support">here</a> or through the code below<em>👇</em></blockquote><pre>viper.AddRemoteProvider(&quot;firestore&quot;, &quot;google-cloud-project-id&quot;, &quot;collection/document&quot;)<br>viper.SetConfigType(&quot;json&quot;)<br>err := viper.ReadRemoteConfig()</pre><p>However, while the inherent support for remote stores is great, it can also be inflexible at times, especially when you want to store configurations in your preferred store. A good example of this is Firestore support (see <a href="https://github.com/spf13/viper/issues/862">here</a> for example).</p><blockquote><em>💡 Expert Advice:</em> Just be cognizant of Viper’s possible limitations moving forward, that’s all. It’s not perfect, but if used correctly and in the right circumstances, it can truly be an asset.</blockquote><h4>Reading configs from non-predefined sources</h4><p>Viper’s baked-in tools are great, but I want to focus on reading configurations from any remote store we wish. [That’s going to be more helpful, right?]</p><p>To do so, we’ll first build our own version of reading configuration sources from Cloud Firestore. Then, we’ll watch changes to our configuration and update our application config whenever these changes happen.</p><p>To start, we’ll use the viper.ReadConfigs method provided by Viper, which will allow us to feed it with any data we want.</p><p>viper.ReadConfigs accepts io.Reader, and the data that we pass to it can come from any source we want. It just needs to be in a format that Viper can understand (i.e., JSON, YAML, etc.):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dbacdfa3688b8e68ba8edf05d3a9c35/href">https://medium.com/media/8dbacdfa3688b8e68ba8edf05d3a9c35/href</a></iframe><p>We also need to tell Viper <em>the format</em> we are using. We’ll do this through the viper.SetConfigType method, in our case, above JSON ☝️.</p><h4>Installing dependencies and getting the required credentials</h4><p>To read configurations from Cloud Firestore, we’ll start by installing the Firebase package for Go and Viper, using go get:</p><pre>go get firebase.google.com/go<br>go get github.com/spf13/viper</pre><p>Next, we’ll need credentials to authorize our Go application to access Firebase Cloud Firestore. We’ll use service accounts to authenticate our Go applications against Firebase, allowing us to query our Cloud Firestore database.</p><blockquote><em>📖 Further Reading:</em> Learn more here about Firebase Service accounts <a href="https://firebase.google.com/support/guides/service-accounts">here</a></blockquote><p>We’ll also save the credential file we get from Firebase/Google Cloud Platform within our file system; please take note of the path, as we will need it in the next step.</p><blockquote><em>👉 Note:</em> (1) Do not commit the credentials file you are going to get from Firebase; (2) The service account allows you to access all Firebase services and if you are running this in production, it’s best practice to only allow your credentials to access the necessary services. You can learn more about how to manage credentials on both Firebase and Google Platform <a href="https://cloud.google.com/docs/authentication/client-libraries">here</a>.</blockquote><p>If you are using another remote store or specialized config service, follow the relevant, official guidelines on acquiring the credentials for the specific system (and how to use them).</p><figure><img alt="The GoDev Corner’s unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Managing Configurations From Cloud Firestore</h3><h4>Reading configurations from Cloud Firestore</h4><p>Next, we will need to create a Firestore client that we can use to fetch and watch changes in our Firestore Document.</p><p>This is also the place where we need our credentials file by using the option.WithCredentialsFile() method, passing the path to the credential file as the argument. Then we need to pass the resulting variable to the firebase.NewApp() method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bd3a1135e9046b2efd160150e3e5ecf/href">https://medium.com/media/9bd3a1135e9046b2efd160150e3e5ecf/href</a></iframe><p>Next, since we now have a client, we can go ahead and read the configuration document from Cloud Firestore, as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eefc562c90d9ad8aa8d34af624c5f4f8/href">https://medium.com/media/eefc562c90d9ad8aa8d34af624c5f4f8/href</a></iframe><p>Cloud Firestore is a NoSQL database that is document-oriented. All documents are part of a collection (similar to tables).</p><p>To access a document, you need to know the collection it&#39;s in and the id of the document.</p><blockquote><em>📖 Further Reading:</em> For more information about the structure of Cloud Firestore, please check the official documentation <a href="https://firebase.google.com/docs/firestore/data-model#:~:text=Cloud%20Firestore%20is%20a%20NoSQL,set%20of%20key%2Dvalue%20pairs.">here</a></blockquote><p>In our case above, we are accessing a collection named configs and a document with id config.</p><p>This will allow us to have multiple configs for different applications or users, for instance, if we offer our users the ability to save their app configs remotely and sync across multiple systems.</p><p>When we read the data, we are converting the resulting map data to JSON so that we can pass it to Viper using by using the ReadConfig method. ReadConfig accepts an io.Reader, which is what enables us to pass configs from any source to Viper:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2098481443c6f3e88b0ffd1762bf5f71/href">https://medium.com/media/2098481443c6f3e88b0ffd1762bf5f71/href</a></iframe><p>At this point, we can read our configurations from Cloud Firestore, just like any other configuration, as if it came from any other source using Viper:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40a33e3ddb16a785a937952546b1f874/href">https://medium.com/media/40a33e3ddb16a785a937952546b1f874/href</a></iframe><h4>Watching config changes from Cloud Firestore</h4><p>To recap so far, we can read configs stored in Firestore, but if they changed, <em>we would need to restart our application</em> in order for it to get the latest changes.</p><p>It would be great if config changes were automatically detected and updated within our application so we could use them as soon as possible.</p><p>Fortunately for us, with Cloud Firestore, we can listen to changes automatically in either a collection or a specific document using the Snapshots method.</p><blockquote><em>👉 Note:</em> Snapshots returns a new snapshot whenever there are changes with the latest snapshot of the data</blockquote><p>We will use this method to listen to changes within our config document and use the viper.ReadConfigs to update configs in our application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7490f0e12e9847e00759edd37e0a872/href">https://medium.com/media/d7490f0e12e9847e00759edd37e0a872/href</a></iframe><blockquote>What if my config source doesn&#39;t have this capability?</blockquote><p>In that case, you could opt for a “polling solution,” where you would check in at reasonable intervals to see if configurations have changed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe0f455a8b02aa80b680b012cc089e6d/href">https://medium.com/media/fe0f455a8b02aa80b680b012cc089e6d/href</a></iframe><p>And that&#39;s it; any changes on our Cloud Firestore config document will be automatically reflected within our application. Here is what our code should look like now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6688c21b1adc032791fa7a853fbe99de/href">https://medium.com/media/6688c21b1adc032791fa7a853fbe99de/href</a></iframe><figure><img alt="The GoDev Corner’s unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Using Our Configuration within our Application</h3><p>Let’s set up Viper for our application and use the above configuration. We’ll need to tell Viper that our configuration file format is JSON since we are marshaling our data from Cloud Firestore to JSON.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71f1bc4e1cd1ae1a70bdd29c0f59be67/href">https://medium.com/media/71f1bc4e1cd1ae1a70bdd29c0f59be67/href</a></iframe><blockquote><em>👉 Note: </em>We are running our function to fetch the remote configs inside a Go routine to enable us to listen to updates from Cloud Firestore asynchronously and update viper configs automatically without blocking the main thread</blockquote><p>…and we’re done!</p><p>Questions? Comments? Feel free to leave them below👇 and let me know what you think.</p><figure><img alt="The GoDev Corner’s unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Conclusion</h3><p>In short, we learned how to use Cloud Firestore as a source for our configurations, plus how we can query Cloud Firestore, read the data and pass it to Viper to use it within our application.</p><p>On top of that, we also learned how to watch the configuration changes in Firestore and update Viper so that they are made available within our application as soon as that happens.</p><h4>Key Takeaways</h4><ul><li>Viper provides us with baked-in tools to read configurations from remote stores, such as <a href="https://firebase.google.com/docs/firestore">Cloud Firestore</a>, <a href="https://www.consul.io/">Consul</a>, <a href="https://etcd.io/">etcd</a>, etc., which can be set up pretty quickly</li><li>If you want to read configurations from a remote store, you’ll likely need to build your own version of reading configuration sources. Then, watch for configuration changes and update accordingly</li><li>To do so, use viper.ReadConfigs to feed configurations to Viper from sources that Viper doesn&#39;t provide direct support for</li><li>We can listen to changes within Cloud Firestore automatically in either a collection or a specific document using the Snapshots method and pass the changes to Viper.</li><li>Lastly, don’t forget to set the format for your configs appropriately. It can drive you nuts if you miss this.</li></ul><figure><img alt="The GoDev Corner’s unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Other Articles To Consider</h3><ul><li><a href="https://medium.com/the-godev-corner/manage-configurations-from-local-sources-in-go-4e55146c37c2">Manage Configurations From Local Sources in Go</a></li><li><a href="https://medium.com/the-godev-corner/how-to-run-go-integration-tests-for-third-party-services-using-docker-b8104a943c4">How To Run Go Integration Tests for Third-party Services Using Docker</a></li></ul><p><em>Disclosure: In accordance with Medium.com’s rules and guidelines, I publicly acknowledge financial compensation from </em><a href="http://www.unidoc.io/"><em>UniDoc</em></a><em> for this article. All thoughts, opinions, code, pictures, writing, etc. are my own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7747c45ebf7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-godev-corner/simplify-your-configurations-in-go-b7747c45ebf7">Simplify Your Configurations in Go</a> was originally published in <a href="https://medium.com/the-godev-corner">The GoDev Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage Configurations From Local Sources in Go]]></title>
            <link>https://medium.com/the-godev-corner/manage-configurations-from-local-sources-in-go-4e55146c37c2?source=rss-3162bd0b0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e55146c37c2</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Maina Wycliffe]]></dc:creator>
            <pubDate>Thu, 27 Oct 2022 21:51:34 GMT</pubDate>
            <atom:updated>2022-10-27T21:51:34.846Z</atom:updated>
            <content:encoded><![CDATA[<h4>Golang: How To Guide</h4><h4>Follow along as we use Viper, an open-source Go library, to find configuration files across multiple sources and read them into our applications</h4><figure><img alt="Picture of a Golang gopher and a viper next to a sign that says “manage configs from local sources with Viper”" src="https://cdn-images-1.medium.com/max/1024/1*WukQmKAl9JjEhCK5FI-x_w.png" /><figcaption>Gopher art credit to <a href="https://medium.com/u/c01f387bc9f4">Egon Elbre</a> at <a href="http://www.github.com/egonelbre/gophers">www.github.com/egonelbre/gophers</a></figcaption></figure><h3>Introduction</h3><p>Let’s be honest — providing configurations for your applications can be challenging and can easily turn into a <em>mess</em> if not done properly. Errors in production. Data loss. Bugs that you can’t fix in time.</p><p>Sooner or later you’re working overtime with a project backlog the size of El Capitan, wondering if you’re going to get 4 hours of sleep.</p><p>Ok, well maybe not that drastic. But you know what I mean</p><p>I mean we’ve all been there where everything works perfectly on our machine but not on the client system. That’s a huge PITA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*J9Q29VPpQQacMVRBLxQZOw.jpeg" /></figure><p>The truth is, if you don’t have a solid plan to manage configs, everything may start running away from you as you get closer to shipping the application.</p><p>Enter <a href="https://github.com/spf13/viper"><strong>Viper</strong></a>, an open-source Go configuration management library that makes it easy to manage and streamline application configurations.</p><p><strong>Viper allows you to consume different configuration sources</strong> — files, environment variables, remote sources (e.g., <a href="https://etcd.io/">etcd</a> or <a href="https://www.consul.io/">Consul</a>), or even databases, such as <a href="https://www.mongodb.com/">MongoDB</a> and <a href="https://firebase.google.com/docs/firestore">Cloud Firestore</a> — <strong>while simultaneously prioritizing configurations from multiple sources as well</strong>.</p><h4><strong>❗️TL;DR</strong></h4><blockquote><strong>The main problem Viper solves is standardizing how you consume configs within your application, despite the source, allowing you to focus on writing your code without worrying about the source of your configs.</strong></blockquote><blockquote><strong>The other thing I would like to note is that even without Viper, configs are there; they are just provided differently, or worse, hard coded in to the application, which makes it difficult to change them easily without needing to ship a whole new application.</strong></blockquote><h4>What you will learn</h4><ul><li>How to <a href="#db03">provide configurations to your Go applications from different sources</a> — config files, environment variables, etc.</li><li>How to <a href="#9614">manage multiple configuration sources</a> (e.g., how to let viper know where to look for configurations)</li><li>How to <a href="#91b8">set default values</a> in case configurations aren’t found</li><li>How to <a href="#1dbb">consume and use configurations within your applications</a></li><li>How to <a href="#3a6d">write back to configuration files</a>, especially when the user updates configurations and saves the settings in a config file</li><li>How to <a href="#3db2">watch and live-reload configuration changes</a> to your application without restarting your application for configs to take effect</li></ul><h4>Prerequisites</h4><ul><li>A good understanding of Go fundamentals</li></ul><p>Let’s get to it.</p><blockquote><em>📌</em> Disclaimer: This is going to be the first of two articles. In this article, we are going to focus on features provided by Viper and how we can use them to manage configs from local sources and environment variables. In the next article, we will see how we can use Viper to read remote configuration systems, such as Consul, or databases, such as Cloud Firestore.</blockquote><figure><img alt="Unique separator for The GoDev Corner" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Installing Viper</h3><p>To use Viper, you can install it using the following command:</p><pre>go get -u github.com/spf13/viper</pre><h3>Reading Configuration Local Sources — Files and Environment Variables</h3><h4>Configuration Files</h4><p>When passing configurations to our applications, it is quite common to use config files or environment variables. <strong>With Viper, as we had stated earlier, we can consume configs from different file formats — </strong>yaml, json, toml, etc. — <strong>and from multiple directories</strong>.</p><p>We can even tell Viper where to find a configuration file(s) by using viper.SetConfigFile method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4f0b2c339c634bbf99c4e5ac35c461e/href">https://medium.com/media/e4f0b2c339c634bbf99c4e5ac35c461e/href</a></iframe><blockquote><em>👉</em> <em>Note:</em> This isn’t <strong>flexible</strong>, meaning we need to specify the <em>exact paths</em> for all of our config files</blockquote><p>It’s also worth mentioning that it’s common for different applications to have multiple directories and ways in which configurations can be provided to them.</p><p>For instance, <em>system user-level</em> configuration files can be stored inside the OS User Directory, while <em>application-specific</em> config files can be stored next to the binaries, and so on. (You can also have <em>both</em> simultaneously.)</p><p>Viper allows us to read config files from different sources by accepting the config files’ names, the extensions we’re interested in (json, yaml, etc.), <em>and</em> the directories in which it will look.</p><p><strong>In other words, Viper will gather the source directories, look for configurations, read them, and make them available within your application.</strong></p><p>To achieve this, we need to specify the path(s) where our config files are stored using the viper.AddConfigPath:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/906e2d363ec25a6652b5d7e8660401e8/href">https://medium.com/media/906e2d363ec25a6652b5d7e8660401e8/href</a></iframe><p>Next, we will need to specify the possible names of our config files using the viper.SetConfigName function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/224780428093e85a54ea30e2be927b6c/href">https://medium.com/media/224780428093e85a54ea30e2be927b6c/href</a></iframe><blockquote><em>☝️Remember</em>: The config names do NOT have file extensions, we will set file extensions below.</blockquote><p>The extensions for the config files can be added using the viper.SetConfigType function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03bba0dac1b4748a232ec487e9e8c3bf/href">https://medium.com/media/03bba0dac1b4748a232ec487e9e8c3bf/href</a></iframe><blockquote><em>👉</em> <em>Note: </em>For all this, we can provide multiple values for Config path, name and Type. Viper will use this information to search for configurations files matching the above requirements</blockquote><h4>Environment Variables</h4><p>On top of reading config files, <strong>Viper can also read environment variables and provide robust tools to deal with them</strong>.</p><p>One of the methods provided by Viper for configuration management is AutomaticEnv, a helper method that instructs Viper to automatically look for configurations in environment variables when reading values. So that when you are getting a value, environment variables are also used as a source.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b956f4b885de592218109f4ac78f503/href">https://medium.com/media/2b956f4b885de592218109f4ac78f503/href</a></iframe><p>On top of that, Viper also provides SetEnvPrefix and BindEnv methods.</p><p>The SetEnvPrefix method allows you to set a prefix for all environment variables and retrieve their values without needing to specify the prefix. Additionally, BindEnv allows you to bind an environment variable to a config key.</p><p>The BindEnv method takes multiple arguments, with the first argument being the config key, while the other arguments are environment variables keys to bind to. If they are prefixed, supply them without the prefix and use the SetEnvPrefix method above to set the prefix for the environment variables.</p><blockquote><em>👉 Note:</em> Environment variable keys are bonded in the order they are specified, with the first one taking precedence</blockquote><p>For instance, if our environment variables were prefixed as APP_ (i.e., APP_PORT), we would use the viper.SetEnvPrefix to set the prefix, which will be pre-pended when we try to read environment variables.</p><p>So, in this case, we would only specify either PORT or port (keys are not case sensitive):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56aa52a344ac99cb03156da22a600c19/href">https://medium.com/media/56aa52a344ac99cb03156da22a600c19/href</a></iframe><h4>Setting Default Values</h4><p>Another important aspect of your application configuration files is having <em>default values.</em></p><p><strong>In Viper, <em>default values</em> are used as the fallback values if values aren’t found in any of your other configuration sources</strong>.</p><p>In fact, it provides a method called viper.SetDefault to set default values, which accept a string key and value of any type, as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50db898353d1a34bef16454a96ac148a/href">https://medium.com/media/50db898353d1a34bef16454a96ac148a/href</a></iframe><blockquote><em>👉</em> <em>Note: </em>Key names are NOT case sensitive in Viper</blockquote><blockquote>Please also keep in mind that environment variables take precedence over config files, while config files take precedence over default values.</blockquote><h4>Reading Configurations</h4><p>And finally, we can read our configurations to use within the applications using the viper.ReadInConfig():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/348f39c192665953126131591ac76ff8/href">https://medium.com/media/348f39c192665953126131591ac76ff8/href</a></iframe><p>In the next section, we will see how we can use the configurations within our application.</p><figure><img alt="Unique separator for The GoDev Corner" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Reading Configuration Values</h3><p>Next, we need to get values from our configurations and use them within our application.</p><p>Viper provides a series of methods to get different values of different types. For instance, viper.GetString(key) can retrieve a string value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8704d00cbf701fdc6260b4f24828594/href">https://medium.com/media/d8704d00cbf701fdc6260b4f24828594/href</a></iframe><blockquote><em>📖 Further Reading:</em> Please check out the docs <a href="https://github.com/spf13/viper#getting-values-from-viper">here</a> for a comprehensive list of methods you can use to read config values</blockquote><p>On top of reading individual config values, Viper provides a method to check whether a config file has been set using the viper.IsSet(“key”):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e24612e53ed1ca0db48d3ad9d73c3230/href">https://medium.com/media/e24612e53ed1ca0db48d3ad9d73c3230/href</a></iframe><p>Finally, another method to fetch all keys and settings —viper.AllKeys() and viper.AllSettings(), respectively:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8e23a89f16f13858e6e9e39408cd245/href">https://medium.com/media/b8e23a89f16f13858e6e9e39408cd245/href</a></iframe><blockquote><em>☝️ Remember: </em>Viper returns nil value if a value of the type in question isn’t found and you need to check for nil values before consuming configurations. <strong>You can use defaults to set fallback values.</strong></blockquote><figure><img alt="Unique separator for The GoDev Corner" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Writing Back to Configurations</h3><p>So far, we have been focused on <em>reading</em> config files, but Viper can, in fact, also <em>write to</em> config files, allowing you to save settings/configurations from your application.</p><p>And while more technically astute users can manage and edit the config files directly, others may need some assistance.</p><p><strong>Viper enables all of this for you, and thus makes it possible to provide you with a user interface to interact with and update configs, which at least in my opinion, is <em>exponentially</em> easier.</strong></p><p>Viper provides a number of methods to safely write configurations: WriteConfig() and SafeWriteConfig():</p><ul><li>The WriteConfig() method will write the current configurations back and will override any existing configurations</li><li>Conversely, the SafeWriteConfig method will write back the current configurations but will <strong>NOT</strong> override existing configurations</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ab53834c5d7a95506784a99df512a1e/href">https://medium.com/media/3ab53834c5d7a95506784a99df512a1e/href</a></iframe><blockquote><em>👉</em> <em>Note:</em> The files to write configurations to are the ones that were set using the previously discussed viper.AddConfigPath() and viper.SetConfigName methods. See <a href="#2efe">here</a> to go back to that section</blockquote><p>On top of that, Viper provides two more methods worth discussing: WriteConfigAs and SafeWriteConfigAs, each accepting a path to the config file to which Viper will write the config:</p><ul><li>WriteConfigAs will override any existing configs in the provided path</li><li>SafeWriteConfigAswill fail if configs already exist:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c07e7622553cf6b3c256d7ea9951ac6/href">https://medium.com/media/3c07e7622553cf6b3c256d7ea9951ac6/href</a></iframe><figure><img alt="Unique separator for The GoDev Corner" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Watching Configurations</h3><p>Lastly, one more key feature from Viper is the ability to watch and reload configs <em>when they change</em>.</p><p><strong>You don’t have to start your Go application to reload the configs. Instead, Viper automatically handles this for you.</strong></p><p>You can achieve this using the WatchConfig method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f06d9a932d78f9e3e4b9435c376de4d5/href">https://medium.com/media/f06d9a932d78f9e3e4b9435c376de4d5/href</a></iframe><p>On top of the WatchConfig method for reloading the changes, Viper also provides a OnConfigChange method, which is called each time the config changes, allowing you to react to config changes within your application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc2331502e5e5f966f399dc8cf41d0ed/href">https://medium.com/media/dc2331502e5e5f966f399dc8cf41d0ed/href</a></iframe><figure><img alt="Unique separator for The GoDev Corner" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Conclusion</h3><p>In this article, we learned how we can use Viper, a Golang library, to manage configurations for our Go application.</p><p>With Viper, we are able to search for configurations across a wide range of sources — files, environment variables, and default values and use the configurations within our application.</p><p>On top of reading configuration files, Viper enables us to <em>write back to configs</em> and <em>live-watch configs</em> so that we don’t have the need to restart our application/server whenever configurations changes.</p><p>See you next time when we cover how to use Viper to read and manage configs from remote sources and databases.</p><h4>Key Takeaways</h4><ul><li>Viper is a very powerful Golang library that we can use to manage configurations within our applications. With it, you can consume configs from different file formats — yaml, json, toml, etc. — and from multiple directories</li><li><strong>The main problem Viper solves is standardizing how you consume configs within your application, despite the source, allowing you to focus on writing your code without worrying about the source of the configurations</strong>. Whether we are talking of environment variables, config files, and so on, the API to read and use them is the same — vipers handles everything else for you</li><li>Even when not using Viper to manage configs, configs are still there; they are just provided differently, or worse, hard coded into the application, which makes it difficult to change them without needing to ship a whole new application every time something changes</li><li>Viper can read environment variables and provide robust tools to deal with them. It can also write back to configs using the following methods: WriteConfig(), SafeWriteConfig(), WriteConfigAs, and SafeWriteConfigAs. See more information <a href="#3a6d">here</a></li></ul><figure><img alt="Unique separator for The GoDev Corner" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Other Articles To Consider</h3><ul><li><a href="https://medium.com/the-godev-corner/how-to-run-go-integration-tests-for-third-party-services-using-docker-b8104a943c4">How To Run Go Integration Tests for Third-party Services Using Docker</a></li><li><a href="https://medium.com/the-godev-corner/how-to-create-a-pdf-in-go-157355429a94">How To Create a PDF in Go: A Step-By-Step Tutorial</a></li></ul><figure><img alt="Unique separator for The GoDev Corner" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><p><em>Disclosure: In accordance with Medium.com’s rules and guidelines, I publicly acknowledge financial compensation from </em><a href="http://www.unidoc.io/"><em>UniDoc</em></a><em> for this article. All thoughts, opinions, code, pictures, writing, etc. are my own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e55146c37c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-godev-corner/manage-configurations-from-local-sources-in-go-4e55146c37c2">Manage Configurations From Local Sources in Go</a> was originally published in <a href="https://medium.com/the-godev-corner">The GoDev Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Run Go Integration Tests for Third-party Services Using Docker]]></title>
            <link>https://medium.com/the-godev-corner/how-to-run-go-integration-tests-for-third-party-services-using-docker-b8104a943c4?source=rss-3162bd0b0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8104a943c4</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Maina Wycliffe]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 16:19:36 GMT</pubDate>
            <atom:updated>2022-10-19T16:19:36.269Z</atom:updated>
            <content:encoded><![CDATA[<h4>Golang: How To Guide</h4><h3>How To Run Go Integration Tests For Third-party Services Using Docker</h3><h4>Follow along as we set up a fake mail server and send emails to the Docker container for testing</h4><figure><img alt="A Golang Gopher holding a Docker whale while representing how to run golang integration tests for third party services using Docker" src="https://cdn-images-1.medium.com/max/1024/1*mEC9Ru8wdpQ9-QwHFVG0xA.jpeg" /></figure><h3>Introduction: Simplify The Testing Process</h3><p>Writing integration tests in Go can be a tricky challenge, especially when third-party or external services are involved.</p><p>For instance, think about having a <em>clean</em> <em>database and data set</em> to work for your tests, assuming you wanted to write data to a database.</p><p>It may <em>seem</em> insignificant. But if you’ve ever written tests before, you’ll know that A LOT goes into that, especially when you consider the number of environments you might need to run your tests in (i.e., different developer machines and CI environments).</p><p><strong>Luckily, this is where Docker containers come in</strong>; they can help us create portable environments that we can seed data with, run tests, and then discard after we get our results.</p><p>With containers being created for each test run, we get a sanitized environment — one that hasn’t been contaminated by previous tests and one that only contains the necessary data we need. This results in tests whose behavior is easier to predict (i.e., deterministic), saving us time, money, and potentially extra resources.</p><p>To demonstrate this, we’ll use Docker to set up a fake mail server and send emails to the Docker container during testing. Then, we’ll tear it down immediately after the tests are done.</p><h4>What you will learn</h4><p>By the end of this article, you should be able to:</p><ol><li><a href="#1402"><strong>Install and run Dockertest</strong></a> to build, run and manage Docker containers</li><li><a href="#a38d"><strong>Create and run Docker containers</strong></a><strong> </strong>using a dockertest</li><li>Set up<a href="#3ecd"><strong> a fake mail server</strong></a> using docker to send our testing emails</li><li><a href="#a997"><strong>Retrieve the containers’ published ports</strong></a> to access services (e.g., SMTP and HTTP)</li><li><a href="#5cb7"><strong>Run your test</strong></a> against the docker container created during the setup process</li><li><a href="#ad3f"><strong>Teardown</strong></a> to clean up resources used during the testing process</li><li><a href="#8396"><strong>Gather essential takeaways</strong></a> from your experience</li></ol><p>…and overall, use docker containers to run integration tests against third-party services, such as databases, mail servers, etc.</p><figure><img alt="The GoDev Corner’s unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Get everything lined up</h3><p>To write our integrations, we’ll use <a href="https://github.com/ory/dockertest">Dockertest</a>, which provides us with APIs to interact with Docker. With it, we’ll be able to create and run Docker containers for testing purposes, get the results we need, and discard them afterward for easy cleanup.</p><figure><img alt="Ron Burgundy famously self-proclaiming his notoriety" src="https://cdn-images-1.medium.com/max/500/1*uWIVyczMTiQr7ayP21z1MQ.jpeg" /></figure><p>Thanks Ron.</p><p>Anyway, with Dockertest, we can either use <em>existing</em> Docker images (i.e., pull the images from a Docker repository or use locally available Docker images) or build a Docker file for more complex tests. We’ll focus on the latter to show you how everything works, and to create our own custom images.</p><blockquote><em>👉</em> Note: To get an existing Docker image and follow along, feel free to use <a href="https://hub.docker.com/r/mailhog/mailhog/">MailHog</a></blockquote><h4>Installing and running Dockertest</h4><p>Now, before we can use Dockertest, we first need to install it using the go get command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd3e78a851fd61661911f6176fc8f918/href">https://medium.com/media/bd3e78a851fd61661911f6176fc8f918/href</a></iframe><p>Next, we need to add the logic to create and run the required Docker containers, add any seed data, and kill the containers afterward. All this is done inside the <strong>TestMain</strong> function, which will allow us to have more granular control over everything.</p><p>Let’s get that setup:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/571217b6a0646c19e1358fc6fee9e3c5/href">https://medium.com/media/571217b6a0646c19e1358fc6fee9e3c5/href</a></iframe><p>We also want to write some tests for a very small function that sends out emails to get our Dockertest running correctly. Below is a mail struct, which holds the settings to access our SMTP Server. Let’s enable what we want:</p><blockquote><em>💡 </em>Big Picture: We are going to use a fake mail server that saves emails in an in-memory database and exposes the results via an API that we can use to retrieve emails sent via SMTP. This will allow us to request for all sent messages and then check if the message we sent is among those that we get back. That way, we can know whether our test was a success or a failure.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2932500a5a0d4b4faedeb98e38919835/href">https://medium.com/media/2932500a5a0d4b4faedeb98e38919835/href</a></iframe><p>The <strong>Send</strong> method above allows us to send an email to a list of email addresses with a given subject and body. We want to check whether our email was sent successfully when we do this.</p><h4>Setting up the fake mail server</h4><p>Next, we want to see how we can create our own Docker image to run integration tests against. So we’ll use <a href="https://github.com/mailhog/MailHog">Mailhog</a>, a Golang package inspired by<a href="https://mailcatcher.me/"> MailCatcher</a>, as our fake mail server.</p><p>This is what our Docker file should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3bba8caca18cc4690d36f43affa70fa/href">https://medium.com/media/d3bba8caca18cc4690d36f43affa70fa/href</a></iframe><h4>Setup the container’s published ports</h4><p>Lastly, as part of our setup, we need to define a few package-level variables to hold our SMTP_HOST, SMTP_PORT, and HTTP_PORT.</p><p>We can get both the SMTP_PORT and HTTP_PORT values from the container published ports after it has been created and is up and running:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7174175536e84e364462b634e4b1dd76/href">https://medium.com/media/7174175536e84e364462b634e4b1dd76/href</a></iframe><blockquote>👉 Note: These are the containers’ published ports that allow us to access services such as HTTP (think of <a href="http://localhost:3000)">http://localhost:3000)</a> and SMTP servers running inside our container. They’re forwarded to a container’s internal ports for respective services (i.e., ports 1025 and 8025 for SMTP and HTTP, respectively).</blockquote><p>Now that we have introduced the code, the Docker file, and the published ports that we are going to be testing, we can start writing the actual tests.</p><figure><img alt="Wooderson enthusiastically getting ready for the next section by saying “alright alright alright”" src="https://cdn-images-1.medium.com/max/500/1*4MvVt0CkOVj6dHTmYR358Q.jpeg" /></figure><figure><img alt="The GoDev Corner’s unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Writing and running the test</h3><h4>Set up: Creating and running Docker containers using Dockertest</h4><p>Inside the <strong>TestMain</strong> function of our package, we need to do three things:</p><ol><li>Establish a connection to an existing local Docker API;<br>[To use remote Docker, please see the guide <a href="https://github.com/ory/dockertest#how-to-run-dockertest-with-remote-docker">here</a>]</li><li>Create a Docker container from our Docker file; and</li><li>Verify that it’s up and running</li></ol><p>To achieve this, we’ll need to create a new Docker pool. A pool represents a connection to the Docker API and enables Dockertest to create, run and remove Docker images.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a26622954aff63e9165e2b58722def53/href">https://medium.com/media/a26622954aff63e9165e2b58722def53/href</a></iframe><p>Let’s build and run our Docker file using the <strong>pool.BuildAndRun</strong> method from Dockertest. The method accepts three arguments:</p><ul><li>Container name;</li><li>Path to the Docker file to build and run; and</li><li>Environment variables — <em>a string array in the following format: </em><strong><em>[“env=value”]</em></strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7f48a5bd7801a5aa9f0e33e0f966c06/href">https://medium.com/media/b7f48a5bd7801a5aa9f0e33e0f966c06/href</a></iframe><blockquote><em>👉</em> Note: To use a Docker image pulled from an image repository, you can use the <strong>pool.Run</strong> method instead, which accepts 3 arguments: <em>(1) Docker image to use; (2) the image tag to use; and (3) environment variables</em>. If the image isn’t available locally, Dockertest is going to use Docker to pull from the image repository.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98afb1896bc9381682b25a43860e0bdc/href">https://medium.com/media/98afb1896bc9381682b25a43860e0bdc/href</a></iframe><p>Then we need to make sure our Docker container is up and running by pinging the SMTP Server.</p><p>Use the<strong>pool.Retry</strong> method here to see if our container is ready to be used (with exponential back-off). Then use the <strong>resource.GetPort</strong> method to get the published ports for the container’s SMTP_PORT and HTTP_PORT:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ba403a0050281c8da46b089eee7a152/href">https://medium.com/media/0ba403a0050281c8da46b089eee7a152/href</a></iframe><blockquote><em>👉</em> Note: To get a published container port, we need to know the port it’s being forwarded to (i.e., 1025 for SMTP and 8025 for HTTP in our case). The method will return an error if the container isn’t ready for us to use, and nil if the container <strong>is</strong> ready. To learn more about Docker container networking, please find the documentation<a href="https://docs.docker.com/config/containers/container-networking/#published-ports"> here</a>.</blockquote><p>If we’re dealing with a database (e.g., MySQL, MongoDB, etc.) and we need specific data for our tests to work, we can add seed data at this point.</p><p>For example, if we were testing a login functionality, we might want to create some users in our database to test the functionality. But for now, I’ll skip over this.</p><h4>Run the test</h4><p>Finally, we can tell Go’s test runner to run our tests by calling <strong>m.Run():</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78f76134ad32181ed81a8270835a0e04/href">https://medium.com/media/78f76134ad32181ed81a8270835a0e04/href</a></iframe><blockquote><em>❗️</em> Pro Tip: This is going to run all the tests for the entire package; we need to make sure that all the setup needed by all package tests is done by this point. Remember, we can only have a single <strong><em>TestMain</em></strong> per package.</blockquote><figure><img alt="The GoDev Corner’s unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Teardown</h3><p>After our tests have run, we will need to free up the resources that were created by Dockertest for the purpose of our test, as container names can’t be reused if the container already exists.</p><blockquote>“Can’t I just leave them running in the background?”</blockquote><p>Absolutely not. As you can imagine, this will make running subsequent tests a challenge as the container and any data generated by our tests will be eating up space within our system, which is not something we want.</p><p>If you don’t kill the container after the tests have been completed, either successfully or unsuccessfully, you <strong>will</strong> have to do it manually</p><p>To free up the previously used resources, let’s use the<strong>pool.Purge</strong> command, which will subsequently kill our container(s):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30840f0af3928f03860b1c1b360da5aa/href">https://medium.com/media/30840f0af3928f03860b1c1b360da5aa/href</a></iframe><blockquote><em>❗️</em> Pro Tip: Sometimes, the cleanup process fails for one reason or the other; in cases like this, you can set resources to expire if such situations happen. You achieve this by setting an Expiration time for the resource using the <strong>resource.Expire</strong> method and Docker will hard kill the container after the specified period.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/934bcf47359b76a3f45939405e77d34c/href">https://medium.com/media/934bcf47359b76a3f45939405e77d34c/href</a></iframe><p>Finally, we can finish our tests by calling <strong>os.Exit:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e963a53e977594c9563da3e2179826f1/href">https://medium.com/media/e963a53e977594c9563da3e2179826f1/href</a></iframe><p>This is what our <strong>TestMain</strong> function should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1194f6cf6f61e69fc7eddffa2d2bd07a/href">https://medium.com/media/1194f6cf6f61e69fc7eddffa2d2bd07a/href</a></iframe><figure><img alt="The GoDev Corner’s unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Testing the sent email</h3><p>To recap, we have written our test setup and teardown code and saved our containers’ published ports on package-level variables — <strong>SMTP_PORT</strong> and <strong>HTTP_PORT.</strong></p><p>All we need to do now is to test the <strong>Send</strong> function.</p><blockquote><em>💡</em>Big Picture: Even though we’re testing a send email functionality here, the same kind of logic applies to testing other kinds of services, such as databases (e.g., MongoDB, MySQL) and APIs (either REST or GraphQL). The overall goal isn’t to dive deep into the <strong>Send</strong> function — that’s beyond the scope of the article. Rather, it’s merely to show how the logic is being used to facilitate the testing process.</blockquote><p>Let’s define a new Mail struct here and then call the <strong>mail.Send</strong> method. The method returns an error if things go wrong, and we are going to expect that to be nil if sending an email succeeds.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c429b513bc784e9821f0c3818290936f/href">https://medium.com/media/c429b513bc784e9821f0c3818290936f/href</a></iframe><p>We also want to query the HTTP API exposed by the <strong>MailHog</strong> server running on our Docker container to both fetch messages received and ensure they were sent successfully.</p><p>In our case, since we just have a single function and are calling it once, let’s just focus on getting the first message to run our assertions against its body content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84a943ae962af1bcfeaae73f96bfb951/href">https://medium.com/media/84a943ae962af1bcfeaae73f96bfb951/href</a></iframe><p>Voila! Test complete</p><p>Questions/Troubles/Concerns? Post them below in the Comments👇 and I’ll make sure to answer them as quickly as possible.</p><figure><img alt="The GoDev Corner’s unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Conclusion</h3><p>In this post, we learned how we can use Docker to run integration tests: we used Dockertest to create and run a Docker container, run our tests against it, and destroy it once the tests are done.</p><p>This allows us to have a clean test environment that we can use to run our tests against without fear of contaminated data which can make our tests unpredictable.</p><h4>Takeaways</h4><ol><li><a href="https://github.com/ory/dockertest">Dockertest</a> is a powerful tool that can allow you to interact with Docker. With it, you can create and run Docker containers for testing purposes, acquire the results you need, and clean up everything easily. Consider it in the future.</li><li>Use Docker to create fresh containers containing only what your tests need that you can run your integration tests against. Docker containers are easy to create and destroy and can be easily replicated, ensuring you have the perfect target for your tests.</li><li>Use the TestMain function to set up the resources necessary to run your tests and teardown to release the resources consumed by your tests, such as Docker containers. You don’t want orphan containers running in the background.</li></ol><figure><img alt="The GoDev Corner’s unique separator" src="https://cdn-images-1.medium.com/max/1024/1*qvhuwhaIJ1NCCRA1l0qTig.png" /></figure><h3>Other articles to consider</h3><ul><li><a href="https://medium.com/the-godev-corner/how-to-create-a-pdf-in-go-157355429a94">How To Create a PDF in Go: A Step-By-Step Tutorial</a></li><li><a href="https://medium.com/the-godev-corner/how-to-create-a-go-private-module-with-docker-b705e4d195c4">How To Create a Go Private Module With Docker</a></li></ul><p><em>Disclosure: In accordance with Medium.com’s rules and guidelines, I publicly acknowledge financial compensation from </em><a href="http://www.unidoc.io/"><em>UniDoc</em></a><em> for this article. All thoughts, opinions, code, pictures, writing, etc. are those of my own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8104a943c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-godev-corner/how-to-run-go-integration-tests-for-third-party-services-using-docker-b8104a943c4">How To Run Go Integration Tests for Third-party Services Using Docker</a> was originally published in <a href="https://medium.com/the-godev-corner">The GoDev Corner</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>