December 7, 2022

Go language

For a long time I wanted to try to use the Go language for some serious projects. The choice was obvious, since this language is the best suited for such tasks.

The language supports multiple return values. Instead of the try-catch mechanism, a technique is very often used when an error is returned as the second argument. And if it exists, it is processed mfcalc. There is a built-in error type, which is an interface.

Note that structure fields are capitalized. This means that they are scoped outside of the package. If you write them with a capital letter, they will not be exported, but will be available only within the package. The same applies to functions and methods. Here is such a simple encapsulation mechanism.

Here we are using the wonderful MongoDb driver mgo to save the data. For convenience, I created a small wrapper over api mgo - utils.NewDbSession. The logic of working with data: first we create an object in the internal structure of the language, and then, using the method of this structure, we save it to the database.

Note that in these methods we use our conf.ApiError error type throughout. We convert standard errors to ours with conf.NewApiError(err). Also, the defer operator is important. It is executed at the very end of the method execution. In this case, it closes the connection to the database.