Notes Display

Learn to create an API to read and render a note from the database.

Reading a note

In this lesson, we are going to implement a route/API that shows the details of a note.

Let’s start by defining a new route in the routers/route.go file.

Press + to interact
package routers
import (
"beego_notes/controllers"
beego "github.com/beego/beego/v2/server/web"
)
func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/notes", &controllers.NotesController{}, "get:NotesIndex")
beego.Router("/notes/new", &controllers.NotesController{}, "get:NotesNewForm")
beego.Router("/notes", &controllers.NotesController{}, "post:NotesCreate")
beego.Router("/notes/:id([0-9]+)", &controllers.NotesController{}, "get:NotesShow")
}

Line 14: The route with the pattern /notes/:id([0-9]+) uses the GET method to trigger the NotesShow() action, where :id is a placeholder for the note’s numerical Id. Therefore, requesting /notes/1 would fetch and render the note with Id 1 from the database.

Handler function

Press + to interact
package controllers
import (
"beego_notes/models"
"fmt"
"net/http"
"strconv"
beego "github.com/beego/beego/v2/server/web"
)
// NotesController operations for Notes
type NotesController struct {
beego.Controller
}
func (c *NotesController) NotesIndex() {
// Get all notes
notes := models.NotesGetAll()
c.Data["notes"] = notes
c.TplName = "notes/index.tpl"
}
func (c *NotesController) NotesNewForm() {
c.TplName = "notes/new.tpl"
}
func (c *NotesController) NotesCreate() {
name := c.GetString("name")
content := c.GetString("content")
models.NotesCreate(name, content)
c.Redirect("/notes", http.StatusFound)
}
func (c *NotesController) NotesShow() {
idStr := c.Ctx.Input.Param(":id")
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
fmt.Printf("Error: %v", err)
}
note := models.NotesFind(id)
c.Data["note"] = note
c.TplName = "notes/show.tpl"
}

The NotesShow() function is responsible for showing a note. Details of the function are as follows: ...