<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Janire Fernandez</title>
    <description>The latest articles on DEV Community by Janire Fernandez (@janirefdez).</description>
    <link>https://dev.to/janirefdez</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F905922%2Fc30f44b7-47e2-47ef-90b1-f956a0af24fd.jpeg</url>
      <title>DEV Community: Janire Fernandez</title>
      <link>https://dev.to/janirefdez</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/janirefdez"/>
    <language>en</language>
    <item>
      <title>Android Jetpack Compose MVVM</title>
      <dc:creator>Janire Fernandez</dc:creator>
      <pubDate>Sun, 20 Nov 2022 01:56:13 +0000</pubDate>
      <link>https://dev.to/janirefdez/android-jetpack-compose-mvvm-1nji</link>
      <guid>https://dev.to/janirefdez/android-jetpack-compose-mvvm-1nji</guid>
      <description>&lt;p&gt;I will show you how I've created the screen views with &lt;code&gt;Jetpack Componse&lt;/code&gt; for this &lt;a href="https://github.com/janirefdez/JetpackComposeMVVM" rel="noopener noreferrer"&gt;example&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxvncimbyuhhmstcn1e2v.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxvncimbyuhhmstcn1e2v.gif" alt="Jetpack Compose App" width="600" height="1333"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First, lets explain the basics&lt;/p&gt;

&lt;h2&gt;
  
  
  What is MVVM architecture?
&lt;/h2&gt;

&lt;p&gt;Model — View — ViewModel (MVVM) is the industry-recognized software architecture pattern that overcomes all drawbacks of MVP and MVC design patterns. MVVM suggests separating the data presentation logic(Views or UI) from the core business logic part of the application. &lt;/p&gt;

&lt;p&gt;The separate code layers of MVVM are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Model&lt;/strong&gt;: This layer is responsible for the abstraction of the data sources. Model and ViewModel work together to get and save the data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;View&lt;/strong&gt;: The purpose of this layer is to inform the ViewModel about the user’s action. This layer observes the ViewModel and does not contain any kind of application logic.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;ViewModel&lt;/strong&gt;: It exposes those data streams which are relevant to the View. Moreover, it serves as a link between the Model and the View.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is Jetpack Compose?
&lt;/h2&gt;

&lt;p&gt;Jetpack Compose is Android’s recommended modern toolkit for building native UI. It simplifies and accelerates UI development on Android. Quickly bring your app to life with less code, powerful tools, and intuitive Kotlin APIs.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Now we are ready to start with the project!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;*Note: In this article I will only explain how the screen views have been defined. If you want to know more, you can check the whole project on Github: &lt;a href="https://github.com/janirefdez/JetpackComposeMVVM" rel="noopener noreferrer"&gt;JetpackComposeMVVM&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3j7hn51ujc8jm9w8fhv1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3j7hn51ujc8jm9w8fhv1.png" alt="Project structure" width="530" height="1084"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Jetpack Compose
&lt;/h3&gt;

