Counting number of items in a concurrent map

Lately I’ve been using Go’s concurrent map. And sometimes I needed to count the items I’ve stored in the map. I have ranged over the items and incremented a counter, and it was done:

package main

import (
       "sync"
       "log"
)

func main() {
       m := sync.Map{}
       
       m.Store("k1", "v1")
       m.Store("k2", "v2")
       
       count := 0
       m.Range(func(key, value interface{}) bool{
              count++
              return true
       })

       log.Println(count)
}

But I didn’t want to range over the items each time I wanted to count them. So I thought of incrementing the counter every time an element was added, and to decrementing it when one was removed. The following is just for practice, I didn’t perform any advanced tests. Continue reading Counting number of items in a concurrent map

Go HTTP server duplicate handler call

It took me a minute or two to figure out why, while doing some experiments, for the following built-in HTTP server use case, the handler was called two times, and so printing the log message two times.

package main

import (
       "log"
       "net/http"
)

func main() {
       http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
              log.Println("call")
       })

       http.ListenAndServe(":8800", nil)
}

The path “/” catches all requests, thus it catches the “/favicon.ico” request sent by the browser. So I’ve just used another path.

Two sides of working with junior developers

Seeing people evolve around you gives you a fulfilling. Even more if you were there for them giving advice, sharing ideas and links, lending a book, explaining principles, answering to HOWs and WHYs, making up a step-by-step plan to help them better organize themselves.

If they’re unemployed, maybe you help them get a job. If they’re coworkers, you push them to ask more from themselves regarding the big picture of the project, how to search for help, how to detach sometimes from their mindset and try something new.

And very important, you make them ask themselves how others solved different situations and why they applied some principles. You help them identify needs and track down bugs.

Or…  Continue reading Two sides of working with junior developers

Go web app with all assets embedded into the binary

From my first interactions with Go, a very small web app came out. There were several microservices that were exposing data through REST and I needed to quickly browse all of the content in a user friendly way.

I wanted something fast, simple, and easy to integrate new microservices on in the future, as it was the first Go app in the company. I quickly wrote it, deployed it, and the job was done.

To make the deploy process very easy, I wanted a one file application, so I used the go-bindata package to embed the HTML files into the binary, and the CSS and JS files (jQuery and Bootstrap) were served from the official CDNs (now, to show a full example, I’ve embedded all of them).

Take a look at the Micro UI source code.

From PHP to Go

Besides being very powerful, Go is a clean language. It was easy to get started with it, despite it has some obvious major differences if coming from a language like PHP. I knew some of them, cause they’re specific to any compiled language, while in an interpreted one you have to work in order to get their benefits.

I got comfortable with them and even wished PHP had them. I’m not comparing the two languages by considering one to be better or worse, I’m only telling some differences that caught my eye, even if they are normal to be.

It got me happy about writing code in a very different way, putting aside some things that are normal in other contexts and I was used to. Continue reading From PHP to Go

Go concurrency is elegant and simple

These days I wanted to speed up some data retrieval with Go. Its concurrency model is elegant and simple, it has everything you need built-in.

Let’s say there are some articles that need to be fetched from an API. I have the IDSs of all the articles, and I can fetch them one by one. One request can take even a second, so I added a 1 second sleep to simulate this.

type Article struct {
       ID    uint
       Title string
}

func GetArticle(ID uint) Article {
       time.Sleep(time.Second * 1)
       return Article{ID, fmt.Sprintf("Title %d", ID)}
}

The classic way of doing this is making a request for each article, wait for it to finish, store the data.

var articles []Article
var id uint

for id = 1; id <= 10; id++ {
       log.Println(fmt.Sprintf("Fetching article %d...", id))
       article := GetArticle(id)
       articles = append(articles, article)
}

log.Println(articles)

With a 1 second response time it takes 10 seconds. Now imagine 100 articles or more. Continue reading Go concurrency is elegant and simple

Pipelines and workers in Go

I have some lists of users that I get and, for each user, I need to apply some rules (text formatting, max length, and who knows what other business rules can come up in the future), then send it further to another service. If I get the user again, I have to ignore them from the entire process. If one of the rules tells the user is not eligible, I have to stop the entire process, no need to go the next rules.

If you read the previous paragraph again, you can see some if statements that you should avoid from the technical implementation, but of course, not from the business rules:

  • If user was already processed, continue
  • If max length is exceeded, truncate
  • If a rule tells user is not OK, stop

I look at the rules as being some workers in a pipeline. Every worker does its job and sends its work to the next worker. Here’s how I’ve handled this. Continue reading Pipelines and workers in Go

Migrating an infrastructure

At the end of last year I was given the task to move an infrastructure spread on various providers (cloud and physical servers) to a new cloud. My role was to discover the entire infrastructure and services communication, come up with a strategy of how things are going to take place, then manage and supervise the sysadmin in charge of effectively moving machines.  This was a production environment, so minimum down time was desired. Most of the work was during night time.

It was a challenge from day zero, being a legacy multi component system with no specific flow. I had high level knowledge of the project, but subtle info came up every day. And I learned and used some things that I’d like to mention.

Planning everything ahead

I took each component (or group of components where required) individually and wrote down on a whiteboard their role, technologies, firewalls, running processes, storage info, communication flow with the other components, and a step-by-step process of how the migration should go. Continue reading Migrating an infrastructure

Start now

If you have some technical debt, an architecture issue, an old bug, or just some poorly developed features, now is the right moment to start changing. And I’m all pragmatic about it. No motivational stuff.

I’m talking about real problems which hold you back, waste time and money. Not about small optimizations which don’t bring you value, not every problem needs a solution.

To start doesn’t necessarily mean to actually do or to rush, you can start analyzing the need and the effort, think of required steps (technical analysis, people analysis, business requirements and so on).

Then start refactoring that old class or make a new one, maybe extract that feature into a microservice, upgrade that server, change that old technology, rethink that architecture so you can change easier in the future.

You know your business, but get fresh ideas from other people, maybe you’re too stiffed after many years on the project.

Just start the process now, because later everything will require more and more resources.

 

Why I chose to build a framework at a 3-hour interview

I encourage the use of known frameworks over custom ones, but I decided not to use one when, at an interview, I had 3 hours to prove the technical aspects I’ve been talking about at the first encounter with the employer.

The task was simple: build a REST web service (using PHP and MySQL) and make some operations on a resource, and a small JavaScript client to interact with the service.

I felt that using a known framework for a basic task like this I couldn’t show too many principles I use when developing. It wasn’t the moment to build a production ready app, it was just to show I can DO what I KNOW.

So my 3-hour journey building a framework from scratch started. It had basic components like: Continue reading Why I chose to build a framework at a 3-hour interview