<?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 Uxío García Andrade on Medium]]></title>
        <description><![CDATA[Stories by Uxío García Andrade on Medium]]></description>
        <link>https://medium.com/@uxioandrade?source=rss-baa7cd4fce4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MpCEx_rtJcTm9I54wR_Q5w@2x.jpeg</url>
            <title>Stories by Uxío García Andrade on Medium</title>
            <link>https://medium.com/@uxioandrade?source=rss-baa7cd4fce4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:19:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@uxioandrade/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 Your First Rust API]]></title>
            <link>https://medium.com/better-programming/build-your-first-rust-api-cd2cba50cf8d?source=rss-baa7cd4fce4------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd2cba50cf8d</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Uxío García Andrade]]></dc:creator>
            <pubDate>Tue, 23 Feb 2021 19:54:32 GMT</pubDate>
            <atom:updated>2021-02-23T19:54:32.563Z</atom:updated>
            <content:encoded><![CDATA[<h4>Take a hands on approach to learning Rust by building a real world API using Rocket.rs and Diesel.rs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1Npao1Ww536EDYBe2KZmw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Paweł Czerwiński</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this tutorial I’ll describe how to build a simple API using the popular Rust web framework <a href="https://rocket.rs/">Rocket</a> and <a href="https://diesel.rs/">Diesel</a> as our ORM for Postgres. I initially built this little project to learn both Rust and the aforementioned technologies, so I thought it would be a nice idea to try to build something that I could use in one way or another. That’s why I decided to build this little API to help me manage the links to my Medium posts in my portfolio.</p><h3>Structure of Our API</h3><p>First of all, let’s take a look at how our API will be structured. It will have three main route handlers:</p><ul><li>/user<strong>: </strong>creates users and then validates user’s access tokens</li><li>/auth<strong>: </strong>group used to get user’s access tokens</li><li>/posts<strong><em>: </em></strong>creates and retrieves posts</li></ul><p>At the end of this tutorial, we’ll have the following endpoints in our API (this is the output that we get when we run our server):</p><pre>Mounting <em>/user:</em></pre><pre>=&gt; <strong><em>POST</em></strong> <em>/user</em> <em>application/json</em> <em>(create)</em></pre><pre>=&gt; <strong><em>GET</em></strong> <em>/user/info</em> <em>(info)</em></pre><pre>=&gt; <strong><em>GET</em></strong> <em>/user/info</em> <em>[2]</em> <em>(info_error)</em></pre><pre>Mounting <em>/auth:</em></pre><pre>=&gt; <strong><em>POST</em></strong> <em>/auth/login</em> <em>(login)</em></pre><pre>Mounting <em>/posts:</em></pre><pre>=&gt; <strong><em>POST</em></strong> <em>/posts</em> <em>(create)</em></pre><pre>=&gt; <strong><em>GET</em></strong> <em>/posts</em> <em>(read)</em></pre><pre>=&gt; <strong><em>POST</em></strong> <em>/posts</em> <em>[2]</em> <em>(create_error)</em></pre><pre>Rocket <em>has</em> <em>launched</em> <em>from</em> <a href="http://0.0.0.0:8000/"><em>http://0.0.0.0:8000</em></a></pre><h3>Setting Everything Up</h3><p><em>In this tutorial it’s assumed that you have downloaded Rust and have an instance of </em>Postgres<em> running.</em></p><p>First, we’ll create a new Rust project with the following command (from now on we’ll take blog-backend as the name of our project):</p><pre><strong>cargo</strong> new blog-backend</pre><p>As Rocket makes use of Rust’s advanced features, we’ll need to use the nightly version of Rust. In order to only use the nightly version for our project, we navigate to the directory of our project (blog-backend) and run the following command:</p><pre><strong>rustup</strong> override set nightly</pre><p><em>Note</em>: Rocket requires the latest version of Rust nightly, so if any problem comes up while building, just update both the toolchain and dependencies:</p><pre><strong>rustup</strong> update &amp;&amp; <strong>cargo</strong> update</pre><p>Now we will install the diesel_cli package, which will help us manage our database schema. Again, as we are using Postgres, we can avoid downloading all the other default features:</p><pre><strong>cargo</strong> install diesel_cli --no-default-features --features &quot;postgres&quot;</pre><p>Then we indicate to Diesel the URL for connecting to our database by setting the following environment variable. In this case, blog is the name of the schema we’re using:</p><pre><strong>export</strong> DATABASE_URL=postgres//user:pass@localhost/blog</pre><p>Now the Diesel CLI will handle both the database and the migrations directory creation with this command:</p><pre><strong>diesel</strong> setup</pre><p>Now, if we recall our API definition, we’re clearly working with two different data types: users and posts, so we will have to create tables for both entities.</p><p>First, we create a table to store our users. We do this by defining a migration strategy:</p><pre><strong>diesel</strong> migration generate users</pre><p>This command generates two files, up.sql and down.sql, placed in the directory migrations/date_of_creation_users/<em>. </em>The first file defines how the migration will be applied, the second one defines how it will be reverted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fdb127a8570ad99ced6a950be6faa28/href">https://medium.com/media/2fdb127a8570ad99ced6a950be6faa28/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4f62dc66d6ba38b8aba481e807254fa/href">https://medium.com/media/d4f62dc66d6ba38b8aba481e807254fa/href</a></iframe><p>And we apply the migration:</p><pre><strong>diesel</strong> migration run</pre><p>We’ll repeat the process for the posts table, with the following definition files:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a3d0652ecf85ec7ccd2c1cfc6d0e196/href">https://medium.com/media/5a3d0652ecf85ec7ccd2c1cfc6d0e196/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26621024c41541cb34d9d9aa44ffb628/href">https://medium.com/media/26621024c41541cb34d9d9aa44ffb628/href</a></iframe><p>Finally, we add all the dependencies that we need in our <em>Cargo.toml</em> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7663193a096ca1f7a12d1c44b1638603/href">https://medium.com/media/7663193a096ca1f7a12d1c44b1638603/href</a></iframe><h3>Getting into the Code</h3><p>You might have noticed that a file called schema.rs<em> </em>has been generated at some point during the set up. This file is autogenerated by Diesel and is updated when we run our migrations. It contains table! macros which represent all of the tables and columns from the database schema.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3dcef9c8b8f248bfa9031f810113203/href">https://medium.com/media/f3dcef9c8b8f248bfa9031f810113203/href</a></iframe><p>In order to establish a database connection, we’ll use the following file to create a database connection pool so that we can reuse the database connections in future requests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0eae5d1120bd5030dfd2e4ad3a698a0b/href">https://medium.com/media/0eae5d1120bd5030dfd2e4ad3a698a0b/href</a></iframe><p>Now we add a main function, where we start the rocket server, initialize the database connection pool, and mount both the users and posts module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/243b5eef5a046d45992cca723a6e0f5d/href">https://medium.com/media/243b5eef5a046d45992cca723a6e0f5d/href</a></iframe><h3>Users</h3><p>Now we get into the users module. In this module we not only include everything related to users, but also to authentication.</p><p>First, we take a look at our model.rs<em> </em>file<em>, </em>where we<strong> </strong>define the User structure and implement the methods that interact with the database:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f8ec79416e6cbe45271631ed7dc2f4a/href">https://medium.com/media/1f8ec79416e6cbe45271631ed7dc2f4a/href</a></iframe><p>Note that we have two different user structures. The naming of both structures explains the reasoning for this: as the user ID is created by the database, the user struct that we use for inserting will be the same as the regular user struct, but dropping the ID field.</p><p>We’re using the bcrypt<em> </em>crate to encrypt user’s passwords. When inserting a new user, we update the password field of the user struct by hashing the previous value. On the other hand, when trying to retrieve a user by their username and password, we have to verify that both passwords match by using the verify function from the aforementioned crate.</p><h4>Authentication</h4><p>We’re using a JWT based authentication. I discovered a Rocket implementation in the <a href="https://github.com/marcocastignoli/rust_rocket_api_authentication">following repository</a>, so we can see that’s what we are using:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cacc6f772e6c9649de39be69f1cb14cb/href">https://medium.com/media/cacc6f772e6c9649de39be69f1cb14cb/href</a></iframe><p>In this file, we are essentially checking every request that requires a user to be authenticated. If the requests include a header with a valid token, it’s accepted, but if the token is missing or invalid, the request is forwarded.</p><p>Finally, we define the handler functions for the user and authentication routes. The only handler that’s not straightforward is the login one, where we check whether the credentials are right and then generate a valid token for the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bfac11c07d5f2810f38457cc3c3b90b/href">https://medium.com/media/6bfac11c07d5f2810f38457cc3c3b90b/href</a></iframe><h3>Posts</h3><p>The posts model will be similar to the users one. As posts also have a database generated ID, we’re also taking the two structs approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8ba591298a57e71bc642adf36a9fe15/href">https://medium.com/media/e8ba591298a57e71bc642adf36a9fe15/href</a></iframe><p>Finally, we will also define two routes for the POST method — one to handle the requests which include a valid token, and the other to send an unauthorized error:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eab535ba66daad3c72b69db8c1c31e9b/href">https://medium.com/media/eab535ba66daad3c72b69db8c1c31e9b/href</a></iframe><p>Now that we have everything we need, we can just run the following command and we’ll have everything up and running:</p><pre><strong>cargo</strong> run</pre><p>You may find all the files described in this tutorial in the <a href="https://github.com/UxioAndrade/blog-backend">repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd2cba50cf8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/build-your-first-rust-api-cd2cba50cf8d">Build Your First Rust API</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoid ORM in Go — Use Pure SQL Instead]]></title>
            <link>https://medium.com/better-programming/avoid-orm-in-go-use-pure-sql-instead-3ae7f0485b37?source=rss-baa7cd4fce4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ae7f0485b37</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Uxío García Andrade]]></dc:creator>
            <pubDate>Thu, 04 Feb 2021 18:23:42 GMT</pubDate>
            <atom:updated>2021-02-13T10:10:29.222Z</atom:updated>
            <content:encoded><![CDATA[<h3>Avoid ORM in Go — Use Pure SQL Instead</h3><h4>Stop <strong>learning a new ORM syntax for every language</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6H36joIh9dyT3vEf" /><figcaption>Photo by <a href="https://unsplash.com/@diesektion?utm_source=medium&amp;utm_medium=referral">Robert Anasch</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>If you are a software engineer who likes to try out many different languages and frameworks, you may have experienced the pain of having to learn the syntax of a new ORM for each language. This is a huge drawback that will either slow your initial productivity or drain your motivation.</p><p>On the other hand, if you already know SQL, you can use that knowledge and transfer it to many different languages by just following a few indications or simple tutorials like this one.</p><p>First of all, we will set up our environment. In order to follow the tutorial, you can install Postgres and get it running on your machine. Alternatively, you can use Docker. The following docker-compose file will get everything up and running without having to worry about anything else:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0515de22f5a4359d5f3b8227dcedac8/href">https://medium.com/media/d0515de22f5a4359d5f3b8227dcedac8/href</a></iframe><p>If you place this file at the root of your project, you just have to run the following command to set everything up:</p><pre><strong>docker-compose</strong> up</pre><p>As you can see, we have defined a volume in the db service that shares an SQL script that will be run on docker-compose startup. Note that you must map it to the docker-entrypoint-initdb.d<strong> </strong>directory so that the Postgres container runs it on startup. The init.sql<em> </em>includes the definition of the database and the table we are going to use in this tutorial, which is just an example of what a todos database could look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/975d29d31e54ca93bbbf79461d354996/href">https://medium.com/media/975d29d31e54ca93bbbf79461d354996/href</a></iframe><p>When the db container is started, it will run the script above and create both the database and the todos table (if they haven’t already been created).</p><p>Once we have our environment ready, we will move into the coding part.</p><p>First, we will define how our Go application will configure the access to our database. The only package we need to import is the postgres driver.</p><p>The first good practice that we are going to follow is to get all our database credentials from environment variables, as we don’t want them to be included in our code, which we may expose to the public.</p><p>Although this is not strictly necessary, we will define the following constants to avoid having hardcoded strings in some parts of our code. Note that the names of environment variables tend to be more descriptive in real-world scenarios.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52c4f6e700ac73bc50aa3254220b550e/href">https://medium.com/media/52c4f6e700ac73bc50aa3254220b550e/href</a></iframe><p>Then, we will use those constants to get the environment variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b553f021cba3026c5f9188aa2ee4c7a0/href">https://medium.com/media/b553f021cba3026c5f9188aa2ee4c7a0/href</a></iframe><p>Once we have all that, we will include the rest of our code inside the init() function.<strong> </strong>In Go, the init function gets called the first time a package is used, and it is not called again even if that package is used in a different package. In this function, we will just open the connection to the database and then check if the database is actually working properly by calling the Ping() method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34f8161f30a263a009827cabf9ae0dc8/href">https://medium.com/media/34f8161f30a263a009827cabf9ae0dc8/href</a></iframe><p>Now we will move on to our model. We will use the DAO and DTO patterns to define our model.</p><p>First, we will create the todos_dto.go file<em> </em>within the model/todos<em> </em>directory. The DTO pattern is used to transfer data between different modules of your application. Essentially, it is the abstraction through which information is passed between the DAO and the business services. In Go, you can implement it by creating a struct and defining how each field would be encoded in JSON. Note that this file shouldn’t contain any business logic that your application may contain.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53416f1eb31773b588e1e931f5569b6a/href">https://medium.com/media/53416f1eb31773b588e1e931f5569b6a/href</a></iframe><p>On the other hand, the DAO pattern separates the business logic from the data access logic. It provides methods for creating, retrieving, updating, and deleting the data present in your database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05d406b9949389eec8d599d207fd8ac1/href">https://medium.com/media/05d406b9949389eec8d599d207fd8ac1/href</a></iframe><p>In this tutorial, we will use prepared statements over just calling the Exec()<em> </em>or<em> </em>Query()<em> </em>methods<em> </em>directly. Although there are arguments about why to use one approach over the other, there are some benchmarks indicating that prepared statements are more performant in Go.</p><p>Once we call the Prepare()<em> </em>method with the query that we want to execute, we check the error returned and then defer the closing of the prepared statement. If we forget to do so, it will be bound to our connection forever. Because of that, it is important to always defer the stmt.Close()<em> </em>method call after preparing a statement.</p><p>Once we have all that, in the Save() method, we will execute the QueryRow<em> </em>method and Scan()<em> </em>the id returned. As the ID is autogenerated by the database, it will be missing in the INSERT query that we execute. In order to retrieve it from the database, some databases such as MySQL offer the possibility to call the LastInsertId()<em> </em>method from the result obtained in the query. However, as we are using Postgres, we can just explicitly declare our query that we want to return the ID generated.</p><pre>INSERT INTO todos(description, priority, status) VALUES($1, $2, $3) <strong>RETURNING id;</strong></pre><p>After checking that no errors have arisen, we assign the obtained ID to our Todo struct and we are done with the insertion.</p><p>As we have followed an approach of returning the todo ID in the insert query, the Get()<em> </em>method procedure will be analogous<strong> </strong>but simpler<strong>.</strong></p><p>In order to test that everything is working as expected, we will use the following main.go<em> </em>file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3613a00d7c415e8ccf9a4c03b54a073d/href">https://medium.com/media/3613a00d7c415e8ccf9a4c03b54a073d/href</a></iframe><p>It is a simple main that inserts two todos and then retrieves the todo with ID 1. Considering the logging that we have added to our DAO, the output of this main would be similar to this (note that I get IDs 5 and 6 because I had executed it a couple of times before):</p><figure><img alt="Output" src="https://cdn-images-1.medium.com/max/1024/1*sVRAB8cFwa3lENUf3E_OJA.png" /><figcaption>main.go output</figcaption></figure><p>If you get an output like this, then everything is working properly and you have succeeded at interacting with a database without using an ORM. You can find the code for this tutorial in this <a href="https://github.com/UxioAndrade/tutorials/tree/main/go-sql-tutorial">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ae7f0485b37" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/avoid-orm-in-go-use-pure-sql-instead-3ae7f0485b37">Avoid ORM in Go — Use Pure SQL Instead</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand Threads and Threading in Java]]></title>
            <link>https://medium.com/better-programming/understand-threads-and-threading-in-java-8f706fc44d13?source=rss-baa7cd4fce4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f706fc44d13</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Uxío García Andrade]]></dc:creator>
            <pubDate>Fri, 20 Mar 2020 17:42:34 GMT</pubDate>
            <atom:updated>2020-03-20T17:42:34.017Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concurrent programming with Java and the JVM</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*avFmOjZfhjhmNYoU" /><figcaption>Photo by <a href="https://unsplash.com/@drmakete?utm_source=medium&amp;utm_medium=referral">drmakete lab</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>When writing complex applications, it is common to find ourselves in need of executing multiple actions at the same time. Thankfully, Java and the JVM have been designed to support concurrent programming, as all execution takes place in the context of threads.</p><h3>JVM Support for Multi-Threading</h3><p>As Java was created in the ‘90s, a time when computers already had multiple processing units, their creators decided to include native support for multi-threading.</p><p>Java runs in the Java Virtual Machine. When a program is started, the JVM creates the main thread that executes the main()<em> </em>method. From this point on, the program can create as many threads as needed, following a hierarchical structure. In Java, a thread can be in any of the following states:</p><ul><li>New:<strong> </strong>When a new thread is instantiated, it is in this state. While being in this state, the thread hasn’t yet started to be executed.</li><li>Runnable:<strong> </strong>A thread in this state can either be running or just be prepared to run at any point.</li><li>Blocked/Waiting:<strong> </strong>In this state, the thread is inactive, waiting for a resource.</li><li>Suspended:<strong> </strong>A thread is in this state when it calls a method with a timeout parameter, which will suspend momentarily. After that, it can resume its execution at the point where it had stopped.</li><li>Terminated:<strong> </strong>When a thread finishes the execution of its run()<em> </em>method, it is in the terminated state. The garbage collector will free the resources used by this thread.</li></ul><p>Moreover, the JVM assigns to each thread its own method-call stack, which allows these threads to track local variables, parameters the JVM passes to a method, and the method’s return value.</p><h3>The Thread Class</h3><p>The first way of creating a thread in Java is to create a class that extends the Thread class,<strong> </strong>override the run method with the code the thread must run, and then instantiate this class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b71f09ca31a005ae207499be49d9f643/href">https://medium.com/media/b71f09ca31a005ae207499be49d9f643/href</a></iframe><p>Once we have this class created, we can instantiate it and start the thread:</p><pre><strong>MyThread</strong> thread = new <strong>MyThread</strong>();</pre><pre>thread.<strong>start</strong>();</pre><p>First, we allocate a new MyThread object and then we invoke the start method so that the JVM calls the run method of that thread. Note that starting a thread more than once is strictly forbidden (a thread may not be restarted once it has completed execution). If we wanted to run that thread again, we should create a new instance of the thread object.</p><h3><strong>The Runnable Interface</strong></h3><p>The runnable interface should be implemented by any class whose instances are intended to be executed by a thread. That class must define a method of no arguments called run. Furthermore, the runnable interface provides the means for a class to be active while not subclassing Thread.</p><p>In general, this interface is intended to be used when we just want to override the run method of a thread without using any other Thread method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fef92ec949fd6428b801196e6707c5dc/href">https://medium.com/media/fef92ec949fd6428b801196e6707c5dc/href</a></iframe><h3>How to Run a Thread Multiple Times</h3><p>If we want to run a thread multiple times, how would we do this in Java? One may be inclined to try the following approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/285a4d0a4f68649cee4d53fdba2204c2/href">https://medium.com/media/285a4d0a4f68649cee4d53fdba2204c2/href</a></iframe><p>But as I said before, this is not possible. If we try to run this code, an IllegalThreadStateException will be thrown.</p><p>In order to run it multiple times, a new thread should be instantiated. One of the possible approaches would be to have an array of threads. In this example, I will run ten threads:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1aa59205457d5e9f0dae59d97f9df043/href">https://medium.com/media/1aa59205457d5e9f0dae59d97f9df043/href</a></iframe><h3>Critical Section</h3><p>In Java, the Object class provides a lock that allows the programmer to manage exclusive access to the critical section. Locks admit two operations: open and close. When a lock is closed, any other attempt to close it will be suspended until it is opened by the thread that had closed it. The Java way of managing these operations is by using the synchronized construct. The first way of using this construct is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db155d4dd68d4c4c78cb664af1eaac3b/href">https://medium.com/media/db155d4dd68d4c4c78cb664af1eaac3b/href</a></iframe><p>The other way of using the synchronized construct is to define a synchronized method:</p><pre>public class <strong>MyClass</strong>{ </pre><pre>    public <strong>synchronized</strong> int <strong>methodOne</strong>(args){ </pre><pre>        …… </pre><pre>    }<br>}</pre><h3>Synchronizing Threads</h3><p>The Thread class implements several methods that allow us to control when and how threads wait for other threads.</p><p>The first method is join(). This method is called by a thread using another thread’s reference when it wants to wait for that thread to terminate. This method throws an InterruptedException when the thread that it is waiting for is interrupted by the interrupted() method.</p><p>In the following example, the main thread would wait for the thread1 thread to terminate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/708f6e44bbe741e96b8e42362f8f183b/href">https://medium.com/media/708f6e44bbe741e96b8e42362f8f183b/href</a></iframe><p>Another important method is wait(). This method should be called inside a synchronized method. If the thread that executes the wait method is interrupted, it throws an InterruptedException. The JVM adds the thread that executes the wait method to a waiting list associated with the object that makes the call. Then, the lock associated with the object is opened and it will be closed when returning from the call.</p><p>The last method we will cover is notify(). When called, it will activate a thread that is waiting on the waiting list. The thread that will be started is not determined, but it must wait until it can close the lock again. A similar method is notifyAll(), which activates all the threads on the waiting list.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f706fc44d13" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/understand-threads-and-threading-in-java-8f706fc44d13">Understand Threads and Threading in Java</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get a Full-Stack Development Environment Ready With Docker Compose]]></title>
            <link>https://medium.com/better-programming/get-a-full-stack-development-environment-ready-with-docker-compose-b88d4a56a7f2?source=rss-baa7cd4fce4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b88d4a56a7f2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Uxío García Andrade]]></dc:creator>
            <pubDate>Tue, 14 Jan 2020 01:53:09 GMT</pubDate>
            <atom:updated>2020-01-14T01:53:09.906Z</atom:updated>
            <content:encoded><![CDATA[<h4>Start developing your new full-stack app in a containerized environment with little to no previous Docker experience</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMI20DDdWnKf5PzFK7BDxQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">chuttersnap</a> on <a href="https://unsplash.com/s/photos/stack?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This article will cover how to set up all the containers you need to start developing a full-stack web app.</p><p>Although, here, I will use specific technologies, the technologies running in each container could be replaced by your preferred ones with some minor changes.</p><p>On the other hand, note that this article will only cover the set up of the development. All the Dockerfiles included in this article are not production-ready.</p><p>Now, let’s have a look at what our infrastructure will look like. To do so, I will first show the file structure of our project:</p><pre><strong>app</strong><br>├── docker-compose.yaml<br>├── api<br>│   ├── Dockerfile.dev<br>│   ├── go.mod<br>│   └── main.go<br>├── client<br>│   ├── Dockerfile.dev<br>│   └── <em>create-react-app files and directories</em><br>└── nginx<br>    ├── default.conf<br>    └── Dockerfile.dev</pre><p>In this structure, we can observe that we will be using <a href="https://golang.org/">Go lang</a> (and the web framework <a href="https://github.com/gin-gonic/gin">Gin</a>) for our back end and <a href="https://reactjs.org/">React</a> for the front end.</p><p>Moreover, I will add two other services, a database and a cache. Our docker-compose file will include a <a href="https://www.postgresql.org/">Postgres</a> container, as well as a <a href="https://redis.io/">redis</a> one, to show how these services would be integrated into our application.</p><p>On the other hand, I’ve also decided to use a <a href="https://www.nginx.com/">NGINX</a> server. Although this would not be necessary for our development environment, as we could be using our local machine as a development server, this server will disappear in production, so using NGINX in our docker-compose build will make it easier to transition from this development build to a production-ready one.</p><p>Firstly, we will create the Dockerfile for our React client. To do that, first navigate to the root directory of your project (in this tutorial, the app/ directory will play that role) and run the following command:</p><pre>npx create-react-app client</pre><p>Once the command has finished its execution, we will have our basic React client-ready. The only problem with starting it with the previous command is that, by default, it creates a Git repository in the client/<em> </em>directory, so make sure to delete it<em>.</em></p><p>Apart from that, we are ready to create our first Dockerfile, so we will add the following lines to a file called Dockerfile.dev, which will be located in the client/ directory<em>.</em></p><pre>FROM node:alpine</pre><pre>WORKDIR /app</pre><pre>COPY ./package.json ./</pre><pre>RUN npm install</pre><pre>COPY . .</pre><pre>CMD [“npm”,”run”, “start”]</pre><p>Although this is a basic Dockerfile, I will emphasize one best practice that is worth noting: to avoid the package.json file getting recached every time we update a file, we split its copy from the other files.</p><p>This way, we can avoid running the npm install<em> </em>command in each build, which is one of the most time-consuming steps of building a Docker image.</p><p>On the other hand, it is usually interesting to specify the version of the image we want in our build, as it enhances the consistency of our containers.</p><p>This time, I’ve chosen the node:alpine one, which is a minimal image, i.e., it contains the bare minimum to run npm.</p><p>Moving to the back-end side, let’s first create a basic server with Go’s <a href="https://github.com/gin-gonic/gin">Gin</a> web framework. Navigate to the app/api directory and create a file main.go<em>:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3efaa54d2a5d9af413bd93527b59bf8b/href">https://medium.com/media/3efaa54d2a5d9af413bd93527b59bf8b/href</a></iframe><p>We will also need a go.mod file, which is the equivalent of package.json in npm.</p><pre>module github.com/&lt;yourUsername&gt;/&lt;nameOfYourProject&gt;</pre><pre>go 1.13</pre><pre>require github.com/gin-gonic/gin v1.5.0</pre><p>Once we have both files ready, we can start writing our Dockerfile.dev file in the API directory:</p><pre>FROM golang:latest</pre><pre>ENV GO111MODULE=on</pre><pre>WORKDIR /app</pre><pre>COPY ./go.mod .</pre><pre>RUN go mod download</pre><pre>RUN go get github.com/pilu/fresh</pre><pre>COPY . .</pre><pre>CMD [&quot;fresh&quot;]</pre><p>As you may have already noticed, in this Dockerfile, we follow the same best practices as in the other one.</p><p>We have split the go.mod copy from the other files, as this will prevent the execution of the go mod download command<em> </em>when no new dependencies have been added.</p><p>On the other hand, you may have noticed that the default command this container will be running is fresh<em> </em>instead of go run main.go<em>.</em></p><p>However, if you have ever used Gin, you already know that hot reload is not a default feature in this framework. As this is a desired characteristic in a development environment, we will use <a href="https://github.com/gravityblast/fresh">fresh</a>, which is a command-line tool that builds and restarts a web application every time a file is updated.</p><p>Finally, the only step before getting into our docker-compose file is setting up the NGINX server. First of all, create an nginx/ directory with a file named default.conf inside;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fe1120ae539df03c6943a775810d036/href">https://medium.com/media/5fe1120ae539df03c6943a775810d036/href</a></iframe><p>In short, this file will tell NGINX to create a server listening on port 80, and then redirect the requests to one of its upstream servers.</p><p>If the request’s endpoint starts with /api/,<em> </em>NGINX<em> </em>will proxy pass the request to our API server.</p><p>If the endpoint is any other one, the client-server will be the one getting the request. The other rule is related to <a href="https://github.com/sockjs/sockjs-node">WebSockets (SockJS)</a>, but initially, it wouldn’t be a big deal if you decided to skip that one.</p><p>The Dockerfile.dev for the NGINX server will be the simplest one:</p><pre><strong>FROM</strong> nginx</pre><pre><strong>COPY</strong> ./default.conf /etc/nginx/conf.d/default.conf</pre><p>Now that we are done with all our Dockerfiles, we can move on to the last step: the Docker Compose configuration.</p><p>Docker Compose is a tool for defining and running multi-container Docker applications.</p><p>In this file, we define the Dockerfiles we want to build our containers from, the ports they have to expose, the volumes they have to define, etc.</p><p>Although this file may seem a little intimidating at first, it’s actually a compilation of all the tools you are probably already familiar with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/556bf2371e249c0bfde82faa2208c9f6/href">https://medium.com/media/556bf2371e249c0bfde82faa2208c9f6/href</a></iframe><p>The first thing that I would like to address is the different restart policies we can assign to the Docker containers.</p><p>There are 4 policies: <em>no, always, on-failure, unless-stopped</em>. Note that I’ve assigned the <em>always</em> one to the NGINX server, and <em>on-failure</em> to the API server, but actually, unless you have a reason to restart another service, the only one that is interesting in our application is the one for the NGINX server.</p><p>As our NGINX server is the one redirecting traffic to the other containers, there’s no way any other service can work while it is down.</p><p>Furthermore, I’ve added port mapping to all the containers. Although the ports I’ve chosen are mostly the standard ones, they may be changed to any other port you prefer.</p><p>On the other hand, the volumes added here satisfy one of the following two needs: they either enable hot-reloading (API and client containers), or they allow data persistence (redis and Postgres containers).</p><p>Finally, passing environment variables to the containers using Docker Compose is fairly easy.</p><p>As it can be observed, it is possible to just add the variable itself in the docker-compose file, or, even better, create a .env<em> </em>file where you would store the variables, especially the ones that should not be shared (passwords, secret keys…).</p><p>Once you are done with all the required files, it’s time to run your project and test that everything is working properly. To do that, just run the following command in the root directory:</p><pre>docker-compose up --build</pre><p>You can see if the containers have been successfully created by running:</p><pre>docker-compose ps</pre><p>When you are done with developing, you can stop all the containers at once by running:</p><pre>docker-compose down</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b88d4a56a7f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/get-a-full-stack-development-environment-ready-with-docker-compose-b88d4a56a7f2">Get a Full-Stack Development Environment Ready With Docker Compose</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a Full-Stack Go and React App on Kubernetes]]></title>
            <link>https://medium.com/better-programming/deploy-a-full-stack-go-and-react-app-on-kubernetes-4f31cdd9a48b?source=rss-baa7cd4fce4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f31cdd9a48b</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Uxío García Andrade]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 14:54:12 GMT</pubDate>
            <atom:updated>2021-02-13T10:14:13.111Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to deploy a Gin-Gonic’s Go backend and a React web app on Kubernetes using minikube and kubectl</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pHchtcOYJDVcoVcWPoarnA.jpeg" /><figcaption><a href="https://unsplash.com/photos/4I41IQtmSs0">https://unsplash.com/photos/4I41IQtmSs0</a></figcaption></figure><p>First of all, we create the Docker images we need for our deployment and push them to Docker Hub.</p><p>We will start with the back end container. In your root directory, create a directory named api, which will contain all the files related to the back end. As we will be using <a href="https://gin-gonic.com/">Gin-Gonic</a> as our Go framework, we will create a go.mod file (note that you should change the name of the module):</p><pre><strong>module</strong> github.com/uxioandrade/go-react-kubernetes-tutorial</pre><pre><strong>go</strong> 1.13</pre><pre><strong>require</strong> github.com/gin-gonic/gin v1.5.0</pre><p>Now that we have our go.mod file set up, let’s create a main.go<em> </em>file, which will be essentially a basic Gin-Gonic server example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3efaa54d2a5d9af413bd93527b59bf8b/href">https://medium.com/media/3efaa54d2a5d9af413bd93527b59bf8b/href</a></iframe><p>The last step related to the back end is to create a Dockerfile<em>. </em>Again, it will be a minimalist one, having the bare minimum required to run our server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4af84c8f8f8105c1d4a0062884e7629/href">https://medium.com/media/e4af84c8f8f8105c1d4a0062884e7629/href</a></iframe><p>Finally, we will run two commands to push our Docker image to Docker Hub. Note that for these commands to work, you must be logged in to Docker Hub.</p><pre><strong>docker</strong> build -t uxioandrade/tutorial-api</pre><pre><strong>docker</strong> push uxioandrade/tutorial-api</pre><p>Now that we have our back end ready, let’s move on to the React app. Navigate to the root directory of the project and run the following command:</p><pre><strong>npx</strong> create-react-app client</pre><p>Again, we’ll try to keep our code as simple as possible. Nevertheless, we’ll install the axios library to make requests.</p><pre><strong>npm</strong> i axios  --save</pre><p>Next, navigate to the client folder, and open the src/App.js<strong> </strong>file — the only file we need to modify. In the App component, we make a request to the back end to test that everything is working properly. The following code will satisfy our needs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a637bb32600d87552576d871f22a847/href">https://medium.com/media/2a637bb32600d87552576d871f22a847/href</a></iframe><p>Finally, let’s create a Dockerfile for the client. As we can see, it looks similar to the back end one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1376ba2155f60ca973eda8113975f84/href">https://medium.com/media/b1376ba2155f60ca973eda8113975f84/href</a></iframe><p>As we did with our back end image, let’s push it to Docker Hub:</p><pre><strong>docker</strong> build -t uxioandrade/tutorial-client</pre><pre><strong>docker</strong> push uxioandrade/tutorial-client</pre><p>Now we have everything we need to start deploying our App on Kubernetes. In fact, we could run both containers and see that they work.</p><p>However, we would need make some changes in order to get the two containers to communicate with each other. For example, one easy solution (though not the most elegant) would be to change the endpoint of the GET request in the App.js file. Another option would be to use docker-compose with a NGINX container, but this would be a completely over-the-top solution for our use case.</p><p>In this piece I’ll be using minikube and kubectl, so you need to have both tools installed in your computer. After installing them, run the following command to run minikube:</p><pre>minikube start</pre><p>Once you have that, create a folder named k8s<em>, </em>where we will allocate all the files related to the Kubernetes deployment. Moreover, I will add a postgres service, which will be useful to show how to create a <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/">Persistent Volume Claim</a>.</p><p>We start by creating the config files related to both the API and client deployments. But first, let’s clarify exactly what we mean by deployment in this context. A deployment is a type of object that maintains a set of identical pods, ensuring that they have the correct configuration. With that in mind, let’s see what our deployment files will look like.</p><p>In the API Deployment (api-deployment.yaml) we’ve added some Environment variables related to the Postgres service. Note that in a real scenario, we would want to create a <a href="https://kubernetes.io/docs/concepts/configuration/secret/">secret</a> to store the postgres password.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db55bc698723b7c92e16e379ed37420b/href">https://medium.com/media/db55bc698723b7c92e16e379ed37420b/href</a></iframe><p>The client deployment (client-deployment.yaml) will look like a simplified version of the previous one, as we aren’t using any env variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/228906f8763ef011f9374769767adf67/href">https://medium.com/media/228906f8763ef011f9374769767adf67/href</a></iframe><p>On the other hand, we also need a deployment for the postgres service. However, we must create some sort of persistent storage service before, otherwise, we would lose all our data once the pod is shut down. For that purpose, we will use a Persisent Volume Claim, as I mentioned before. The database-persistent-volume-claim.yaml file will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94cb0243c2a8d82c001fce197c90a5b1/href">https://medium.com/media/94cb0243c2a8d82c001fce197c90a5b1/href</a></iframe><p>Note that the 1Gi size is arbitrary, so we can change it to any number that better fits our needs.</p><p>After having figured out the persistence of our database, the deployment we have to write is again similar to the previous one, with the exception that we must add the Persistent Volume Claim part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/837240a5a897bcc7ec1bab662335c245/href">https://medium.com/media/837240a5a897bcc7ec1bab662335c245/href</a></iframe><p>After completing this, we are done with all the deployments we needed. However, these deployments are isolated — they can’t communicate with any outside service. To enable any communication, we will use a new service, called ClusterIP. The ClusterIPs for the three deployments are going to have the exact same structure, we will just need to modify some parameters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b8766c105f6cd8426867cf054924e6a/href">https://medium.com/media/2b8766c105f6cd8426867cf054924e6a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b8f79288383c2e45a0507c59e5d94df/href">https://medium.com/media/4b8f79288383c2e45a0507c59e5d94df/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ab81591b8fccceadbc6be938285b92b/href">https://medium.com/media/0ab81591b8fccceadbc6be938285b92b/href</a></iframe><p>We’re almost done!</p><p>The only thing to do is to create one last service: an Ingress Service. This manages external access to the services in a cluster. More specifically, we will be using the NGINX Ingress Controller. Look at <a href="https://kubernetes.github.io/ingress-nginx/deploy/#minikube">this guide</a> to see how to enable it. However, in our case we can do it with two commands:</p><pre><strong>kubectl</strong> apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/master/deploy/static/mandatory.yaml</pre><pre><strong>minikube</strong> addons enable ingress</pre><p>We are ready to write our last config file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e05c2f3a74fa402cdcb068a8c909395c/href">https://medium.com/media/e05c2f3a74fa402cdcb068a8c909395c/href</a></iframe><p>If you made it this far, congratulations, you have all your configuration ready to be run. To do so, just run the following command from the root of your project:</p><pre><strong>kubectl</strong> apply -f k8s</pre><p>To check if everything is working as expected, you may run some of the following commands:</p><pre><strong>kubectl</strong> get all</pre><pre><strong>minikube</strong> dashboard</pre><p>If you run the first one, you should check that the three pods are running and that the ClusterIPs you’ve created are also there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kN22CE6gA5_t5W_xKSLdyQ.png" /><figcaption>kubectl get all output</figcaption></figure><p>On the other hand, if you opt for the second command, you can navigate the minikube dashboard in an intuitive way and check that the Kubernetes cluster is behaving accordingly.</p><p>Finally, let’s see if our application is indeed running. Get the minikube’s ip in your local machine with this command:</p><pre><strong>minikube</strong> ip</pre><p>Then navigate to that IP in your preferred browser. If you see something similar to the following, you have successfully deployed a full-stack Golang and React application on Kubernetes!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kW_vHQQ52AiygTuaSAWnMg.png" /><figcaption>Finished Deployment</figcaption></figure><p>If you have any doubts or think that you may have made some mistakes following the tutorial, you can find the code in this <a href="https://github.com/UxioAndrade/tutorials/tree/main/go-react-kubernetes">Github repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f31cdd9a48b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/deploy-a-full-stack-go-and-react-app-on-kubernetes-4f31cdd9a48b">Deploy a Full-Stack Go and React App on Kubernetes</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Session caching in Go with Gin Sessions, Redis and Docker]]></title>
            <link>https://uxioandrade.medium.com/implementing-session-caching-in-go-with-gin-sessions-redis-and-docker-838608f6cca?source=rss-baa7cd4fce4------2</link>
            <guid isPermaLink="false">https://medium.com/p/838608f6cca</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Uxío García Andrade]]></dc:creator>
            <pubDate>Sun, 15 Dec 2019 17:48:56 GMT</pubDate>
            <atom:updated>2021-02-13T10:12:03.208Z</atom:updated>
            <content:encoded><![CDATA[<h4>Go’s web framework Gin-Gonic provides developers with a wide range of approaches to keep track of users’ sessions. In this article I will discuss the one involving Redis.</h4><p>While trying to implement <strong>gin’s sessions with Redis in Go</strong>, I went through some issues that could have been avoided hadn’t there been a lack of examples that helped me understand how to implement it. So, once I figured it out, I thought it would be a good idea to make a post out of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNd4CpLwstZWWvSawZlCDg.jpeg" /><figcaption><a href="https://unsplash.com/photos/WiONHd_zYI4">https://unsplash.com/photos/WiONHd_zYI4</a></figcaption></figure><p>This article will cover how to implement a basic <strong>API with user authentication and session cache in Go</strong>. For that purpose, we will use the Gin-gonic framework and Redis, running both services in separate docker containers.</p><p>First of all, let’s <strong>set up our environment</strong>. In your working directory, create a file name <em>go.mod </em>and add the following two lines to the file:</p><pre><strong>module</strong> github.com/username/repositoryname</pre><pre><strong>go</strong> 1.13</pre><p>Now, create a file called <em>main.go</em>, and paste the following code (gin’s official documentation first example).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eab821909967d1e7f719cbe586239d0a/href">https://medium.com/media/eab821909967d1e7f719cbe586239d0a/href</a></iframe><p>As we said before, we plan to dockerize all our services, so now let’s create a <em>Dockerfile.dev</em> file to build our gin container.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aea0d5c243e3eb945688ab58e59af298/href">https://medium.com/media/aea0d5c243e3eb945688ab58e59af298/href</a></iframe><p>Note that we don’t copy all our files before running <em>go mod</em>, as that would imply that <strong>we wouldn’t be able to use docker’s cache</strong> when running the <em>go mod download. </em>On the other hand, in order to enable hot reload, we will run our server with <a href="https://github.com/gravityblast/fresh">fresh</a>.</p><p>Once we have our Dockerfile ready, we can test if it is working properly. First, let’s build the container.</p><pre><strong>docker</strong> build -t uxioandrade/gin-sessions -f Dockerfile.dev .</pre><p><em>After the -t tag you can name the image in any way you want, but remember to use the same name in the docker run command:</em></p><pre><strong>docker</strong> run -p 8080:8080 uxioandrade/gin-sessions</pre><p>Once the container is up, you can test that everything is running as it should with the following command:</p><pre><strong>curl</strong> localhost:8080/ping</pre><p>If you receive a {“message”:”pong”} as a response, everything is okay.</p><p>Now that we have our Go container up and running, let’s see how we can <strong>create the Redis one and establish a connection between both of them</strong>. For that purpose, we will just create a <em>docker-compose.yml </em>file as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1196ae1a27eb42be9542b967cb280b2/href">https://medium.com/media/a1196ae1a27eb42be9542b967cb280b2/href</a></iframe><p>After doing that, we may start both services by running the following command:</p><pre>docker-compose up </pre><p>Once you check that both services are running, let’s go back to our <em>main.go </em>file. First of all, we must <strong>initialize our redis store</strong>, and indicate our gin router to use it for all our routes. Then, we will set up routes for logging in and out, and then we will create another group which will use a <strong>middleware function which checks if the user is logged in</strong>. If that’s not the case, the middleware function will return a JSON error and <strong>prevent the server from getting to the handler function</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd506e1ad2ecb246fc5838a3943f5725/href">https://medium.com/media/cd506e1ad2ecb246fc5838a3943f5725/href</a></iframe><p>Now, let’s define the <strong>userController and the two controller functions</strong>. Note that all the code related to controllers should be in a different package, but for the purpose of simplicity, I just added all the code to the <em>main.go</em> file. Moreover, in a real world application, we would implement the login feature by connecting to a database and validating the request’s credentials, but here I skipped that part.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22703fa80f95d3e8637107ebaa2e7a69/href">https://medium.com/media/22703fa80f95d3e8637107ebaa2e7a69/href</a></iframe><p>In the end, the only remaining step is to test that everything is working. We will use the curl command to send requests to our server. However, <strong>we need some extra file to keep track of the cookies</strong>, so that our server can recognize the user’s session. One simple solution would be to create a cookies.txt file, and run the following commands (<em>remember that you need to be running the containers with docker-compose up</em>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*QA_e7jPduKUa_0UlJrr4Ug.png" /><figcaption>Testing our implementation</figcaption></figure><p>As we can see, the <strong>first time</strong> we tried to send a get request to the /auth/ping endpoint, we got an error stating that we were <strong>not authed</strong>. Then, once we log in, this error goes away and we can access the ping function. After that, we log out and get the error back.</p><p>Gin’s sessions library is such a powerful library which allows developers to keep track of user authentication in Redis with a few lines of code. <strong>In case you have had any issues with this tutorial</strong>, you can find all the code in the <a href="https://github.com/UxioAndrade/tutorials/tree/main/go-sessions-tutorial">this repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=838608f6cca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>