Establish a database connection in GoLang
Hello, as I continue my GoLang series without slowing down, in the next stage, I would like to explain how GoLang works with a database. Preface: For this article, my database preference will be MySQL.
In this article, I assume that you have already set up your GOPATH and installed Go. For those who haven’t done these steps, I recommend reading my previous articles. As an example, I will present fetching data from a sample user table. First, let’s dive into the concept of models.
Anyone who has done object-oriented programming has seen that real-world objects can be represented by virtual objects in software. In GoLang, this situation is a little different. We can define any entity with real-world properties using structs in GoLang. Below, I will demonstrate the definition of a user in GoLang using a struct.
type User struct {
Id int `json:"id"`
Name string `json:"name"`
Surname string `json:"name"`
}
In the above block, we defined a user entity with properties such as Id, Name, and Surname. From now on, to create a new user entity named ‘u’, the following code block will be sufficient:
var u User
Now let’s see how we can create a user with default values when creating a new user:
var u = User{"1", "Onur", "Göker"}
Now our user ‘u’ has a default ID, Name, and Surname. Alternatively, we can directly create a user entity and assign values as follows:
var u = User{Id: "1", Name: "Onur", Surname: "Göker"}
By using the code block below, we can create a complete model for our user entity.
package models // specifying the package it belongs to
type User struct {
Id int `json:"id"`
Name string `json:"name"`
Surname string `json:"name"`
}
Now create a folder named ‘models’ in your project directory and paste the above code block into a file named ‘models.go’ inside this folder. Now we have a model ready for our project!