Adding a Backend Module
The internal/app folder
Backend modules are located in the /internal/app
folder.
root
|--internal
| |--app
| |--[module 1]
| |--[module 2]
| |--[...]
Each backend module should have its own folder which should contain the exposed API and all the code for the module's internal workings.
Example
Lets create a simple todo list app called mytodo. Start by initializing a new project.
gofs init github.com/myorg/mytodo mytodo
Now lets create a backend module called list
that will contain all the business logic and database logic for the todo list. Lets also say todo lists may not contain more than 20 items because that's just too much to do.
Create the list module folder
Create a folder for the list module.
mytodo
|--internal
| |--app
| |--list
Create the list api
Create a new file /internal/app/list/list.go
with the List
struct and functions for creating a new todo list and adding items to the list. NB: This code is incomplete, you need to add the database code from Persisting data before it will compile.
mytodo
|--internal
| |--app
| |--list
| |--list.go
package list
import (
"github.com/google/uuid"
)
const MaxItems = 20
type List struct {
ID string
Name string
Items []string
}
func NewList(name string) (*List, error) {
l := &List{
ID: uuid.NewString(),
Name: name,
}
// Save list to database
if err != nil {
return nil, err
}
return l, nil
}
func AddItem(listID string, item string) error {
l, err := // Retrieve list from the database
if err != nil {
return err
}
// Check if the list is full
if len(l.Items) >= MaxItems {
return fmt.Errorf("Todo list is full")
}
l.Items = append(l.Items, item)
// save to the database
if err != nil {
return err
}
return nil
}