Go Microservice Part III - Model
By ski11up.com
In the previous blog post, Go MVC Part II - Application Configuration we have imported Viper
and wrote project configuration.
Let’s start with Model
first and then we will move upwards and write Service
, Controller
, and then App
code and finally the main
function which will start the contact web application.
Model or Domain
Model
contains domain objects as well as the information retrieval mechanical from the database. Let’s assume our database is nothing but a go
struct
for the simplicity of the application.
Below is the Contact struct
code.
1
2
3
4
5
6
7
package domain
type Contact struct { (1)
Id int64 `json:"id"` (2)
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
}
1 | defining a struct which will hold contact details |
2 | we want to return the response in JSON format and it has to be some logical name |
We need to write a code that will access the Contract struct
and returns it to the Service
Layer.
Below is the code for accessing the DB
and retrieved information based on the user request.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package domain
import (
"errors" (6)
"fmt"
)
var contacts = map[int64]*Contact{
1: {Id: 1, FirstName: "Jagdeep", LastName: "Jain"}, (1)
}
func GetContact(id int64) (*Contact, error) { (2)
contact := contacts[id] (3)
if contact != nil {
return contact, nil (4)
}
return nil, errors.New( (5)
fmt.Sprintf("User with id %v not found in our database...", id))
}
1 | initializing the Contact struct which is a map having key as integer and the value will be a pointer to the Contact struct |
2 | defining the function which will take the input id and returns a pointer to the Contact struct and in case of failure return error |
3 | retrieving the value based on index location or key |
4 | if contact is not null that mean we got the contact, return the contact and error as nil |
5 | got an error, format the message by embedding the id not found |
6 | import will be automatically added, this comes with standard go package |
Next
Go to Go MVC Part IV - Service to get started with the Contact Service
code.