<?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 Yasmin Guimarães  on Medium]]></title>
        <description><![CDATA[Stories by Yasmin Guimarães  on Medium]]></description>
        <link>https://medium.com/@yasmin_12961?source=rss-4bed3cb88550------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Orf1MW0hS1J8VFS6Ff0cqw.jpeg</url>
            <title>Stories by Yasmin Guimarães  on Medium</title>
            <link>https://medium.com/@yasmin_12961?source=rss-4bed3cb88550------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:41:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yasmin_12961/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Diagnose and Avoid Race Conditions When Using Goroutines in Go]]></title>
            <link>https://medium.com/@yasmin_12961/how-to-diagnose-and-avoid-race-conditions-when-using-goroutines-in-go-ecbb1fc5cc09?source=rss-4bed3cb88550------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecbb1fc5cc09</guid>
            <category><![CDATA[mutex]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[golang-mutex]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Yasmin Guimarães ]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 20:45:16 GMT</pubDate>
            <atom:updated>2025-07-25T20:45:16.876Z</atom:updated>
            <content:encoded><![CDATA[<h4>Go’s concurrency model with goroutines is powerful, but it also introduces risks like race condition.</h4><blockquote>Let’s kick things off with a real question: What kind of Go code is most likely to get wrecked by race conditions?</blockquote><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>type SyncCounter struct {<br> sync.Mutex<br> Value int<br>}<br><br>var counter SyncCounter<br><br>func main() {<br> var wg sync.WaitGroup<br><br> for i := 0; i &lt; 10; i++ {<br>  wg.Add(1)<br>  // opening a new goroutine to increment the counter variable that is shared<br>  go incremental(&amp;counter, &amp;wg)<br> }<br><br> wg.Wait()<br> fmt.Println(&quot;Final counter:&quot;, counter.Value)<br>}<br><br>func incremental(syncCounter *SyncCounter, wg *sync.WaitGroup) {<br> defer wg.Done()<br> for i := 0; i &lt; 1000; i++ {<br>  syncCounter.Value++<br> }<br>}</pre><p>Yes ! Exactly, a code like this, what are we doing here ?</p><blockquote>1. ⁠We are creating 10 go routines to increment a shared variable.</blockquote><blockquote>2. This introduces a race condition because multiple goroutines access and modify ‘counter’ concurrently without synchronization.</blockquote><p>The answer expected from the counter should be = 10000, but, with the actual status of the code that is not what we got ! After running that 3 times I got 3 different results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MyqXPcnY2n1ih4GxaCDH2w.png" /></figure><blockquote>Okay, I’ve got this problem, how can I diagnose a potential concurrency issue <em>before</em> it blows up in production? And once I know it’s there, how do I fix it?</blockquote><ol><li>How to Detect Race Conditions ?</li></ol><p>You can simply run the following command to detect race conditions in your code:</p><pre>go run -race main.go</pre><p>If a race condition exists, Go will alert you with a warning message like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*cemvUVPwudFaLKMJngX-6A.png" /></figure><p>2. How to fix it ?</p><p>One way to stop the madness? Wrap that part of your code in a <strong>mutex, </strong>short for <em>mutual exclusion</em>. Think of a mutex as a <strong>bouncer at the door</strong> of a club: only one goroutine can enter the “critical section” at a time. If another goroutine tries to enter while it’s already occupied, it has to <strong>wait outside</strong> until the first one is done and leaves (unlocks the door).</p><p>Using a mutex allows you to <strong>lock</strong> a section of your code so that <strong>only one goroutine can execute it at a time</strong>. Once the goroutine is done, it <strong>unlocks</strong> it, letting the next one in line take over. This ensures that your program behaves <strong>safely and predictably</strong>, even when running lots of goroutines in parallel.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>type SyncCounter struct {<br> sync.Mutex<br> Value int<br>}<br><br>var counter SyncCounter<br><br>func main() {<br> var wg sync.WaitGroup<br><br> for i := 0; i &lt; 10; i++ {<br>  wg.Add(1)<br>  // opening a new goroutine to increment the counter variable that is shared<br>  go incremental(&amp;counter, &amp;wg)<br> }<br><br> wg.Wait()<br> fmt.Println(&quot;Final counter:&quot;, counter.Value)<br>}<br><br>func incremental(syncCounter *SyncCounter, wg *sync.WaitGroup) {<br> defer wg.Done()<br> for i := 0; i &lt; 1000; i++ {<br>  syncCounter.Lock()<br>  // lock before add a value to the counter<br>  syncCounter.Value++<br>  // unlock after the operation being done<br>  syncCounter.Unlock()<br> }<br>}</pre><p>Now, if you run</p><pre>go run main.go</pre><p>You should get the right expected value for the counter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*UA3xsUQgELb1sW_hLColjQ.png" /></figure><p>Github repository: <a href="https://github.com/yasming/goroutines-concurrency">https://github.com/yasming/goroutines-concurrency</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecbb1fc5cc09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide: Deploying a Golang Application to AWS Elastic Container Service]]></title>
            <link>https://medium.com/@yasmin_12961/step-by-step-guide-deploying-a-golang-application-to-aws-elastic-container-service-2b5e95965600?source=rss-4bed3cb88550------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b5e95965600</guid>
            <category><![CDATA[web-scrapping]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[elastic-container-service]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[ecs-fargate]]></category>
            <dc:creator><![CDATA[Yasmin Guimarães ]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 18:59:49 GMT</pubDate>
            <atom:updated>2025-02-03T18:59:49.886Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>For beginners looking to enhance their skills in modern software deployment, learning how to deploy a Golang application to AWS ECS using AWS ECR is invaluable. This guide provides a clear, step-by-step process, making it easy to understand the intricacies of containerization and cloud deployment. By mastering these skills, you’ll be able to deploy scalable and secure applications, setting a strong foundation for your future projects in the cloud.</blockquote><blockquote><strong>Let’s begin by creating our local Golang application.</strong></blockquote><ol><li><strong>main.go:</strong></li></ol><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>)<br><br>func main() {<br>    SetInterval(<br>       func() {<br>          fmt.Println(&quot;-- Deploying to aws ecs --&quot;)<br>       },<br>       24*time.Hour,<br>    )<br>    for {}<br>}<br><br>func SetInterval(action func(), interval time.Duration) func() {<br> quit := make(chan struct{})<br><br> go func() {<br>  // Run the action immediately<br>  action()<br>  ticker := time.NewTicker(interval)<br>  defer ticker.Stop()<br>  for {<br>   select {<br>   case &lt;-ticker.C:<br>    action()<br>   case &lt;-quit:<br>    return<br>   }<br>  }<br> }()<br><br> return func() {<br>  close(quit)<br> }<br>}</pre><p>This application will print a message to the terminal, keep the container running, and repeat the message every 24 hours.</p><blockquote><strong>Docker image and push our image to Aws Elastic Container Registry. (</strong>A fully managed Docker container registry that makes it easy to store, manage, and deploy container images.<strong>)</strong></blockquote><ol><li>Let’s create our Dockerfile under the docker-prod folder</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*YnXkcGcLVIER9BRAXnFHaA.png" /></figure><pre>FROM golang:1.21.6 as builder<br><br>WORKDIR /app<br><br>COPY . .<br><br>RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o server .<br><br>ENTRYPOINT [&quot;/app/server&quot;]<br><br>FROM scratch<br><br>COPY --from=builder /app/server /server<br><br>ENTRYPOINT [&quot;/server&quot;]</pre><p>2. Run:</p><pre>docker build -f docker-prod/Dockerfile -t golang-production:latest .</pre><p>3. After you get your image built go to <strong>Amazon Elastic Container Registry </strong>and configure it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*krZZaxYIAo25gOIpbz7uEg.png" /></figure><p>4. Copy the url that is highlighted in red</p><blockquote>After this you should see your private repository created in <strong>Amazon Elastic Container Registry</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBfkkt4xnomzdNj4ZJlUzQ.png" /></figure><p>5. Run:</p><pre>docker tag golang-production:latest 111111.dkr.ecr.us-east-2.amazonaws.com/golang-production:latest</pre><blockquote>Replace <strong>111111.dkr.ecr.us-east-2.amazonaws.com</strong> with the URL you copied from ECR creation</blockquote><p>6. Login into <strong>Amazon Elastic Container Registry</strong> by your terminal (for this you need the aws cli installed) running:</p><pre>aws ecr get-login-password --profile personal-aws | docker login --username AWS --password-stdin 111111.dkr.ecr.us-east-2.amazonaws.com</pre><blockquote>You should see the follow output:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*1JVafBgXdNBUdAQXjGkexA.png" /></figure><blockquote>On this command you are willing to replace: <strong>personal-aws </strong>by the name of your aws configurations stored on:<strong> ~/.aws/credentials</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*n5SlRI9kJDPJBCFTUGhvKA.png" /></figure><blockquote>and replace <strong>111111.dkr.ecr.us-east-2.amazonaws.com</strong> with the URL you copied from ECR creation</blockquote><p>7. Push your image to your repository</p><pre>docker push 111111.dkr.ecr.us-east-2.amazonaws.com/golang-production:latest</pre><blockquote>You should have this output if everything went ok:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*KlppVPN2oVh6XrrOJEc2Dw.png" /></figure><blockquote>On this command you are willing to replace<strong> 111111.dkr.ecr.us-east-2.amazonaws.com</strong> with the URL you copied from <strong>ECR</strong> creation</blockquote><blockquote><strong>Amazon Elastic Container Service</strong></blockquote><ol><li>In AWS go to <strong>Amazon Elastic Container Service &gt; Task definitions -&gt; Create new task definition</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*yS3e6n8CO8Luq5HGulYl9Q.png" /></figure><blockquote>Using AWS Fargate over EC2 to simplify container management by eliminating the need to provision, configure, and scale underlying infrastructure, allowing you to focus on application development.</blockquote><p>2. On <strong>Task definition family </strong>and in<strong> Container details -&gt; name </strong>put the name of your preference,</p><p>3. On <strong>Container Details -&gt; Image URI </strong>put the url from<strong> Amazon Elastic Registry</strong></p><blockquote>After click in the create button you should see something similar to:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oeFvWnh23shEcFMIHj4jDA.png" /></figure><blockquote><strong>Cluster</strong></blockquote><ol><li>In AWS go to <strong>Amazon Elastic Container Service -&gt; Clusters -&gt; Create cluster</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*U7R95hbTIamn1OwwXcnqKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zySdfSdY8DUq_Rf666P81w.png" /></figure><p>2. Click on view cluster, then on <strong>create</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZLNMSb2ilf7w9FwAzGJJQ.png" /></figure><p>3. Setup your service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*Wcg3HyXa83JffK2BpOiynw.png" /></figure><p>What is in red should be replaced by the name of you preference, then, click in the <strong>create</strong> button.</p><p>After a while you should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zpr1oM9a4WIa1Pm-gMsJ3Q.png" /></figure><p>4. Click on <strong>view service -&gt; logs</strong>, then you should have the confirmation our service is deployed to correctly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0MQfwbHWGu0uqgHEVIO-Iw.png" /></figure><p>Now you have your application deployed to a production environment 🥳</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b5e95965600" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to reduce code duplication in rspec with shared_examples.]]></title>
            <link>https://medium.com/@yasmin_12961/how-to-reduce-code-duplication-in-rspec-with-shared-examples-74973daa4a6c?source=rss-4bed3cb88550------2</link>
            <guid isPermaLink="false">https://medium.com/p/74973daa4a6c</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[shared-examples]]></category>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Yasmin Guimarães ]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 16:48:13 GMT</pubDate>
            <atom:updated>2023-04-28T16:48:13.315Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Reducing code duplication in RSpec can help make your tests more concise and maintainable. One way to achieve this is by using <strong>shared examples</strong>. Shared examples allow you to define reusable blocks of code that can be shared across multiple tests. This can save time and effort, as well as improve the readability and clarity of your test code.</blockquote><blockquote><strong>So, the business rule we will be dealing with in our code is:</strong></blockquote><blockquote>1. We need to create an activity after each user and task is created.</blockquote><blockquote><strong>With that said, we will need have 3 models and migrations for that:</strong></blockquote><blockquote>1. User</blockquote><blockquote>2. Task</blockquote><blockquote>3. Activity</blockquote><blockquote><strong>Models and Migrations</strong></blockquote><ol><li><strong>User</strong></li><li><strong>rails generate model User name:string</strong></li><li>Keep just the migration and model files</li></ol><pre>class User &lt; ApplicationRecord<br>end</pre><pre>class CreateUsers &lt; ActiveRecord::Migration[7.0]<br>  def change<br>    create_table :users do |t|<br>      t.string :name<br>      t.timestamps<br>    end<br>  end<br>end</pre><ol><li><strong>Task</strong></li><li><strong>rails generate model Task description:string</strong></li><li>Keep just the migration and model files</li></ol><pre>class Task &lt; ApplicationRecord<br>end</pre><pre>class CreateTasks &lt; ActiveRecord::Migration[7.0]<br>  def change<br>    create_table :tasks do |t|<br>      t.string :description<br>      t.timestamps<br>    end<br>  end<br>end</pre><ol><li>Activity</li><li><strong>rails generate model Activity</strong></li><li>keep just migration and model files.</li></ol><pre>class Activity &lt; ApplicationRecord<br> belongs_to :origin, polymorphic: true<br>end</pre><pre>class CreateActivities &lt; ActiveRecord::Migration[7.0]<br>  def change<br>    create_table :activities do |t|<br>      t.references :origin, polymorphic: true, index: true, null: false<br>      t.timestamps<br>    end<br>  end<br>end</pre><blockquote><strong>Write tests</strong></blockquote><blockquote>So, let’s start writing the tests for our application. As we know, we need a test to validate whether an activity is created after a user and a task are created.</blockquote><blockquote>With RSpec installed, let’s create your model’s test in the following folder:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*tLnuso0KoaX0CHMYU2iUwA.png" /></figure><pre>require &#39;rails_helper&#39;<br><br>RSpec.describe User, type: :model do<br>  describe &quot;#after_create&quot; do<br>    it &quot;should create an activity&quot; do<br>      user = User.create!(name: &quot;test&quot;)<br>      expect(Activity.count).to eq(1)<br>      expect(Activity.first.origin).to eq(user)<br>    end<br>  end<br>end</pre><pre>require &#39;rails_helper&#39;<br><br>RSpec.describe Task, type: :model do<br>  describe &quot;#after_create&quot; do<br>    it &quot;should create an activity&quot; do<br>      task = Task.create!(description: &quot;test&quot;)<br>      expect(Activity.count).to eq(1)<br>      expect(Activity.first.origin).to eq(task)<br>    end<br>  end<br>end</pre><blockquote><strong>Add after_create in models</strong></blockquote><pre>class User &lt; ApplicationRecord<br>  after_create :create_activity<br>end</pre><pre>class Task &lt; ApplicationRecord<br>  after_create :create_activity<br>end</pre><p>And in our <strong>ApplicationRecord</strong> file:</p><pre>class ApplicationRecord &lt; ActiveRecord::Base<br>  primary_abstract_class<br><br>  def create_activity<br>    Activity.create(origin: self)<br>  end<br>end</pre><blockquote><strong>Run tests</strong></blockquote><ol><li>Now, if we run <strong>rspec</strong> in the console, we should see this:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*L3TDfGcgki6JM-fVbZkRJg.png" /></figure><blockquote><strong>Refactor tests</strong></blockquote><ol><li>Now that our tests for the business rule are passing, let’s refactor our tests to avoid duplication. Currently, both the <strong>User</strong> and <strong>Task</strong> tests need to validate the creation of an associated <strong>Activity</strong>. We can extract this logic into a <strong>shared example</strong>, which will be included in <strong>both tests</strong>, reducing the repetition in our code.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*_PQmYVk6ROBODIvGX40yhw.png" /></figure><pre>RSpec.shared_examples &quot;activity created after model created&quot; do |model_class, attributes|<br>  describe &quot;#after_create&quot; do<br>    it &quot;should create an activity after model created&quot; do<br>      model_instance = model_class.create!(attributes)<br>      expect(Activity.count).to eq(1)<br>      expect(Activity.first.origin).to eq(model_instance)<br>    end<br>  end<br>end</pre><p>2. Now that we have created our <strong>shared_example</strong>, let’s adjust our tests accordingly:</p><pre>require &#39;rails_helper&#39;<br>require_relative &#39;../support/shared_examples/activity_created_after_model_created&#39;<br><br>RSpec.describe User, type: :model do<br>  describe &quot;#after_create&quot; do<br>    it_behaves_like &quot;activity created after model created&quot;, User, { name: &quot;test&quot; }<br>  end<br>end</pre><pre>require &#39;rails_helper&#39;<br>require_relative &#39;../support/shared_examples/activity_created_after_model_created&#39;<br><br>RSpec.describe Task, type: :model do<br>  describe &quot;#after_create&quot; do<br>    it_behaves_like &quot;activity created after model created&quot;, Task, { description: &quot;test&quot; }<br>  end<br>end</pre><p>3. Now, if we run <strong>rspec</strong> in the console, we should see the same:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*fOd9oPK5duEnC8aN_8h4dg.png" /></figure><blockquote><strong>Conclusion</strong></blockquote><p>By implementing <strong>shared_examples</strong> in our tests, we were able to reduce the amount of code written and create more <strong>maintainable</strong> and <strong>reusable</strong> tests. This technique allows us to write <strong>cleaner</strong> and more <strong>concise</strong> tests that can be easily adapted and <strong>extended</strong> to other models in our application that have <strong>similar behaviors</strong>. By using <strong>shared_examples</strong>, we can improve the overall <strong>quality</strong> and <strong>efficiency</strong> of our testing process, making it easier to identify and fix issues in our code.</p><blockquote><strong>Github repository: </strong><a href="https://github.com/yasming/Ruby_On_Rails_Rspec_Shared_Examples">https://github.com/yasming/Ruby_On_Rails_Rspec_Shared_Examples</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74973daa4a6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to safely improve and refactor code with hash maps and tests in Laravel.]]></title>
            <link>https://medium.com/@yasmin_12961/how-to-safely-improve-and-refactor-code-with-hash-maps-and-tests-in-laravel-479d3376abf9?source=rss-4bed3cb88550------2</link>
            <guid isPermaLink="false">https://medium.com/p/479d3376abf9</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[hashmap]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Yasmin Guimarães ]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 14:36:53 GMT</pubDate>
            <atom:updated>2023-03-31T14:36:53.737Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the ways to improve code performance is to use a hash map to avoid loops inside loops, for example. The better way to start refactoring the code is to write tests for the existing code to ensure that nothing stops working in the process of refactoring.</p><blockquote><strong>The business rule behind the code we will be writing here is:</strong></blockquote><blockquote>1. We obtain a list of candidates and a list of developers from two different APIs, and then we save both in our database on the Candidates and Developers tables.</blockquote><blockquote>2. Then, in our endpoint, we will need to match the candidates with developers. The matching key will be the email from the two different tables we have.</blockquote><blockquote>3. Finally, our endpoint will return the list of developers with one more key, “<strong>candidateId</strong>”, attached to the developer’s list when it is found.</blockquote><blockquote><strong>Models and migrations</strong></blockquote><blockquote><strong>So, with a fresh Laravel application, let’s start creating our models and migrations:</strong></blockquote><blockquote><strong>1. php artisan make:model Candidate\\Candidate -m</strong></blockquote><blockquote><strong>2. php artisan make:model Developer\\Developer -m</strong></blockquote><p>Add the following code to <strong>candidate.php</strong> file:</p><pre>&lt;?php<br><br>namespace App\Models\Candidate;<br><br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;<br><br>class Candidate extends Model<br>{<br>    use HasFactory;<br>}</pre><p>Add the following code to <strong>developer.php</strong> file:</p><pre>&lt;?php<br><br>namespace App\Models\Developer;<br><br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;<br><br>class Developer extends Model<br>{<br>    use HasFactory;<br>}</pre><p>Add the following code to <strong>create_candidates_table.php</strong> file:</p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\DB;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     */<br>    public function up(): void<br>    {<br>        Schema::create(&#39;candidates&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;email&#39;);<br>            $table-&gt;string(&#39;name&#39;);<br>            $table-&gt;string(&#39;company&#39;);<br>            $table-&gt;uuid(&#39;candidate_uuid&#39;)-&gt;default(DB::raw(&#39;(UUID())&#39;));<br>            $table-&gt;timestamps();<br>        });<br>    }<br><br>    /**<br>     * Reverse the migrations.<br>     */<br>    public function down(): void<br>    {<br>        Schema::dropIfExists(&#39;candidates&#39;);<br>    }<br>};</pre><p>Add the following code to <strong>create_developers_table.php</strong> file:</p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     */<br>    public function up(): void<br>    {<br>        Schema::create(&#39;developers&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;name&#39;);<br>            $table-&gt;string(&#39;email&#39;);<br>            $table-&gt;timestamps();<br>        });<br>    }<br><br>    /**<br>     * Reverse the migrations.<br>     */<br>    public function down(): void<br>    {<br>        Schema::dropIfExists(&#39;developers&#39;);<br>    }<br>};</pre><blockquote><strong>Seeds</strong></blockquote><blockquote><strong>Now, let&#39;s create ours seeds files:</strong></blockquote><blockquote><strong>1. php artisan make:factory Candidate\\CandidateFactory</strong></blockquote><blockquote><strong>2. php artisan make:factory Candidate\\DeveloperFactory</strong></blockquote><p>Add the following code to <strong>CandidateFactory.php</strong> file:</p><pre>&lt;?php<br><br>namespace Database\Factories\Candidate;<br><br>use Illuminate\Database\Eloquent\Factories\Factory;<br>use Illuminate\Support\Str;<br><br>/**<br> * @extends \Illuminate\Database\Eloquent\Factories\Factory&lt;\App\Models\Developer\Candidate&gt;<br> */<br>class CandidateFactory extends Factory<br>{<br>    /**<br>     * Define the model&#39;s default state.<br>     *<br>     * @return array&lt;string, mixed&gt;<br>     */<br>    public function definition(): array<br>    {<br>        return [<br>            &#39;name&#39; =&gt; fake()-&gt;name(),<br>            &#39;email&#39; =&gt; fake()-&gt;unique()-&gt;safeEmail(),<br>            &#39;company&#39; =&gt; fake()-&gt;name(),<br>            &#39;candidate_uuid&#39; =&gt; Str::uuid()<br>        ];<br>    }<br>}</pre><p>Add the following code to <strong>DeveloperFactory.php</strong> file:</p><pre>&lt;?php<br><br>namespace Database\Factories\Developer;<br><br>use Illuminate\Database\Eloquent\Factories\Factory;<br><br>/**<br> * @extends \Illuminate\Database\Eloquent\Factories\Factory&lt;\App\Models\Developer\Developer&gt;<br> */<br>class DeveloperFactory extends Factory<br>{<br>    /**<br>     * Define the model&#39;s default state.<br>     *<br>     * @return array&lt;string, mixed&gt;<br>     */<br>    public function definition(): array<br>    {<br>        return [<br>            &#39;name&#39; =&gt; fake()-&gt;name(),<br>            &#39;email&#39; =&gt; fake()-&gt;unique()-&gt;safeEmail(),<br>        ];<br>    }<br>}</pre><p>And add the following code to <strong>DatabaseSeeder.php</strong> file:</p><pre>&lt;?php<br><br>namespace Database\Seeders;<br><br>use App\Models\Candidate\Candidate;<br>use App\Models\Developer\Developer;<br>use Illuminate\Database\Seeder;<br><br>class DatabaseSeeder extends Seeder<br>{<br>    /**<br>     * Seed the application&#39;s database.<br>     */<br>    public function run(): void<br>    {<br>        Candidate::factory(1000)-&gt;create();<br>        Developer::factory()-&gt;count(1000)<br>            -&gt;state(function () {<br>                return [&#39;email&#39; =&gt; Candidate::query()-&gt;inRandomOrder()-&gt;first()-&gt;email];<br>            })-&gt;create();<br>    }<br>}</pre><blockquote><strong>We will start by testing the performance with just 1000 records, and then we will scale the application to handle larger amounts of data.</strong></blockquote><blockquote><strong>Controller and routes</strong></blockquote><blockquote><strong>Now, let&#39;s create our controller:</strong></blockquote><blockquote><strong>1. php artisan make:controller Developer\\DeveloperController</strong></blockquote><blockquote>2. So, in our index method, we will write the first non-performative version to solve the problem.</blockquote><blockquote>3. We will first loop through all developers in our database. Inside this loop, we will loop through all candidates and check if we can find any candidate that has the same email as the current developer. If we find a match, we will modify the $developers array and insert the candidateId into it.</blockquote><p>Add the following code to <strong>DeveloperController.php</strong> file:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers\Developer;<br><br>use App\Http\Controllers\Controller;<br>use App\Models\Candidate\Candidate;<br>use App\Models\Developer\Developer;<br><br>class DeveloperController extends Controller<br>{<br>    public function index(): array<br>    {<br>        $candidates = Candidate::all()-&gt;toArray();<br>        $developers = Developer::all()-&gt;toArray();<br>        $candidateFounded = [];<br>        foreach($developers as $key =&gt; $developer) {<br>            foreach ($candidates as $candidate) {<br>                if ($developer[&#39;email&#39;] === $candidate[&#39;email&#39;]) {<br>                    $candidateFounded[] = $candidate;<br>                }<br>            }<br>            if ( ! empty($candidateFounded) ) {<br>                $developers[$key] = array_merge($developer, [&#39;candidateId&#39; =&gt; reset($candidateFounded)[&#39;id&#39;]]);<br>                $candidateFounded = [];<br>            }<br>            $candidateFounded = [];<br>        }<br>        return $developers;<br>    }</pre><blockquote><strong>Now, let&#39;s create our route:</strong></blockquote><p>Add the following code to <strong>routes/api.php</strong> file:</p><pre>&lt;?php<br><br>use App\Http\Controllers\Developer\DeveloperController;<br>use Illuminate\Support\Facades\Route;<br><br>Route::get(&#39;/get-developers-with-uuid&#39;, [DeveloperController::class, &#39;index&#39;]);</pre><blockquote><strong>Endpoint test</strong></blockquote><blockquote><strong>Now, let&#39;s run our server:</strong></blockquote><blockquote><strong>1. php artisan serve</strong></blockquote><p><strong>Then, in Postman, let&#39;s hit our endpoint:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q7Kl-U4S-nbx-WkayF5Rbw.png" /></figure><p>So, our first request with a 1000 records in each table just took <strong>324ms</strong></p><blockquote><strong>Writings tests</strong></blockquote><blockquote><strong>Now, we want to refactor the code to improve the way it were done, so, let&#39;s start writing a test for this actual method:</strong></blockquote><blockquote><strong>1. php artisan make:test Controllers\\Developer\\DeveloperControllerTest</strong></blockquote><p>Then, add the following code to <strong>DeveloperControllerTest.php:</strong></p><pre>&lt;?php<br><br>namespace Tests\Feature\Controllers\Developer;<br><br>use App\Models\Candidate\Candidate;<br>use App\Models\Developer\Developer;<br>use Illuminate\Foundation\Testing\DatabaseMigrations;<br>use Symfony\Component\HttpFoundation\Response as HttpResponse;<br>use Tests\TestCase;<br><br>class DeveloperControllerTest extends TestCase<br>{<br>    use DatabaseMigrations;<br><br>    private Candidate $candidate;<br>    private Developer $developer;<br>    private Developer $developer2;<br><br>    protected function setUp(): void<br>    {<br>        parent::setUp();<br>        $this-&gt;candidate = Candidate::factory(1)-&gt;create()-&gt;first();<br>        $this-&gt;developer = Developer::factory(1)-&gt;create([&#39;email&#39; =&gt; $this-&gt;candidate-&gt;email])-&gt;first();<br>        $this-&gt;developer2 = Developer::factory(1)-&gt;create()-&gt;first();<br>    }<br><br>    public function test_should_return_right_endpoint_values(): void<br>    {<br>        $response = $this-&gt;get(&#39;/api/get-developers-with-uuid&#39;)-&gt;assertStatus(HttpResponse::HTTP_OK);<br>        $this-&gt;assertEquals([<br>            [<br>                &quot;id&quot; =&gt; $this-&gt;developer-&gt;id,<br>                &quot;name&quot; =&gt; $this-&gt;developer-&gt;name,<br>                &quot;email&quot; =&gt; $this-&gt;developer-&gt;email,<br>                &quot;created_at&quot; =&gt; $this-&gt;developer-&gt;created_at-&gt;toJson(),<br>                &quot;updated_at&quot; =&gt; $this-&gt;developer-&gt;updated_at-&gt;toJson(),<br>                &quot;candidateId&quot; =&gt; $this-&gt;candidate-&gt;id,<br>            ],<br>            [<br>                &quot;id&quot; =&gt; $this-&gt;developer2-&gt;id,<br>                &quot;name&quot; =&gt; $this-&gt;developer2-&gt;name,<br>                &quot;email&quot; =&gt; $this-&gt;developer2-&gt;email,<br>                &quot;created_at&quot; =&gt; $this-&gt;developer2-&gt;created_at-&gt;toJson(),<br>                &quot;updated_at&quot; =&gt; $this-&gt;developer2-&gt;updated_at-&gt;toJson(),<br>            ]<br>        ], $response-&gt;json());<br>    }<br>}</pre><blockquote>So, if you run:</blockquote><blockquote><strong>1. php artisan test</strong></blockquote><blockquote>You should get this <strong>result:</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XALLOECN6O-TmxredTT6FA.png" /></figure><blockquote><strong>Adjusting tests and improving code performance</strong></blockquote><p><strong>Now, that we have our test working, let&#39;s duplicate the test to cover our new endpoint:</strong></p><pre>&lt;?php<br><br>namespace Tests\Feature\Controllers\Developer;<br><br>use App\Models\Candidate\Candidate;<br>use App\Models\Developer\Developer;<br>use Illuminate\Foundation\Testing\DatabaseMigrations;<br>use Symfony\Component\HttpFoundation\Response as HttpResponse;<br>use Tests\TestCase;<br><br>class DeveloperControllerTest extends TestCase<br>{<br>    use DatabaseMigrations;<br><br>    private Candidate $candidate;<br>    private Developer $developer;<br>    private Developer $developer2;<br><br>    protected function setUp(): void<br>    {<br>        parent::setUp();<br>        $this-&gt;candidate = Candidate::factory(1)-&gt;create()-&gt;first();<br>        $this-&gt;developer = Developer::factory(1)-&gt;create([&#39;email&#39; =&gt; $this-&gt;candidate-&gt;email])-&gt;first();<br>        $this-&gt;developer2 = Developer::factory(1)-&gt;create()-&gt;first();<br>    }<br><br>    public function test_should_return_right_endpoint_values(): void<br>    {<br>        $response = $this-&gt;get(&#39;/api/get-developers-with-uuid&#39;)-&gt;assertStatus(HttpResponse::HTTP_OK);<br>        $this-&gt;assertEquals([<br>            [<br>                &quot;id&quot; =&gt; $this-&gt;developer-&gt;id,<br>                &quot;name&quot; =&gt; $this-&gt;developer-&gt;name,<br>                &quot;email&quot; =&gt; $this-&gt;developer-&gt;email,<br>                &quot;created_at&quot; =&gt; $this-&gt;developer-&gt;created_at-&gt;toJson(),<br>                &quot;updated_at&quot; =&gt; $this-&gt;developer-&gt;updated_at-&gt;toJson(),<br>                &quot;candidateId&quot; =&gt; $this-&gt;candidate-&gt;id,<br>            ],<br>            [<br>                &quot;id&quot; =&gt; $this-&gt;developer2-&gt;id,<br>                &quot;name&quot; =&gt; $this-&gt;developer2-&gt;name,<br>                &quot;email&quot; =&gt; $this-&gt;developer2-&gt;email,<br>                &quot;created_at&quot; =&gt; $this-&gt;developer2-&gt;created_at-&gt;toJson(),<br>                &quot;updated_at&quot; =&gt; $this-&gt;developer2-&gt;updated_at-&gt;toJson(),<br>            ]<br>        ], $response-&gt;json());<br>    }<br><br>    public function test_should_return_right_endpoint_values_for_improved_endpoint(): void<br>    {<br>        $response = $this-&gt;get(&#39;/api/get-developers-with-uuid-improvement&#39;)-&gt;assertStatus(HttpResponse::HTTP_OK);<br>        $this-&gt;assertEquals([<br>            [<br>                &quot;id&quot; =&gt; $this-&gt;developer-&gt;id,<br>                &quot;name&quot; =&gt; $this-&gt;developer-&gt;name,<br>                &quot;email&quot; =&gt; $this-&gt;developer-&gt;email,<br>                &quot;created_at&quot; =&gt; $this-&gt;developer-&gt;created_at-&gt;toJson(),<br>                &quot;updated_at&quot; =&gt; $this-&gt;developer-&gt;updated_at-&gt;toJson(),<br>                &quot;candidateId&quot; =&gt; $this-&gt;candidate-&gt;id,<br>            ],<br>            [<br>                &quot;id&quot; =&gt; $this-&gt;developer2-&gt;id,<br>                &quot;name&quot; =&gt; $this-&gt;developer2-&gt;name,<br>                &quot;email&quot; =&gt; $this-&gt;developer2-&gt;email,<br>                &quot;created_at&quot; =&gt; $this-&gt;developer2-&gt;created_at-&gt;toJson(),<br>                &quot;updated_at&quot; =&gt; $this-&gt;developer2-&gt;updated_at-&gt;toJson(),<br>            ]<br>        ], $response-&gt;json());<br>    }<br>}</pre><p>Creating our new route in <strong>routes/api.php</strong> file:</p><pre>&lt;?php<br><br>use App\Http\Controllers\Developer\DeveloperController;<br>use Illuminate\Support\Facades\Route;<br><br><br>Route::get(&#39;/get-developers-with-uuid&#39;, [DeveloperController::class, &#39;index&#39;]);<br>Route::get(&#39;/get-developers-with-uuid-improvement&#39;, [DeveloperController::class, &#39;indexImproved&#39;]);</pre><blockquote>And now, we will rewrite the old code we have to be more performant using a <strong>hashmap:</strong></blockquote><blockquote>1. The idea is to avoid doing one foreach inside another</blockquote><blockquote>2. So, for this, we will loop through the candidates first and then create a new array with this <strong>structure</strong>: [&quot;candidate_email&quot; =&gt; &quot;candidateId&quot;]</blockquote><blockquote>3. So, with this data structure, we can then loop through the developers and check if the developer’s email exists in the new candidate array using <strong>isset</strong>. If so, we can get the candidateId from the <strong>data structure</strong>.</blockquote><p>Add the following code to <strong>DeveloperController.php</strong> file:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers\Developer;<br><br>use App\Http\Controllers\Controller;<br>use App\Models\Candidate\Candidate;<br>use App\Models\Developer\Developer;<br><br>class DeveloperController extends Controller<br>{<br>    public function index(): array<br>    {<br>        $candidates = Candidate::all()-&gt;toArray();<br>        $developers = Developer::all()-&gt;toArray();<br>        $candidateFounded = [];<br>        foreach($developers as $key =&gt; $developer) {<br>            foreach ($candidates as $candidate) {<br>                if ($developer[&#39;email&#39;] === $candidate[&#39;email&#39;]) {<br>                    $candidateFounded[] = $candidate;<br>                }<br>            }<br>            if ( ! empty($candidateFounded) ) {<br>                $developers[$key] = array_merge($developer, [&#39;candidateId&#39; =&gt; reset($candidateFounded)[&#39;id&#39;]]);<br>                $candidateFounded = [];<br>            }<br>            $candidateFounded = [];<br>        }<br>        return $developers;<br>    }<br><br>    public function indexImproved(): array<br>    {<br>        $candidates = Candidate::all()-&gt;toArray();<br>        $developers = Developer::all()-&gt;toArray();<br>        $newCandidateArray = [];<br>        foreach ($candidates as $candidate) {<br>            $newCandidateArray[$candidate[&#39;email&#39;]] = $candidate[&#39;id&#39;];<br>        }<br>        foreach ($developers as &amp;$developer) {<br>            if (isset($newCandidateArray[$developer[&#39;email&#39;]])) {<br>                $developer[&#39;candidateId&#39;] = $newCandidateArray[$developer[&#39;email&#39;]];<br>            }<br>        }<br>        return $developers;<br>    }<br>}</pre><p>Just running <strong>php artisan test</strong> again to check if the tests are passing with the new code, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kxPjfJEVzMtNdorU2C6tGA.png" /></figure><blockquote><strong>Endpoint test</strong></blockquote><p><strong>Now, in Postman, let’s hit our new endpoint:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2V2SrlWViyqMYnlVWSaJ3w.png" /></figure><p>So, our first request with a 1000 records in each table took <strong>141ms</strong>, already a improvement of <strong>183ms</strong></p><blockquote><strong>Scaling application and comparing both endpoints</strong></blockquote><p><strong>Now, let&#39;s change our<em> DatabaseSeeder.php </em>file to add <em>100000</em> records to each table:</strong></p><pre>&lt;?php<br><br>namespace Database\Seeders;<br><br>use App\Models\Candidate\Candidate;<br>use App\Models\Developer\Developer;<br>use Illuminate\Database\Seeder;<br><br>class DatabaseSeeder extends Seeder<br>{<br>    /**<br>     * Seed the application&#39;s database.<br>     */<br>    public function run(): void<br>    {<br>        Candidate::factory(100000)-&gt;create();<br>        Developer::factory()-&gt;count(100000)<br>            -&gt;state(function () {<br>                return [&#39;email&#39; =&gt; Candidate::query()-&gt;inRandomOrder()-&gt;first()-&gt;email];<br>            })-&gt;create();<br>    }<br>}</pre><blockquote>1. Running <strong>php artisan migrate:refresh — seed</strong></blockquote><blockquote>2. Hit the <strong>endpoints</strong> again</blockquote><p>We got this result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBdErKAAoL9vqzDSfQjNqw.png" /></figure><p>For the non-improved endpoint, the time was <strong>8 minutes and 26.52 seconds</strong></p><p>And this result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ul6bp_LwaOTNdQExKPTO-Q.png" /></figure><p>For the improved endpoint, the time was <strong>8.59 seconds</strong></p><blockquote><strong>Conclusion</strong></blockquote><blockquote>So, as we can see, when we start having more records in our database, having one loop inside another loop could result in a significant delay in our endpoint response.</blockquote><blockquote>1. When we try to improve code performance, we can check if we can reduce the number of loops nested inside others.</blockquote><blockquote>2. Use hashmap to improve performance, and make sure to write tests first to ensure safety !</blockquote><p>Github repository: <a href="https://github.com/yasming/Laravel_Hashmap_Performance_Improvement">https://github.com/yasming/Laravel_Hashmap_Performance_Improvement</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=479d3376abf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a web scraper with golang]]></title>
            <link>https://medium.com/@yasmin_12961/how-to-create-a-web-scraper-with-golang-5a57e6f11e72?source=rss-4bed3cb88550------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a57e6f11e72</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[crawler]]></category>
            <dc:creator><![CDATA[Yasmin Guimarães ]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 09:42:34 GMT</pubDate>
            <atom:updated>2023-02-20T09:46:22.585Z</atom:updated>
            <content:encoded><![CDATA[<h4>The objective of this tutorial is to learn how to build a web scraping/crawler. A very useful tool to get information from specific websites when one API is not available. We will be using golang language and applying some awesome DDD techniques!</h4><blockquote>For our project project structure:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*lldjbY7jJJkpLBHjJqujew.png" /></figure><blockquote>The first thing we will be doing to start our project is to create a docker container for our application</blockquote><blockquote>Docker is the easiest way to get any project running on multiple machines. To start the container we will need two files</blockquote><blockquote>1. <strong>docker-compose.yml</strong> (This file specifies the services use by our application, as well as any volumes required to support our services)</blockquote><pre>version: &#39;3.5&#39;<br>services:<br>  server:<br>    container_name: web_scraping<br>    build:<br>      context: .<br>    command: nodemon --exec go run main.go --signal SIGTERM<br>    ports:<br>      - &quot;8989:8989&quot;<br>    volumes:<br>      - .:/app</pre><blockquote>2. <strong>dockerfile</strong> (A text file that contains instructions to build a Docker image)</blockquote><pre>FROM golang:latest<br>RUN apt-get update<br>RUN apt-get -y install npm<br>RUN npm install -g nodemon<br>RUN apt -y install chromium<br>COPY ./ /app/<br>WORKDIR /app</pre><blockquote>Now, lets create our .<strong>gitignore</strong> file:</blockquote><pre>.env<br>.coverage.out<br>.idea</pre><blockquote>And let&#39;s create our .<strong>env.example</strong> and <em>.</em><strong>env</strong> with the following variables:</blockquote><pre>CLASSIFICATION_URL_CBLOL=https://flashscore.com.br/esports/league-of-legends/cblol/classificacao/<br>AUTHORIZED_USER=user1<br>AUTHORIZED_USER_PASSWORD=password1</pre><blockquote>And create our <strong>go.mod </strong>file with the following code:</blockquote><pre>module webscraping-league-of-legends-v2</pre><blockquote>To make the way we run our project faster, we will create a <strong>makefile</strong> which is used to automate the build process of the project</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*aetum42Hq8Z1_c1Y9_fTIQ.png" /></figure><blockquote>And write the following code in the file:</blockquote><pre>#!make<br>include .env<br><br>start:<br>   docker-compose up<br><br>install-new-package:<br> docker-compose run --rm server go get -u $(package_name)<br><br>run-all-tests:<br>   docker-compose run --rm server go test -coverprofile=coverage.out ./...<br><br>stop:<br>   docker-compose down</pre><blockquote>Now lets create our <strong>main.go</strong>, an entry point of our application</blockquote><pre>package main<br><br>func main() {<br> println(&quot;it is working&quot;)<br>}</pre><blockquote>Run the following command to install <strong>godotenv</strong> dependency to enable us to use <strong>.env</strong> variables inside our codebase:</blockquote><blockquote><strong>make install-new-package package_name=”github.com/joho/godotenv”</strong></blockquote><blockquote>Now let’s install the package that will help us create our <strong>web service</strong>:</blockquote><blockquote><strong>make install-new-package package_name=”github.com/gin-gonic/gin”</strong></blockquote><blockquote>And the last package we will need , will help us interact with the browser:</blockquote><blockquote><strong>make install-new-package package_name=”github.com/chromedp/chromedp”</strong></blockquote><blockquote>And then:</blockquote><blockquote><strong>make start</strong></blockquote><blockquote>After the build be completed, it should output:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*Dq0WuubGhFCK5Hqop5HCZw.png" /></figure><blockquote>And in our <strong>main.go</strong>:</blockquote><pre>package main<br><br>import (<br> &quot;github.com/joho/godotenv&quot;<br> &quot;log&quot;<br> &quot;webscraping-league-of-legends-v2/cblol/infra/http/routes&quot;<br>)<br><br>func main() {<br>  err := godotenv.Load(&quot;.env&quot;)<br>  if err != nil {<br>    log.Fatal(err)<br>  }<br>  router := routes.AddRoutesWithAuthentication()<br>  router.Run(&quot;:8989&quot;)<br>}</pre><blockquote>Let’s add our routes:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*IgYT9_xGEFEU2HXKbRCt3A.png" /></figure><pre>package routes<br><br>import (<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;os&quot;<br> &quot;webscraping-league-of-legends-v2/cblol/application/controllers/teams&quot;<br>)<br><br>func AddRoutesWithAuthentication() *gin.Engine {<br>  router := gin.Default()<br>  authorized := router.Group(&quot;/api&quot;, gin.BasicAuth(gin.Accounts{<br>  os.Getenv(&quot;AUTHORIZED_USER&quot;): os.Getenv(&quot;AUTHORIZED_USER_PASSWORD&quot;),<br> }))<br>  authorized.GET(&quot;/get-teams&quot;, controller_teams.GetTeams)<br>  return router<br>}</pre><blockquote>So, now we have our routes with basic auth</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*Ed4UNzDxN_JBJEajtNHAmg.png" /></figure><blockquote>Inside our <strong>teams_controller.go </strong>let’s write:</blockquote><pre>package controller_teams<br><br>import (<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;net/http&quot;<br>)<br><br>func GetTeams(c *gin.Context) {<br> c.IndentedJSON(http.StatusOK, &quot;test&quot;)<br>}</pre><blockquote>If you have not run <strong>make start</strong> yet, run it now and go to the following URL in the browser:</blockquote><ul><li><a href="http://localhost:8989/api/get-teams">http://localhost:8989/api/get-teams</a></li></ul><blockquote>Then, fill the form with:</blockquote><blockquote><strong>user:</strong> user1</blockquote><blockquote><strong>password:</strong> password1</blockquote><blockquote>And you should see:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*tO0ZP5Tpj0N69y81SgVNYg.png" /></figure><blockquote>Ok! Now we have our web service running pointing to our controller, and returning a json response.</blockquote><blockquote>Now, let’s create our <strong>first test</strong></blockquote><blockquote>First run:</blockquote><blockquote><strong>make install-new-package package_name=”github.com/stretchr/testify/assert”</strong></blockquote><blockquote>Then, let’s create our <strong>teams_controller_test.go</strong>:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*Y14DhFaa6nIfLlECqTAwrw.png" /></figure><blockquote>Inside our <strong>teams_controller.go </strong>let’s write:</blockquote><pre>package controller_teams_test<br><br>import (<br>   &quot;encoding/base64&quot;<br>   &quot;github.com/stretchr/testify/assert&quot;<br>   &quot;net/http&quot;<br>   &quot;net/http/httptest&quot;<br>   &quot;os&quot;<br>   &quot;testing&quot;<br>   &quot;webscraping-league-of-legends-v2/cblol/infra/http/routes&quot;<br>)<br><br>func TestPingRoute(t *testing.T) {<br>   t.Setenv(&quot;AUTHORIZED_USER&quot;, &quot;user&quot;)<br>   t.Setenv(&quot;AUTHORIZED_USER_PASSWORD&quot;, &quot;password&quot;)<br>   router := routes.AddRoutesWithAuthentication()<br>   w := httptest.NewRecorder()<br>   req, _ := http.NewRequest(&quot;GET&quot;, &quot;/api/get-teams&quot;, nil)<br>   req.Header.Add(&quot;Authorization&quot;, &quot;Basic &quot;+basicAuth(os.Getenv(&quot;AUTHORIZED_USER&quot;), os.Getenv(&quot;AUTHORIZED_USER_PASSWORD&quot;)))<br>   router.ServeHTTP(w, req)<br>   assert.Equal(t, 200, w.Code)<br>   assert.Equal(t, &quot;\&quot;test\&quot;&quot;, w.Body.String())<br>}<br><br>func basicAuth(username, password string) string {<br>   auth := username + &quot;:&quot; + password<br>   return base64.StdEncoding.EncodeToString([]byte(auth))<br>}</pre><blockquote>Then, for our test coverage, run the following command:</blockquote><blockquote><strong>make run-all-tests</strong></blockquote><blockquote>Then, you should get the following output:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mrPz4bAUAGYQgLKVt7VEVA.png" /></figure><blockquote>Now that we have the test setup let’s get back to our controller and start writing the code of our crawler:</blockquote><pre>package controller_teams<br><br>import (<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;webscraping-league-of-legends-v2/cblol/application/usecase/teams&quot;<br>)<br><br>func PopulateTeams(c *gin.Context) {<br> c.IndentedJSON(http.StatusOK, gin.H{&quot;teams&quot;: usecase_teams.GetTeams()})<br>}</pre><blockquote>In our controller we will call our use case that is <strong>GetTeams</strong>, so let’s create our file:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*G0LOM3O74VTDpHgcJgKEDQ.png" /></figure><blockquote>And write:</blockquote><pre>package usecase_teams<br><br>import (<br> &quot;webscraping-league-of-legends-v2/cblol/domain/services/teams&quot;<br>)<br><br>func GetTeams() []string {<br> return service_teams.GetTeams()<br>}</pre><blockquote>Then, let&#39;s create our service:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*awoiEjJ2xzQ3vGY68RnnSA.png" /></figure><blockquote>With the following code:</blockquote><pre>package service_teams<br><br>import (<br> &quot;webscraping-league-of-legends-v2/cblol/infra/gateway&quot;<br>)<br><br>var GetTeamsFromFlashScoreGateway = gateway.GetTeamsFromFlashScore<br><br>func GetTeams() []string {<br> return GetTeamsFromFlashScoreGateway()<br>}</pre><blockquote>Now, let’s create our gateway to send the external request to <strong>flashscore</strong> website</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*WBei2xlm4eLsZHiFxrQ4QA.png" /></figure><blockquote>In our crawler from flashscore website, we will need to find all the names and structure of the teams in the html. It looks something like:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQCN5yMDHpkALVhIIT0Ekg.png" /></figure><blockquote>So, we need to find the class <strong>tableCellParticipant__name</strong></blockquote><blockquote>And mount our <strong>crawller</strong> using <strong>chromedp</strong> libary to find the class we need inside the html :</blockquote><pre>package gateway<br><br>import (<br>   &quot;context&quot;<br>   &quot;github.com/chromedp/chromedp&quot;<br>   &quot;log&quot;<br>   &quot;os&quot;<br>   &quot;time&quot;<br>)<br><br>func GetTeamsFromFlashScore() []string {<br>   ctx, cancel := chromedp.NewContext(<br>      context.Background(),<br>   )<br>   defer cancel()<br>   ctx, cancel = context.WithTimeout(ctx, 15*time.Second)<br>   defer cancel()<br>   var teams []string<br>   err := chromedp.Run(ctx,<br>      chromedp.Navigate(os.Getenv(&quot;CLASSIFICATION_URL_CBLOL&quot;)),<br>      chromedp.WaitVisible(`.tableCellParticipant__name`),<br>      chromedp.Evaluate(`[...document.querySelectorAll(&#39;.tableCellParticipant__name&#39;)].map((e) =&gt; e.innerText)`, &amp;teams),<br>   )<br>   if err != nil {<br>      log.Fatal(err)<br>   }<br>   return teams<br>}</pre><blockquote>Now when you go to <a href="http://localhost:8989/api/get-teams">http://localhost:8989/api/get-teams</a> on your browser, you should get:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*NHIswhNyOFzkI0TfyiMpXw.png" /></figure><blockquote>Now let’s just adjust our test to mock our crawler response:</blockquote><pre>package controller_teams_test<br><br>import (<br>   &quot;encoding/base64&quot;<br>   &quot;github.com/stretchr/testify/assert&quot;<br>   &quot;net/http&quot;<br>   &quot;net/http/httptest&quot;<br>   &quot;os&quot;<br>   &quot;testing&quot;<br>   &quot;webscraping-league-of-legends-v2/cblol/domain/services/teams&quot;<br>   &quot;webscraping-league-of-legends-v2/cblol/infra/http/routes&quot;<br>)<br><br>func TestPingRoute(t *testing.T) {<br>   t.Setenv(&quot;AUTHORIZED_USER&quot;, &quot;user&quot;)<br>   t.Setenv(&quot;AUTHORIZED_USER_PASSWORD&quot;, &quot;password&quot;)<br>   t.Setenv(&quot;CLASSIFICATION_URL_CBLOL&quot;, &quot;https://flashscore.com.br/esports/league-of-legends/cblol/classificacao/&quot;)<br>   router := routes.AddRoutesWithAuthentication()<br>   mockGetTeamsFromFlashScore()<br>   w := httptest.NewRecorder()<br>   req, _ := http.NewRequest(&quot;GET&quot;, &quot;/api/get-teams&quot;, nil)<br>   req.Header.Add(&quot;Authorization&quot;, &quot;Basic &quot;+basicAuth(os.Getenv(&quot;AUTHORIZED_USER&quot;), os.Getenv(&quot;AUTHORIZED_USER_PASSWORD&quot;)))<br>   router.ServeHTTP(w, req)<br>   assert.Equal(t, 200, w.Code)<br>   assert.Equal(t, &quot;{\n    \&quot;teams\&quot;: [\n        \&quot;INTZ-eSports\&quot;\n    ]\n}&quot;, w.Body.String())<br>}<br><br>func basicAuth(username, password string) string {<br>   auth := username + &quot;:&quot; + password<br>   return base64.StdEncoding.EncodeToString([]byte(auth))<br>}<br><br>func mockGetTeamsFromFlashScore() {<br>   service_teams.GetTeamsFromFlashScoreGateway = func() []string {<br>      var strArr []string<br>      strings := append(strArr, &quot;INTZ-eSports&quot;)<br>      return strings<br>   }<br>}</pre><blockquote>And we are <strong>done!!</strong> We were able to get the teams with our crawler from <strong>flashscore</strong> website.</blockquote><blockquote>- <strong>Github link:</strong> <a href="https://github.com/yasming/Webscrapping_Golang"><strong>https://github.com/yasming/Webscraping_Golang</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a57e6f11e72" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>