&lt;p&gt;To be able to display a list of Categories we first need to define how one category should be displayed. In this case we have the following (code below images):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyorme44ewzjti5s05o18.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyorme44ewzjti5s05o18.png" alt="CategoryItem" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We also need to understand what are &lt;code&gt;Rows&lt;/code&gt; and &lt;code&gt;Columns&lt;/code&gt; in Jetpack Compose:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Row: It arranges the views horizontally. &lt;/li&gt;
&lt;li&gt;Column: It arranges the views vertically. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftfy6w6cis3g7yt3ft9kq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftfy6w6cis3g7yt3ft9kq.png" alt="Row and Columns in Jetpack Compose" width="800" height="546"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this case we have a Row to display the &lt;code&gt;Image&lt;/code&gt;, &lt;code&gt;Title&lt;/code&gt; and &lt;code&gt;Description&lt;/code&gt;. But we also have a column which contains the &lt;code&gt;Title&lt;/code&gt; and &lt;code&gt;Description&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The code for displaying a Category Item is the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Composable
fun CategoryItem(category: Category, context: Context, onClickListener: (Category) -&amp;gt; Unit) {
    Card(
        modifier = Modifier
            .padding(8.dp, 4.dp)
            .fillMaxWidth()
            .height(300.dp)
            .clickable { onClickListener.invoke(category) },
        shape = RoundedCornerShape(25.dp),
    ) {
        Surface(
            color = Color.LightGray
        ) {

            Row(
                Modifier
                    .padding(4.dp)
                    .fillMaxSize()
            ) {

                Image(
                    painter = rememberAsyncImagePainter(
                        model = category.strThumb,
                        imageLoader = ImageLoader.Builder(context).crossfade(true).build()
                    ),
                    contentDescription = category.str,
                    modifier = Modifier
                        .fillMaxHeight()
                        .weight(0.2f)
                )
                Column(
                    verticalArrangement = Arrangement.Center,
                    modifier = Modifier
                        .padding(4.dp)
                        .fillMaxHeight()
                        .weight(0.8f)
                ) {
                    Text(
                        text = category.str,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                    Text(
                        text = category.strDescription,
                        style = MaterialTheme.typography.bodyMedium
                    )
                }
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once we have how one category should look like, we can define how the list should be displayed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Composable
fun CategoryList(
    categoryList: List&amp;lt;Category&amp;gt;,
    context: Context,
    onClickListener: (Category) -&amp;gt; Unit
) {
    LazyColumn {
        itemsIndexed(items = categoryList) { _, item -&amp;gt;
            CategoryItem(category = item, context, onClickListener)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case we define a &lt;code&gt;LazyColumn&lt;/code&gt; which is a vertically scrolling list that only composes and lays out the currently visible items. It’s similar to a Recyclerview in the classic Android View system.&lt;/p&gt;

&lt;p&gt;The result is the following:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fce9tnxwn5mvhxkhnxvc1.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fce9tnxwn5mvhxkhnxvc1.jpg" alt="Category List" width="576" height="1280"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we need to call CategoryList method in the MainActivity:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    private val viewModel: MainViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MealRecipesTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    CategoryList(categoryList = viewModel.categoryList, context = this) {
                        val intent = Intent(this@MainActivity, DetailActivity::class.java).apply {
                            putExtra(DetailActivity.DETAIL_CATEGORY, it)
                        }
                        intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
                        startActivity(intent)
                    }
                    viewModel.getCategories()

                }
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that when a category is clicked, another view will be displayed with the information of the category selected. This can be done because in the CategoryItem compose function we have:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.clickable { onClickListener.invoke(category) }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When clicking on a Category we go to another activity (there is an &lt;code&gt;Intent&lt;/code&gt; in the MainActivity that will be called when the category is clicked). &lt;/p&gt;

&lt;p&gt;The new activity, DetailActivity, displays again the &lt;code&gt;Title&lt;/code&gt;,&lt;code&gt;Description&lt;/code&gt; and the &lt;code&gt;Image&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;The compose function looks like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvloxku5aycp5cxfzc9sx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvloxku5aycp5cxfzc9sx.png" alt="Detail Category View" width="800" height="447"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Composable
fun CategoryItem(category: Category, context: Context) {
    Surface(
        modifier = Modifier
            .padding(4.dp)
            .fillMaxHeight(),
        color = Color.White,
    ) {
        Column(
            verticalArrangement = Arrangement.Top,
            modifier = Modifier
                .padding(20.dp)
                .fillMaxHeight()
        ) {

            Text(
                text = category.str,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold,
                modifier = Modifier
                    .padding(25.dp)
            )
            Image(
                painter = rememberAsyncImagePainter(
                    model = category.strThumb,
                    imageLoader = ImageLoader.Builder(context).crossfade(true).build()
                ),
                contentDescription = category.str,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 25.dp)
            )
            Text(
                text = category.strDescription,
                style = MaterialTheme.typography.bodyMedium,
                modifier = Modifier
                    .padding(25.dp)
            )

        }


    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we need to call CategoryItem function in the DetailActivity:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@AndroidEntryPoint
class DetailActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val category = if (Build.VERSION.SDK_INT &amp;gt;= Build.VERSION_CODES.TIRAMISU) {
            intent.getSerializableExtra(DETAIL_CATEGORY, Serializable::class.java) as Category
        } else {
            @Suppress("DEPRECATION")
            intent.getSerializableExtra(DETAIL_CATEGORY) as Category
        }
        setContent {
            MealRecipesTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    CategoryItem(category = category, context = this@DetailActivity)
                }
            }
        }
    }

    companion object {
        const val DETAIL_CATEGORY = "detail_category"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result is the following: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F49649o5c7pv8j3wvcfx0.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F49649o5c7pv8j3wvcfx0.jpg" alt="Category in detail" width="576" height="1280"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And that's all!! That's how you create screen views with Jetpack Compose. Hope you enjoyed!!&lt;/p&gt;

&lt;p&gt;If you want to check the whole project here you have the link: &lt;a href="https://github.com/janirefdez/JetpackComposeMVVM" rel="noopener noreferrer"&gt;JetpackComposeMVVM&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Don't forget to like and share! Thank you! :)&lt;/p&gt;

</description>
      <category>vue</category>
      <category>opensource</category>
    </item>
    <item>
      <title>Connect REST API to database with Go</title>
      <dc:creator>Janire Fernandez</dc:creator>
      <pubDate>Sat, 15 Oct 2022 15:27:54 +0000</pubDate>
      <link>https://dev.to/janirefdez/connect-rest-api-to-database-with-go-d8m</link>
      <guid>https://dev.to/janirefdez/connect-rest-api-to-database-with-go-d8m</guid>
      <description>&lt;p&gt;In previous tutorial we learned how to &lt;a href="https://dev.to/janirefdez/create-a-rest-api-with-go-1j52"&gt;create a REST API with Go&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we are going to connect this API to a database. We will use PostgreSQL.&lt;/p&gt;

&lt;p&gt;If you want to check the whole project here you have the link: &lt;a href="https://github.com/janirefdez/ArticleRestApi/tree/database-connection" rel="noopener noreferrer"&gt;ArticleRestApi&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Create database
&lt;/h2&gt;

&lt;p&gt;To create a database we are going to use a Docker image. Make sure you have &lt;a href="https://www.docker.com/get-started/" rel="noopener noreferrer"&gt;docker installed&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;*&lt;code&gt;A Docker image is a read-only template that contains a set of instructions for creating a container that can run on the Docker platform.&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;Create a file &lt;code&gt;docker-compose.yml&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;version: "3.8"
services:
  database:
    container_name: database
    image: postgres
    ports:
      - "5432:5432"
    volumes:
      - ./database:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=articlesDB
      - POSTGRES_USER=janire
      - POSTGRES_PASSWORD=password
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;This will pull the postgres image from the Docker Hub.&lt;/li&gt;
&lt;li&gt;The container opens port &lt;code&gt;5432&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;It sets the environment variables to use when connecting to the database.&lt;/li&gt;
&lt;li&gt;The volume is needed so the data persists inside the container at &lt;code&gt;/var/lib/postgresql/data&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To start the docker container use command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker-compose up -d
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can stop it by doing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker-compose down
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2xwhwvbrppv9saky2vit.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2xwhwvbrppv9saky2vit.png" alt="Database Container" width="800" height="284"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Connect to database
&lt;/h2&gt;

&lt;p&gt;Now that the database is created let's connect to it. In my case I will be using &lt;a href="https://tableplus.com/" rel="noopener noreferrer"&gt;TablePlus&lt;/a&gt;, but you can use other database management. &lt;/p&gt;

&lt;p&gt;We need to create a new connection with details defined in &lt;code&gt;docker-compose.yml&lt;/code&gt;.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkcar9va95gq4m2ujs7v0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkcar9va95gq4m2ujs7v0.png" alt="Database connection details" width="800" height="625"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Connect to database with Go
&lt;/h2&gt;

&lt;p&gt;Go’s standard library was not built to include any specific database drivers. So we need to install a third party package. In this case we are going to install &lt;a href="https://github.com/lib/pq" rel="noopener noreferrer"&gt;https://github.com/lib/pq&lt;/a&gt;. Run following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go get github.com/lib/pq
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see that the dependency has been included in file called &lt;code&gt;go.mod&lt;/code&gt; and &lt;code&gt;go.sum&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Now we are going to create &lt;code&gt;db.go&lt;/code&gt; file in package &lt;code&gt;pkg/db&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package db

import (
    "database/sql"
    "fmt"
    "log"

    "github.com/janirefdez/ArticleRestApi/pkg/mocks"
    _ "github.com/lib/pq"
)

const (
    host     = "localhost"
    port     = 5432
    user     = "janire"
    password = "password"
    dbname   = "articlesDB"
)

func Connect() *sql.DB {
    connInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        host, port, user, password, dbname)

    db, err := sql.Open("postgres", connInfo)
    if err != nil {
        log.Fatal(err)
    }
    err = db.Ping()
    if err != nil {
        panic(err)
    }
    fmt.Println("Successfully connected to db!")
    return db
}

func CloseConnection(db *sql.DB) {
    defer db.Close()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Connection information is defined in our &lt;code&gt;docker-compose.yml&lt;/code&gt; file.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sql.Open()&lt;/code&gt; connects to the database.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now that we have the database setup, we need to think where to start the connection. We cannot connect in each handler as this will create lots of database connections.&lt;/p&gt;

&lt;p&gt;We will use dependency injection to pass only one database connection to all the handlers. &lt;/p&gt;

&lt;p&gt;Create file &lt;code&gt;handler.go&lt;/code&gt; in &lt;code&gt;pkg/handlers&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package handlers

import "database/sql"

type handler struct {
    DB *sql.DB
}

func New(db *sql.DB) handler {
    return handler{db}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The structure of the project in our example should now be like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;├── cmd
│   └── main.go
├── pkg
│    ├── db
│    │   └── db.go
│    ├── handlers
│    │   ├── AddArticle.go
│    │   ├── DeleteArticle.go
│    │   ├── GetAllArticles.go
│    │   ├── GetArticle.go
│    │   ├── UpdateArticle.go
│    │   └── Handler.go
│    ├── mocks
│    │   └── article.go
│    └── models
│        └── article.go
├── go.sum
└── go.mod

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lets include the dependency in the handlers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;GetAllArticles
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func (h handler) GetAllArticles(w http.ResponseWriter, r *http.Request) { ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Get Article By Id
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func (h handler) GetArticle(w http.ResponseWriter, r *http.Request) { ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create new Article
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func (h handler) AddArticle(w http.ResponseWriter, r *http.Request) { ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Update Article by id
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func (h handler) UpdateArticle(w http.ResponseWriter, r *http.Request) { ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Delete Article by id
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func (h handler) DeleteArticle(w http.ResponseWriter, r *http.Request) {
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's change the &lt;code&gt;cmd/main.go&lt;/code&gt; to start the database connection:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func handleRequests(DB *sql.DB) {
    h := handlers.New(DB)
    // create a new instance of a mux router
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/", homePage)
    myRouter.HandleFunc("/articles", h.GetAllArticles).Methods(http.MethodGet)
    myRouter.HandleFunc("/articles/{id}", h.GetArticle).Methods(http.MethodGet)
    myRouter.HandleFunc("/articles", h.AddArticle).Methods(http.MethodPost)
    myRouter.HandleFunc("/articles/{id}", h.UpdateArticle).Methods(http.MethodPut)
    myRouter.HandleFunc("/articles/{id}", h.DeleteArticle).Methods(http.MethodDelete)
    log.Fatal(http.ListenAndServe(":8080", myRouter))
}

func main() {
    DB := db.Connect()
    handleRequests(DB)
    db.CloseConnection(DB)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you now run the API you should see message :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;% go run cmd/main.go
Successfully connected to db!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But we still have to update the functions of the handlers to use the database information instead of the mocks defined in &lt;code&gt;pkg/mocks/article.go&lt;/code&gt; and we also have to create a table 'articles' in the database. So let's start with that.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Create table in database with Go
&lt;/h2&gt;

&lt;p&gt;We can create a table directly with &lt;code&gt;TablePlus&lt;/code&gt; or we can create it with the code. These are the SQL queries we will use: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;To create the table 'articles':
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE articles (id VARCHAR(36) PRIMARY KEY, title VARCHAR(100) NOT NULL, description VARCHAR(50) NOT NULL, content VARCHAR(50) NOT NULL);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;To know if table 'articles' already exists:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT EXISTS (SELECT FROM pg_tables WHERE  schemaname = 'public' AND tablename = 'articles' );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or when creating the table we can include &lt;code&gt;IF NOT EXISTS&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE IF NOT EXISTS  articles  (id VARCHAR(36) PRIMARY KEY, title VARCHAR(100) NOT NULL, description VARCHAR(50) NOT NULL, content VARCHAR(50) NOT NULL);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;To include data in table 'articles':
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSERT INTO articles (id,title,description,content) VALUES ('8617bf49-39a9-4268-b113-7b6bcd189ba2', 'Article 1', 'Article Description 1', 'Article Content 1');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example we will create the table with Go so let's create a new function in &lt;code&gt;pkg/db/db.go&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func CreateTable(db *sql.DB) {
    var exists bool
    if err := db.QueryRow("SELECT EXISTS (SELECT FROM pg_tables WHERE  schemaname = 'public' AND tablename = 'articles' );").Scan(&amp;amp;exists); err != nil {
        fmt.Println("failed to execute query", err)
        return
    }
    if !exists {
        results, err := db.Query("CREATE TABLE articles (id VARCHAR(36) PRIMARY KEY, title VARCHAR(100) NOT NULL, description VARCHAR(50) NOT NULL, content VARCHAR(50) NOT NULL);")
        if err != nil {
            fmt.Println("failed to execute query", err)
            return
        }
        fmt.Println("Table created successfully", results)

        for _, article := range mocks.Articles {
            queryStmt := `INSERT INTO articles (id,title,description,content) VALUES ($1, $2, $3, $4) RETURNING id;`

            err := db.QueryRow(queryStmt, &amp;amp;article.Id, &amp;amp;article.Title, &amp;amp;article.Desc, &amp;amp;article.Content).Scan(&amp;amp;article.Id)
            if err != nil {
                log.Println("failed to execute query", err)
                return
            }
        }
        fmt.Println("Mock Articles included in Table", results)
    } else {
        fmt.Println("Table 'articles' already exists ")
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will call this function in &lt;code&gt;cmd/main.go&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    DB := db.Connect()
    db.CreateTable(DB)
    handleRequests(DB)
    db.CloseConnection(DB)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you run the API it will first create the database and insert data into it. You should now be able to see content in your database:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq9wq0rdp31uv747vqash.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq9wq0rdp31uv747vqash.png" alt="Table articles" width="800" height="139"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Update handlers
&lt;/h2&gt;

&lt;p&gt;We already have a database with articles and we are able to create a connection with Go. Now its time to modify the handlers so our API works with the database instead of the mocks defined in &lt;code&gt;pkg/mocks/article.go&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Get All Articles
&lt;/h3&gt;

&lt;p&gt;In &lt;code&gt;pkg/handlers/GetAllArticles.go&lt;/code&gt; we need to use query &lt;code&gt;SELECT * FROM articles;&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func (h handler) GetAllArticles(w http.ResponseWriter, r *http.Request) {

    results, err := h.DB.Query("SELECT * FROM articles;")
    if err != nil {
        log.Println("failed to execute query", err)
        w.WriteHeader(500)
        return
    }

    var articles = make([]models.Article, 0)
    for results.Next() {
        var article models.Article
        err = results.Scan(&amp;amp;article.Id, &amp;amp;article.Title, &amp;amp;article.Desc, &amp;amp;article.Content)
        if err != nil {
            log.Println("failed to scan", err)
            w.WriteHeader(500)
            return
        }

        articles = append(articles, article)
    }

    w.Header().Add("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(articles)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The method returns results, which is of type &lt;code&gt;sql.Rows&lt;/code&gt;. This stores the result of a query, row by row. So we need to go thought the list and scan the content.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2vpjhj9qqriutec1hnzs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2vpjhj9qqriutec1hnzs.png" alt="Get All Articles Paw" width="800" height="473"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Get Article By Id
&lt;/h3&gt;

&lt;p&gt;In &lt;code&gt;pkg/handlers/GetArticle.go&lt;/code&gt; we need to use query &lt;code&gt;SELECT * FROM articles WHERE id = $1 ;&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func (h handler) GetArticle(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]

    queryStmt := `SELECT * FROM articles WHERE id = $1 ;`
    results, err := h.DB.Query(queryStmt, id)
    if err != nil {
        log.Println("failed to execute query", err)
        w.WriteHeader(500)
        return
    }

    var article models.Article
    for results.Next() {
        err = results.Scan(&amp;amp;article.Id, &amp;amp;article.Title, &amp;amp;article.Desc, &amp;amp;article.Content)
        if err != nil {
            log.Println("failed to scan", err)
            w.WriteHeader(500)
            return
        }
    }

    w.Header().Add("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(article)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fctgvy0z8ejg4ej7edef5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fctgvy0z8ejg4ej7edef5.png" alt="Get Article Paw" width="800" height="344"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Create new Article
&lt;/h3&gt;

&lt;p&gt;In &lt;code&gt;pkg/handlers/AddArticle.go&lt;/code&gt; we need to use query &lt;code&gt;INSERT INTO articles (id,title,description,content) VALUES ($1, $2, $3, $4)&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func (h handler) AddArticle(w http.ResponseWriter, r *http.Request) {
    // Read to request body
    defer r.Body.Close()
    body, err := ioutil.ReadAll(r.Body)

    if err != nil {
        log.Fatalln(err)
        w.WriteHeader(500)
        return
    }
    var article models.Article
    json.Unmarshal(body, &amp;amp;article)

    article.Id = (uuid.New()).String()
    queryStmt := `INSERT INTO articles (id,title,description,content) VALUES ($1, $2, $3, $4) RETURNING id;`
    err = h.DB.QueryRow(queryStmt, &amp;amp;article.Id, &amp;amp;article.Title, &amp;amp;article.Desc, &amp;amp;article.Content).Scan(&amp;amp;article.Id)
    if err != nil {
        log.Println("failed to execute query", err)
        w.WriteHeader(500)
        return
    }

    w.Header().Add("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode("Created")

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6uszqro1sik6axta8usq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6uszqro1sik6axta8usq.png" alt="Add article Paw" width="800" height="192"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Update Article by id
&lt;/h3&gt;

&lt;p&gt;In &lt;code&gt;pkg/handlers/UpdateArticle.go&lt;/code&gt; we need to use query &lt;code&gt;UPDATE articles SET title = $2, description = $3, content = $4 WHERE id = $1 RETURNING id;&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func (h handler) UpdateArticle(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]

    // Read request body
    defer r.Body.Close()
    body, err := ioutil.ReadAll(r.Body)

    if err != nil {
        log.Fatalln(err)
    }

    var updatedArticle models.Article
    json.Unmarshal(body, &amp;amp;updatedArticle)

    queryStmt := `UPDATE articles SET title = $2, description = $3, content = $4 WHERE id = $1 RETURNING id;`
    err = h.DB.QueryRow(queryStmt, &amp;amp;id, &amp;amp;updatedArticle.Title, &amp;amp;updatedArticle.Desc, &amp;amp;updatedArticle.Content).Scan(&amp;amp;id)
    if err != nil {
        log.Println("failed to execute query", err)
        w.WriteHeader(500)
        return
    }

    w.Header().Add("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode("Updated")

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyxnwlng2aqazoo6olx6k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyxnwlng2aqazoo6olx6k.png" alt="Update Article Paw" width="800" height="190"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Delete Article by id
&lt;/h3&gt;

&lt;p&gt;In &lt;code&gt;pkg/handlers/DeleteArticle.go&lt;/code&gt; we need to use query &lt;code&gt;DELETE FROM articles WHERE id = $1;&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func (h handler) DeleteArticle(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]

    queryStmt := `DELETE FROM articles WHERE id = $1;`
    _, err := h.DB.Query(queryStmt, &amp;amp;id)
    if err != nil {
        log.Println("failed to execute query", err)
        w.WriteHeader(500)
        return
    }

    w.Header().Add("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode("Deleted")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuuv4opbf6k3p8gdzytm3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuuv4opbf6k3p8gdzytm3.png" alt="Delete Article Paw" width="800" height="228"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And that's all!! You have an API that connects to a database. Hope you enjoyed!!&lt;/p&gt;

&lt;h2&gt;
  
  
  Improvements
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Include error response when an article is not found.&lt;/li&gt;
&lt;li&gt;Include tests.&lt;/li&gt;
&lt;li&gt;...&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you want to check the whole project here you have the link: &lt;a href="https://github.com/janirefdez/ArticleRestApi" rel="noopener noreferrer"&gt;ArticleRestApi&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Don't forget to like and share! Thank you! :)&lt;/p&gt;

</description>
      <category>go</category>
      <category>rest</category>
      <category>api</category>
      <category>postgres</category>
    </item>
    <item>
      <title>Create a REST API with Go</title>
      <dc:creator>Janire Fernandez</dc:creator>
      <pubDate>Mon, 10 Oct 2022 18:06:35 +0000</pubDate>
      <link>https://dev.to/janirefdez/create-a-rest-api-with-go-1j52</link>
      <guid>https://dev.to/janirefdez/create-a-rest-api-with-go-1j52</guid>
      <description>&lt;p&gt;In this &lt;a href="https://github.com/janirefdez/ArticleRestApi" rel="noopener noreferrer"&gt;example&lt;/a&gt; we will create a simple REST API with Go. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Get all articles.&lt;/li&gt;
&lt;li&gt;Get specific article.&lt;/li&gt;
&lt;li&gt;Add new article.&lt;/li&gt;
&lt;li&gt;Update Article.&lt;/li&gt;
&lt;li&gt;Delete article.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's get started!&lt;/p&gt;

&lt;h2&gt;
  
  
  Install Go
&lt;/h2&gt;

&lt;p&gt;Make sure that Go language is installed in your system. Open a new terminal and run the following command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go version
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It should print the Go language version that you have. &lt;br&gt;
Otherwise install the Go language before proceeding.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;brew install go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Create a new Go project
&lt;/h2&gt;

&lt;p&gt;First, create a new directory for the Go project and go into the directory created.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir articleRestApi

cd articleRestApi
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we need to create the project module with the &lt;code&gt;go mod init &amp;lt;path&amp;gt;&lt;/code&gt; command. &lt;br&gt;
The module path normally is the URL where you publish your project. In my case it will be &lt;code&gt;github.com/janirefdez/ArticleRestApi&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go mod init github.com/janirefdez/ArticleRestApi
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command will create a file called &lt;code&gt;go.mod&lt;/code&gt;. It will contain information about the Go module path and the Go language version. When adding more dependencies to the project, they will be mentioned in this file.&lt;/p&gt;

&lt;h2&gt;
  
  
  Set up
&lt;/h2&gt;

&lt;p&gt;In this example we are going to use a &lt;a href="https://github.com/gorilla/mux" rel="noopener noreferrer"&gt;gorilla/mux&lt;/a&gt; router instead of the traditional net/http router.&lt;/p&gt;

&lt;p&gt;And we are also going to use &lt;a href="https://github.com/google/uuid" rel="noopener noreferrer"&gt;google/uuid&lt;/a&gt; to generate random uuids.&lt;/p&gt;

&lt;p&gt;Run the following command to be able to use &lt;code&gt;gorilla/mux&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go get github.com/gorilla/mux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And for &lt;code&gt;google/uuid&lt;/code&gt; run&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go get github.com/google/uuid
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see that in &lt;code&gt;go.mod&lt;/code&gt; it should appear the dependencies &lt;code&gt;gorilla/mux&lt;/code&gt; and &lt;code&gt;google/uuid&lt;/code&gt;. And a new file &lt;code&gt;go.sum&lt;/code&gt; should have been created. &lt;/p&gt;

&lt;h2&gt;
  
  
  Create the base for our API
&lt;/h2&gt;

&lt;p&gt;Now let's create the &lt;code&gt;main.go&lt;/code&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;touch main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and add the following code to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func homePage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Welcome to the Article REST API!")
    fmt.Println("Article REST API")
}

func handleRequests() {
    // create a new instance of a mux router
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/", homePage)
    log.Fatal(http.ListenAndServe(":8080", myRouter))
}

func main() {
    handleRequests()
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This has:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A homePage function that will handle all requests to our root URL.&lt;/li&gt;
&lt;li&gt;A handleRequests function that will match the URL path hit with a defined function&lt;/li&gt;
&lt;li&gt;A main function which will kick off our REST API.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's run our API to see what happens ;)!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go run main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you now check &lt;code&gt;http://localhost:8080/&lt;/code&gt; you should see message &lt;code&gt;Welcome to the Article REST API!&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcf30dwqxx35ep201d2u0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcf30dwqxx35ep201d2u0.png" alt="Welcome to the Article REST API!" width="536" height="188"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This means we have now successfully created the base for our REST API. &lt;/p&gt;

&lt;p&gt;But first we need to organize the project because we don't want to code everything on &lt;code&gt;main.go&lt;/code&gt;. So let's move &lt;code&gt;main.go&lt;/code&gt; to a new directory called &lt;code&gt;cmd&lt;/code&gt;. At this point the project structure should look like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;├── cmd
│   └── main.go
├── go.sum
└── go.mod
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Create Article Model and Mock
&lt;/h2&gt;

&lt;p&gt;Now we need to define our Article model. In this example, Article will contain an &lt;code&gt;Id&lt;/code&gt;, a &lt;code&gt;Title&lt;/code&gt;, a &lt;code&gt;Description&lt;/code&gt; and &lt;code&gt;Content&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Let's create file &lt;code&gt;pkg/models/article.go&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package models

type Article struct {
    Id      string `json:"Id"`
    Title   string `json:"Title"`
    Desc    string `json:"desc"`
    Content string `json:"content"`
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and also create mocks for that Article model &lt;code&gt;pkg/mocks/article.go&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package mocks

import "github.com/janirefdez/ArticleRestApi/pkg/models"

var Articles = []models.Article{
    {Id: "8617bf49-39a9-4268-b113-7b6bcd189ba2", Title: "Article 1", Desc: "Article Description 1", Content: "Article Content 1"},
    {Id: "38da7ce2-02b5-471a-90b8-c299f2ef132e", Title: "Article 2", Desc: "Article Description 2", Content: "Article Content 2"},
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now our project looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;├── cmd
│   └── main.go
├── pkg
│    ├── mocks
│    │   └── article.go
│    └── models
│        └── article.go
├── go.sum
└── go.mod
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  API EndPoints
&lt;/h2&gt;

&lt;p&gt;Now we are going to start creating our API endpoints. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Get All Articles&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This will be an &lt;code&gt;HTTP GET&lt;/code&gt; request that will return all the articles.&lt;/p&gt;

&lt;p&gt;Create a new handler &lt;code&gt;pkg/handlers/GetAllArticles.go&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package handlers

import (
    "encoding/json"
    "net/http"

    "github.com/janirefdez/ArticleRestApi/pkg/mocks"
)

func GetAllArticles(w http.ResponseWriter, r *http.Request) {
    w.Header().Add("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(mocks.Articles)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The call to &lt;code&gt;json.NewEncoder(w).Encode(mocks.Articles)&lt;/code&gt; does the job of encoding our articles array into a JSON string and then writing as part of our response.&lt;/p&gt;

&lt;p&gt;In function &lt;code&gt;handleRequests()&lt;/code&gt; from &lt;code&gt;cmd/main.go&lt;/code&gt; include the new endpoint.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func handleRequests() {
    // create a new instance of a mux router
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/", homePage)
    myRouter.HandleFunc("/articles", handlers.GetAllArticles).Methods(http.MethodGet)
    log.Fatal(http.ListenAndServe(":8080", myRouter))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we now run &lt;code&gt;main.go&lt;/code&gt; we can do the request to get all the articles.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go run cmd/main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;*Note: It will return the articles defined in &lt;code&gt;pkg/mocks/article.go&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw0sgbvf3des1yjr8eb43.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw0sgbvf3des1yjr8eb43.png" alt="GetArticles Paw" width="800" height="544"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Get Article By Id&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This will be an &lt;code&gt;HTTP GET&lt;/code&gt; request that will return one article.&lt;/p&gt;

&lt;p&gt;Create a new handler &lt;code&gt;pkg/handlers/GetArticle.go&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package handlers

import (
    "encoding/json"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/janirefdez/ArticleRestApi/pkg/mocks"
)

func GetArticle(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]

    for _, article := range mocks.Articles {
        if article.Id == id {
            w.Header().Add("Content-Type", "application/json")
            w.WriteHeader(http.StatusOK)
            json.NewEncoder(w).Encode(article)
            break
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And in function &lt;code&gt;handleRequests()&lt;/code&gt; from &lt;code&gt;cmd/main.go&lt;/code&gt; include the new endpoint.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func handleRequests() {
    // create a new instance of a mux router
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/", homePage)
    myRouter.HandleFunc("/articles", handlers.GetAllArticles).Methods(http.MethodGet)
    myRouter.HandleFunc("/articles/{id}", handlers.GetArticle).Methods(http.MethodGet)
    log.Fatal(http.ListenAndServe(":8080", myRouter))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we now run &lt;code&gt;main.go&lt;/code&gt; we can do the request to get an specific article by id.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go run cmd/main.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8vs8v5x08yzg693p28ca.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8vs8v5x08yzg693p28ca.png" alt="GetArticle Paw" width="800" height="304"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Create new Article&lt;/strong&gt;&lt;br&gt;
This will be an &lt;code&gt;HTTP POST&lt;/code&gt; request that will add a new article.&lt;/p&gt;

&lt;p&gt;Create a new handler &lt;code&gt;pkg/handlers/AddArticle.go&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package handlers

import (
    "encoding/json"
    "io/ioutil"
    "log"
    "net/http"

    "github.com/janirefdez/ArticleRestApi/pkg/mocks"
    "github.com/janirefdez/ArticleRestApi/pkg/models"

    "github.com/google/uuid"
)

func AddArticle(w http.ResponseWriter, r *http.Request) {
    // Read to request body
    defer r.Body.Close()
    body, err := ioutil.ReadAll(r.Body)

    if err != nil {
        log.Fatalln(err)
    }
    var article models.Article
    json.Unmarshal(body, &amp;amp;article)

    article.Id = (uuid.New()).String()
    mocks.Articles = append(mocks.Articles, article)

    w.Header().Add("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode("Created")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this function we are reading the information of the article the client has sent. And we are generating a random uuid to that article. &lt;/p&gt;

&lt;p&gt;If everything goes well, we send response HTTP 201. &lt;/p&gt;

&lt;p&gt;*Note: 201 -&amp;gt; created success status response code indicates that the request has succeeded and has led to the creation of a resource.&lt;/p&gt;

&lt;p&gt;And in function &lt;code&gt;handleRequests()&lt;/code&gt; from &lt;code&gt;cmd/main.go&lt;/code&gt; include the new endpoint.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func handleRequests() {
    // create a new instance of a mux router
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/", homePage)
    myRouter.HandleFunc("/articles", handlers.GetAllArticles).Methods(http.MethodGet)
    myRouter.HandleFunc("/articles/{id}", handlers.GetArticle).Methods(http.MethodGet)
    myRouter.HandleFunc("/articles", handlers.AddArticle).Methods(http.MethodPost)
    log.Fatal(http.ListenAndServe(":8080", myRouter))
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we now run &lt;code&gt;main.go&lt;/code&gt; we can do the request to add a new article.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxgwtmul4ogzjguvq5nwq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxgwtmul4ogzjguvq5nwq.png" alt="Add Article Paw" width="800" height="186"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you then do the request to get all articles, the new article you have added should be there. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Update Article by id&lt;/strong&gt;&lt;br&gt;
This will be an &lt;code&gt;HTTP PUT&lt;/code&gt; request that will update an article.&lt;/p&gt;

&lt;p&gt;Create a new handler &lt;code&gt;pkg/handlers/UpdateArticle.go&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package handlers

import (
    "encoding/json"
    "io/ioutil"
    "log"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/janirefdez/ArticleRestApi/pkg/mocks"
    "github.com/janirefdez/ArticleRestApi/pkg/models"
)

func UpdateArticle(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]

    // Read request body
    defer r.Body.Close()
    body, err := ioutil.ReadAll(r.Body)

    if err != nil {
        log.Fatalln(err)
    }

    var updatedArticle models.Article
    json.Unmarshal(body, &amp;amp;updatedArticle)

    for index, article := range mocks.Articles {
        if article.Id == id {
            article.Title = updatedArticle.Title
            article.Desc = updatedArticle.Desc
            article.Content = updatedArticle.Content

            mocks.Articles[index] = article

            w.Header().Add("Content-Type", "application/json")
            w.WriteHeader(http.StatusOK)
            json.NewEncoder(w).Encode("Updated")
            break
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And in function &lt;code&gt;handleRequests()&lt;/code&gt; from &lt;code&gt;cmd/main.go&lt;/code&gt; include the new endpoint.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func handleRequests() {
    // create a new instance of a mux router
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/", homePage)
    myRouter.HandleFunc("/articles", handlers.GetAllArticles).Methods(http.MethodGet)
    myRouter.HandleFunc("/articles/{id}", handlers.GetArticle).Methods(http.MethodGet)
    myRouter.HandleFunc("/articles", handlers.AddArticle).Methods(http.MethodPost)
    myRouter.HandleFunc("/articles/{id}", handlers.UpdateArticle).Methods(http.MethodPut)
    log.Fatal(http.ListenAndServe(":8080", myRouter))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we now run &lt;code&gt;main.go&lt;/code&gt; we can do the request to update an article.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvjj4sol4c1p9z7fjfe8v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvjj4sol4c1p9z7fjfe8v.png" alt="Update Article Paw" width="800" height="166"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you then do the request to get all articles, the article should be updated.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Delete Article by id&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This will be an &lt;code&gt;HTTP DELETE&lt;/code&gt; request that will delete an article.&lt;/p&gt;

&lt;p&gt;Create a new handler &lt;code&gt;pkg/handlers/DeleteArticle.go&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package handlers

import (
    "encoding/json"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/janirefdez/ArticleRestApi/pkg/mocks"
)

func DeleteArticle(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]

    for index, article := range mocks.Articles {
        if article.Id == id {
            mocks.Articles = append(mocks.Articles[:index], mocks.Articles[index+1:]...)

            w.Header().Add("Content-Type", "application/json")
            w.WriteHeader(http.StatusOK)
            json.NewEncoder(w).Encode("Deleted")
            break
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And in function &lt;code&gt;handleRequests()&lt;/code&gt; from &lt;code&gt;cmd/main.go&lt;/code&gt; include the new endpoint.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func handleRequests() {
    // create a new instance of a mux router
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/", homePage)
    myRouter.HandleFunc("/articles", handlers.GetAllArticles).Methods(http.MethodGet)
    myRouter.HandleFunc("/articles/{id}", handlers.GetArticle).Methods(http.MethodGet)
    myRouter.HandleFunc("/articles", handlers.AddArticle).Methods(http.MethodPost)
    myRouter.HandleFunc("/articles/{id}", handlers.UpdateArticle).Methods(http.MethodPut)
    myRouter.HandleFunc("/articles/{id}", handlers.DeleteArticle).Methods(http.MethodDelete)
    log.Fatal(http.ListenAndServe(":8080", myRouter))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we now run &lt;code&gt;main.go&lt;/code&gt; we can do the request to delete an article.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwfz3xwga78kp97jusmef.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwfz3xwga78kp97jusmef.png" alt="DeleteArticle Paw" width="800" height="224"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you then do the request to get all articles, the article you deleted shouldn't appear.&lt;/p&gt;

&lt;p&gt;Now our project looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;├── cmd
│   └── main.go
├── pkg
│    ├── handlers
│    │   ├── AddArticle.go
│    │   ├── DeleteArticle.go
│    │   ├── GetAllArticles.go
│    │   ├── GetArticle.go
│    │   └── UpdateArticle.go
│    ├── mocks
│    │   └── article.go
│    └── models
│        └── article.go
├── go.sum
└── go.mod
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Improvements
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Include error response when something goes wrong.&lt;/li&gt;
&lt;li&gt;Include error response when an article is not found.&lt;/li&gt;
&lt;li&gt;&lt;a href="https://dev.to/janirefdez/connect-rest-api-to-database-with-go-d8m"&gt;Connect the API to a real database&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;...&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But this is a simple example to learn how to create a REST API. Hope you enjoyed!!&lt;/p&gt;

&lt;p&gt;If you want to check the whole project here you have the link: &lt;a href="https://github.com/janirefdez/ArticleRestApi" rel="noopener noreferrer"&gt;ArticleRestApi&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;In the next example we will &lt;a href="https://dev.to/janirefdez/connect-rest-api-to-database-with-go-d8m"&gt;connect this API to PostgreSQL database&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Don't forget to like and share! Thank you! :)&lt;/p&gt;

</description>
      <category>go</category>
      <category>rest</category>
      <category>api</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Shimmer Effect on Android</title>
      <dc:creator>Janire Fernandez</dc:creator>
      <pubDate>Wed, 10 Aug 2022 15:06:00 +0000</pubDate>
      <link>https://dev.to/janirefdez/shimmer-effect-on-android-57ke</link>
      <guid>https://dev.to/janirefdez/shimmer-effect-on-android-57ke</guid>
      <description>&lt;h2&gt;
  
  
  What is a Shimmer Effect?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F549b151ppif3zee6xywz.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F549b151ppif3zee6xywz.gif" alt="Shimmer Effect Demo"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Its an effect to show a loading status. Instead of using a progress, Shimmer effect creates a better design for ux. It mimics the page’s layout by showing its elements in a shape similar to the actual content as it is loading and becoming available (i.e. when network latency allows).&lt;/p&gt;

&lt;h2&gt;
  
  
  How to implement this on Android?
&lt;/h2&gt;

&lt;p&gt;There is is an Android library, Shimmer, that provides an easy way to add a shimmer effect to any view in your Android app. &lt;/p&gt;

&lt;p&gt;So lets start!&lt;/p&gt;

&lt;p&gt;First include the library dependency:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

dependencies {
    // Shimmer
    implementation 'com.facebook.shimmer:shimmer:0.5.0'
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now create a layout &lt;code&gt;list_placeholder_layout.xml&lt;/code&gt; that will act as a placeholder while content is loading. &lt;/p&gt;

&lt;p&gt;In my example I have an imageView to display the image of the animal and two textViews for the name and the type. So the layout is something like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?xml version="1.0" encoding="utf-8"?&amp;gt;
&amp;lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginStart="10dp"&amp;gt;

    &amp;lt;androidx.cardview.widget.CardView
        android:id="@+id/animal_image"
        android:layout_width="120dp"
        android:layout_height="150dp"
        android:backgroundTint="@color/gray"
        app:cardCornerRadius="20dp"
        app:cardElevation="4dp"
        app:cardUseCompatPadding="true"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" /&amp;gt;

    &amp;lt;androidx.cardview.widget.CardView
        android:id="@+id/animal_name"
        android:layout_width="120dp"
        android:layout_height="30dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="30dp"
        android:backgroundTint="@color/gray"
        app:cardCornerRadius="10dp"
        app:cardElevation="4dp"
        app:cardUseCompatPadding="true"
        app:layout_constraintStart_toEndOf="@id/animal_image"
        app:layout_constraintTop_toTopOf="parent" /&amp;gt;

    &amp;lt;androidx.cardview.widget.CardView
        android:id="@+id/animal_type"
        android:layout_width="120dp"
        android:layout_height="30dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="20dp"
        android:backgroundTint="@color/gray"
        app:cardCornerRadius="10dp"
        app:cardElevation="4dp"
        app:cardUseCompatPadding="true"
        app:layout_constraintStart_toEndOf="@id/animal_image"
        app:layout_constraintTop_toBottomOf="@id/animal_name" /&amp;gt;

&amp;lt;/androidx.constraintlayout.widget.ConstraintLayout&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Once the layout is created we need to include it in the main layout &lt;code&gt;activity_main&lt;/code&gt;, where the recyclerView is situated. &lt;/p&gt;

&lt;p&gt;To do that, we include &lt;code&gt;&amp;lt;com.facebook.shimmer.ShimmerFrameLayout&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&amp;lt;?xml version="1.0" encoding="utf-8"?&amp;gt;
&amp;lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.main.MainActivity"&amp;gt;

    &amp;lt;com.facebook.shimmer.ShimmerFrameLayout
        android:id="@+id/shimmer_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:duration="800"&amp;gt;

        &amp;lt;!-- Adding 8 rows of placeholders --&amp;gt;
        &amp;lt;LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"&amp;gt;

            &amp;lt;include layout="@layout/list_placeholder_layout" /&amp;gt;
            &amp;lt;include layout="@layout/list_placeholder_layout" /&amp;gt;
            &amp;lt;include layout="@layout/list_placeholder_layout" /&amp;gt;
            &amp;lt;include layout="@layout/list_placeholder_layout" /&amp;gt;
            &amp;lt;include layout="@layout/list_placeholder_layout" /&amp;gt;
            &amp;lt;include layout="@layout/list_placeholder_layout" /&amp;gt;
            &amp;lt;include layout="@layout/list_placeholder_layout" /&amp;gt;
            &amp;lt;include layout="@layout/list_placeholder_layout" /&amp;gt;
        &amp;lt;/LinearLayout&amp;gt;

    &amp;lt;/com.facebook.shimmer.ShimmerFrameLayout&amp;gt;

    &amp;lt;androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginStart="5dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent" /&amp;gt;

&amp;lt;/androidx.constraintlayout.widget.ConstraintLayout&amp;gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the next step, we just need to tell Shimmer when to start and stop the animation. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We should start the Shimmer when we fetch the list of items.
&lt;code&gt;binding.shimmerView.startShimmer()&lt;/code&gt; &lt;/li&gt;
&lt;li&gt;We should stop the Shimmer when we get the list of items. 
&lt;code&gt;binding.shimmerView.stopShimmer()&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Also, we should hide the visibility of the Shimmer Frame Layout, when we have the list of items. &lt;br&gt;
&lt;code&gt;binding.shimmerView.isVisible = false&lt;/code&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    private val viewModel: MainViewModel by viewModels()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        //Start Shimmer
        binding.shimmerView.startShimmer()

        viewModel.getAnimals(10)
        viewModel.animalList.observe(this) {
            initRecyclerView(it)
        }
    }

    private fun initRecyclerView(animalList: List&amp;lt;Animal&amp;gt;) {

        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        val adapter = AnimalAdapter(animalList)
        binding.recyclerView.adapter = adapter
        //Stop Shimmer
        binding.shimmerView.stopShimmer()
        //Hide Shimmer view
        binding.shimmerView.isVisible = false
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And that's all!! &lt;/p&gt;

&lt;p&gt;If you want to check the whole project here you have the link: &lt;a href="https://github.com/janirefdez/ShimmerEffectAndroid" rel="noopener noreferrer"&gt;ShimmerEffectAndroid&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Don't forget to like and share! Thank you! :) &lt;/p&gt;

&lt;p&gt;Useful links: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://facebook.github.io/shimmer-android/" rel="noopener noreferrer"&gt;https://facebook.github.io/shimmer-android/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>shimmer</category>
      <category>android</category>
      <category>kotlin</category>
      <category>github</category>
    </item>
  </channel>
</rss>
