<?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 Felipe Caputo on Medium]]></title>
        <description><![CDATA[Stories by Felipe Caputo on Medium]]></description>
        <link>https://medium.com/@felipecaputo?source=rss-31e9d3577043------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nbV2F_NClj0Sr5TQ.jpg</url>
            <title>Stories by Felipe Caputo on Medium</title>
            <link>https://medium.com/@felipecaputo?source=rss-31e9d3577043------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 20:47:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@felipecaputo/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[Building an API with Golang in 2020 — Part 2]]></title>
            <link>https://blog.devgenius.io/building-an-api-with-golang-in-2020-part-2-ed9f70d46ff3?source=rss-31e9d3577043------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed9f70d46ff3</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Felipe Caputo]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 11:38:09 GMT</pubDate>
            <atom:updated>2020-08-05T17:38:15.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9prSTTihyJAZuxL5DmfkNw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@adelis?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Adel</a> on <a href="https://unsplash.com/s/photos/climbing?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3><a href="https://medium.com/@felipecaputo/building-an-api-with-golang-in-2020-part-1-bfe61ac8ae8?source=your_stories_page---------------------------">Building an API with Golang in 2020 — Part </a>2</h3><p>Following the idea of the <a href="https://medium.com/@felipecaputo/building-an-api-with-golang-in-2020-part-1-bfe61ac8ae8">previous post</a>, we will get the project we have started and will add now a database connection, and a user CRUD API. It will be really simple, with simple validations, and simple error handling, but I think it will give you some ideas about how the modules and files are isolated, and how to handle HTTP and database operations, read config from environment variables, and also we will use a docker-compose to provide our database service. Let’s get started!</p><h4>Our first package — config</h4><p>Our application already has a package, as we declared package main in our main.go file. Golang organize programs and libraries into packages, by convention they are declared with the same name ofthe folder that contains the .go files. Our main package is a <a href="https://blog.learngoprogramming.com/special-packages-and-directories-in-go-1d6295690a6b">special package</a> that represents the entry package of any Go application, we will create another package now that is also a special package called internal and to do that, we will create a folder called internal in the root folder of our application.</p><p>This internal package is special because it is only visible to the same root based packages that it is created. We will use it as a container for our first internal package called config and inside this folder we will create our file config.go After that, our project will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*v7YXRMNnL28oKRlw4My7bQ.png" /><figcaption>package current structure</figcaption></figure><p>This file will contain our application configuration. Based on the <a href="https://12factor.net/">12factor</a>, configuration should be read from environment, and to do that we will create a struct that is the equivalent of a class in most of the languages. Our Config will have fields to expose our ConnectionString and also the environment in which our application is running.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00dfe53919723bfb45f49b192e4e16d4/href">https://medium.com/media/00dfe53919723bfb45f49b192e4e16d4/href</a></iframe><p>In the first line we define our package, naming it config. In the line 3, we import the standard package called os that we will use to read the configuration from the OS environment variables.</p><p>From line 5 to 8 we are declaring our Config struct. We write it with ts first letter capitalized <a href="https://medium.com/better-programming/string-case-styles-camel-pascal-snake-and-kebab-case-981407998841">(Pascal Case</a>), because in Go, the uppercase entities are public outside the package, and the lowercase are private. We will define two fields in it right now, Environment that will be our application running environment (local, test or production) and ConnectionString that will have our database connection string. Both fields are also declared uppercase to be visible outside the config package.</p><p>From line 10 until 16 we are creating a function called getConfigValue to allow us to read values from the environment, but returning a default value if the configuration doesn’t exist. We use the os package’s function LookupEnv that accepts one argument and returns two values. The argument is the environment variable name, and it returns the variable value as the first result, and a boolean value which is true when the variable is found. When the variable is found, we return the variable value and if it is not found, we return the default value received value.</p><h4>Creating our first constructor</h4><p>Now that we have defined how to read the configuration values, we need to expose our Configstruct with the calues. To make it, between lines 18 and 23 we create our constructor for the Config struct. In Go, the constructor are not struct level methods, they are generally package level functions, and by convention are named with the prefix<strong> New</strong> followed by the name of the struct, in our case NewConfig that returns an instance of the struct. In this constructor, we initialize each of our config fields, reading from the environment variable, and defining the default value for a localhost MySQL database, and the local environment.</p><h4>The database package</h4><p>After finishing our config package, lets create our second internal package that will be the database package with the db.go file inside it. We will do something that is similar to our config file above, but we don’t need to create a struct because sqlx package already have a DB interface that we will create, we will only create a constructor that will receive a Config struct as argument to configure a connection, as we can see in the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a78ae8c585387cdd851cf65fad11ef4e/href">https://medium.com/media/a78ae8c585387cdd851cf65fad11ef4e/href</a></iframe><p>Just like the when we were creating the config package, we are defining the package name as database, and doing the needed imports. In this one we are importing our config package, the <a href="https://godoc.org/github.com/jmoiron/sqlx">sqlx package</a> that we will use to connect to the database, and the MySQL driver.</p><p>It is important to note that <strong><em>we are using an alias </em></strong>(_) to the MySQL driver package because in Go, if we don’t use an imported package it will show a compilation error, and using the _ as the alias, we are telling the compiler to ignore the given import. We need to import it to add support to MySQL to the default database package (<a href="http://go-database-sql.org/importing.html">more info</a>).</p><p>We will use the sqlx package, that has the same methods as the default database/sql but implements some other methods that makes it easier to write map queries and updates with structs than the default package methods, we will get more into it a little later.</p><p>The constructor this time is called NewDB and has an argument of the type of our recently created Config struct. You can also note that in the method Open, that is called on line 29, we pass the driverName (“mysql”) as the first argument, and our ConnectionString from the received config as the second one. This method returns an interface that represents a pool of connections to the database, so we don’t neet to implement anything to handle concurrent uses with it.</p><h4>Our first domain level package — user</h4><p>Now that we already have a database connection, we will start our first domain package called user where we will handle all the user structs and methods. The first step is to represent our entity. The name of the file into the package does not matter for the compiler, so the name of the file is important for us and our fellow developers in the same project. We could put all our code into a file for example, but that makes it harder to read and to understand the project. The first file we will create is the user/entity.go as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a81160a640a3c55d34a65886f2cd5629/href">https://medium.com/media/a81160a640a3c55d34a65886f2cd5629/href</a></iframe><p>We will name our package as user and will import a package called validator to help us validate our inputs in an easier way. After that, is created the User struct with some basic fields just to show the functionality of a simple CRUD operations using chi.</p><h4>Adding validation to our struct</h4><p>The strings that are present in front of the type of each field are tags. Tags are used to add reflection info the struct fields (<a href="https://medium.com/golangspec/tags-in-golang-3e5db0b8ef3e">more info here</a>), and the ones we are using are for JSON, database fields and validation.</p><p>The <a href="https://github.com/go-playground/validator/">validator package</a> uses the validate tag to show which fields should be validated, and their validation rule. In line 9, when we define the min=3 we are saying that the minimum length for our field is 3, when the field is a number, it validates the value instead of the length. In the function Validate declared on line 13, we are using an instance of the validator package to validate our struct passed as argument, and return an error if the validation fails.</p><h4>Creating the repository</h4><p>Now that we already have our User entity, let’s create our repository to allow us to persist and read data from our database. To do that, we will create our user/repository.go</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe5a7562e0dc440f0395034975e6d887/href">https://medium.com/media/fe5a7562e0dc440f0395034975e6d887/href</a></iframe><p>There are a lot of imports this time, but let’s just go it over in parts. First we declare our UserRepository struct with only one field db that is lowercase this time, as we don’t need to expose it as public outside our package.</p><p>After that we will declare some constants with the SQL commands we will need to run on database to provide the CRUD operations for the user entity. The first method is the CreateUser that receives a User struct as argument and returns a point to a user (to return the inserted id) and an error in case we cannot create the user. This is the biggest method we have, so let’s get into it so we can understand it better.</p><p>If you are not yet used to how Go knows which methods are from the package and which ones are related to structs, just note that after the func reserved keyword, if we open a parenthesis and create a parameter with a type, just like in the func (u *UserRepository) CreateUser, the method is being <em>attached </em>to that struct, being a member of it, instead of the package.</p><h4>Inserting a user</h4><p>First we will generate the uuid for our user. UUID are great for primary keys and are better to expose to external URLs instead of sequential numbers. After that we will hashAndSalt the password, using the bcrypt package. This is really important when storing password as we should <a href="https://security.stackexchange.com/questions/120540/why-shouldnt-i-store-passwords-in-plaintext">never store plain text passwords</a> and using SHA or MD5 are not safe enough as it can be compared to other hashed texts.</p><p>The bcrypto method put a random salt and cryptography a text using it, making it possible to evaluate if the password is correct, only having the right password and the stored salt, giving an extra layer of security to the stored sensible data.</p><p>After validating if the hashAndSalt didn’t return an error, we just need to run our insert into the database. For that, we are using the sqlx method called NamedExec that is a simple execute to database, but that parses our parameters list from the command, and map them to the struct fields we passed in the second argument, in a way we don’t need to use positional arguments, and pass a lot of arguments to the exec.</p><p>Another error validation and <em>voilà</em> we have a function user insertion on database, and just return the inserted user with the id, and nil to show that no error occurred. Now that we already have a user into the database, lets see how to read it.</p><h4>Retrieving a user from database</h4><p>To read the user from database, we will take advantage again from the helper methods of the sqlx package, in this case the db.Get method, that requests three arguments. The first one is a pointer to the target struct, that will be mapped by reflection, the seconds is the query we want to run, and the third is the positional argument ? in the select query.</p><p>The Get method returns an error when it fails, so we don’t need to add a lot of error handling here, just returning the user struct we defined before, and the error that will be nil if the methods execute correctly, on an error object when it fails, just as our method.</p><h4>Updating user</h4><p>Now to update the user, we will put some rules as we don’t want our update user method to update the id, password, or set the user as admin, to guarantee it, our update will only be used to update email and name fields.</p><p>To do this, our update SQL command doesn’t have the fields in the command, and we implement a <a href="https://gobyexample.com/variadic-functions">variadic method</a> called updateUser in lowercase, to avoid being exposed outside the package, that receives a user struct, that has the data we are going to update, and the variadic argument, that is any number of arguments, that will be received as a slice, that makes it easier to be invoked without the developer initiate a slice to pass as argument, as we can see in line 67. Now we just need to call the internal updateUser in our public Update method.</p><h4>Deleting a user</h4><p>To complete our CRUD operations, we already have the <strong>C</strong>reate, <strong>R</strong>ead and <strong>U</strong>pdate, now we will implement the delete operation. As delete is a simple operation, we will only run the SQL command, and return the error, if it happens.</p><h4>Exposing the endpoints</h4><p>Now that we already have all the CRUD operations implemented in our repository, all we need to do is expose the /user endpoints, to do that let’s create a new file called user/routes.go just like this one below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/472ed87f68437744d35092227002186f/href">https://medium.com/media/472ed87f68437744d35092227002186f/href</a></iframe><p>As we already got into package and import a lot of time, from this point on, and in the next articles, I will get straight to implementation, unless there is something especial in the package or import sections.</p><h4>Creating a UserHandler</h4><p>In order to make our dependencies management easier, lets create a struct called userHandler as showed in line 13, to use it as a container for our render, database and repository, and create it’s constructor (line 19) that will receive only the database, and with this database we will create the repository.</p><p>It is important to notice that we are not exposing our userHandler and its constructor outside of the package, as both of them are lowercase, but we expose the RegisterRoutes method that will register the routes in a given router, keeping the endpoint registration encapsulated inside the package.</p><p>As this article is getting a lot bigger than I expected, I will go a little faster here. We are exposing four endpoints, one for each CRUD operations base on REST HTTP verbs, we are not exposing a GET for the list of users right now. To do this, on line 99 we create a route group /user and pass a function in the second argument that receiver a router that is related to this group. In this function we relate each handler function to its endpoint.</p><p>One point that is important to show is that we use an {id} in the route definition, and this is the name of the param we will retrieve inside the methods using chi.URLParam(r, &quot;id&quot;) that returns the value of the given param or an empty string when not found.</p><p>To read the data in createUser and updateUser we’ve created a method called getUserFromRequest that reads the data from the request body using json.Decoder struct and parses to a User variable using the Decode method.</p><p>To return errors I’m using the http.Error method and returning the errors as plain text for now (we will improve it later) just for simplicity.</p><h4>Registering handler in our app (almost over)</h4><p>I know this article got really big, but we are almost there now. In the end of the part 1, we already had a main.go file with a working http listener. Now we just need to update it as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ed7a956e1cabf916c7b0f27c6e56894/href">https://medium.com/media/8ed7a956e1cabf916c7b0f27c6e56894/href</a></iframe><p>To highlight the changes, we added a middleware from chi on line 16 just to get a logger to output the received requests and the time it took to respond and also added in the line 27, the calls the user.RegisterRoutes that we register all our user handlers.</p><h4>(Finally) Running our app</h4><p>Now, given that you have a localhost MySQL instance running or running in docker and with port mapped to localhost, you just need to run go run *.go to see the magic happening. Use your favorite request client to make some requests and you will see in your console the Logger from chi middleware printing them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1vuRlvgaMSdq9ytl2uEbwA.png" /><figcaption>Console output</figcaption></figure><h4>Conclusion</h4><p>That was all of it, I know it was longer than expected but I hope I made clear what, how and why each part was done that way. In the next article I will get into testing our API just as it is now. If you got into any trouble, <a href="https://github.com/felipecaputo/go-voting-api/tree/part-2">all source code of this article can be found here</a>.</p><p>I would also like to thank a lot to my colleagues <a href="https://medium.com/u/b26c2029e1d2">Erick Oliveira,</a> <a href="https://medium.com/u/8a8cbb9714ee">Niccolas Costa,</a> <a href="https://medium.com/u/17539b9f3131">João Miguel Noronha</a> e Diego Alves for reviewing and giving me feedback about it.</p><p>I hope you liked the reading, and would love to get your feedback about this article or the series. See you all in the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed9f70d46ff3" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/building-an-api-with-golang-in-2020-part-2-ed9f70d46ff3">Building an API with Golang in 2020 — Part 2</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an API with Golang in 2020 — Part 1]]></title>
            <link>https://blog.devgenius.io/building-an-api-with-golang-in-2020-part-1-bfe61ac8ae8?source=rss-31e9d3577043------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfe61ac8ae8</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Felipe Caputo]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 01:33:41 GMT</pubDate>
            <atom:updated>2020-08-05T08:40:45.213Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*noNAPXiTjNJRaB9BLPmzow.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Emile Perron</a> on <a href="https://unsplash.com/s/photos/code?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Building an API with Golang in 2020 — Part 1</h3><p>Before start in this new job at Mercado Livre this year, I was already in love with Golang, made a small API for internal use in my previous job and some side projects, but nothing really production ready.</p><p>In the last three months, I’ve had an amazing immersion and learned a lot from all colleagues and teammates and I think that it would be nice to share my experiences and what a learned by building a project using the good practices I’m learning.</p><p>The idea of this article and some others that I intend to write started when I read <a href="https://medium.com/@diegoholiveira/how-im-organizing-my-go-applications-bc543f2316b2">this great article</a> from <a href="https://medium.com/u/a72b03d3464f">Diego Henrique Oliveira,</a> and found it amazing, and it inspired me to build something using his ideas of project organization.</p><p>The main idea is to build a <strong>Voting API </strong>where we would have CRUD operations and also API operations and validations, and apply some concepts as <em>Clean Architecture, package management, Domain Isolation, Dependency Injection</em> and so on. We will also get a little use of Docker, and deploy our API with a CI. That said, let’s get started!</p><h3>Starting a project</h3><p>We will start by initializing the project with support to <strong>Go Modules</strong>, which is the default package manager since Go 1.13. To do this, create your source folder, in my case go-voting-api wherever you prefer to keep your project, open a terminal in that folder and run:</p><pre>$ go mod init github.com/$yourGithubName/go-voting-api<br>$ git init</pre><p>This command will create two files in your root folder, go.mod that will keep track of your dependencies and its versions. For more details, <a href="https://blog.golang.org/using-go-modules">this blog post</a> is great.</p><p>Go already come out-of-the-box with a great HTTP package, but we will use in this example <a href="https://github.com/go-chi/chi">Chi</a>, that is an incredible HTTP Router, with middleware support. At this point, we will install manually the chi package using go get as shown below. We will not need to install every package using go get since go mod already identify imports that are not met at build time, and install them. Another important info about go mod is that, as it imports automatically, some times it could keep track of some packages that we are not using anymore, and you can run go mod tidy to remove unused packages.</p><pre>go get github.com/go-chi/chi</pre><p><strong>Building the first route</strong></p><p>With our main dependencies installed, we will start our app by creating a simple /health endpoint, just to see our server running fine. To do that, create a main.go file, that will create a router and start a server, handling our health route.</p><pre><strong>package</strong> main<br><br><strong>import</strong> (<br>	&quot;fmt&quot;<br>	&quot;net/http&quot;<br><br>	&quot;github.com/go-chi/chi&quot;<br>)<br><br><strong>func</strong> main() {<br>	router := chi.NewRouter()<br>	router.Get(&quot;/health&quot;, <strong>func</strong>(w http.ResponseWriter, r *http.Request) {<br>		fmt.Fprint(w, &quot;healthy&quot;)<br>	})<br><br>	fmt.Println(&quot;Starting server...&quot;)<br>	err := http.ListenAndServe(&quot;:8080&quot;, router)<br>	if err != nil {<br>		fmt.Printf(&quot;Error starting server: %s&quot;, err)<br>	}<br>}</pre><p>Let’s break into pieces to make it more understandable. In the first line, we typed package main to tell go that we are building an app, and this is the main package of the app. After that, we import some packages from Go Standard Lib, fmt to handle logs and string operations, such as writing the response string to the response stream, and net/http to handle our HTTP requests and start the server. The last import is to import Chi that will be our router over the standard HTTP package.</p><p>After that we create a main function that tells go that, this is the function that initializes our app, the main function of the main package. In this function we start our Chi Router, and set a route to GET /health and sets a default <a href="https://golang.org/pkg/net/http/#HandlerFunc">HTTP handler function</a>, to handle the request.</p><p>After that we use the method ListenAndServe from the http package to start a server, passing the port in the first argument, and our router as the second argument.</p><p>In the if err != nil { just after the ListenAndServe we can see how Golang handle errors. Every function that could raise an error will return an error as one of its results, and then we need to check if that error is not empty to handle the error.</p><p>Now you just need to run in your terminal go run main.go and you will see our log line, telling that the server is starting, and if you visit http://localhost:8080, you will see our Healthy response.</p><h3>Conclusion</h3><p>This article ended up a bit bigger than I expected, but I hope it is well explained and could help you, and any feedback is welcome. You can see the source we build in the <a href="https://github.com/felipecaputo/go-voting-api">article repository</a>, and in the next one, we will add the database to our API.</p><p>Enjoy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfe61ac8ae8" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/building-an-api-with-golang-in-2020-part-1-bfe61ac8ae8">Building an API with Golang in 2020 — Part 1</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>