Search⌘ K
AI Features

Notes Display

Explore how to implement a notes display feature in a Golang and Beego web application. Learn to create routes with URL parameters, develop controller functions to retrieve notes by ID, interact with the database using ORM, and render the results with templates. This lesson equips you with practical skills to build dynamic data-driven pages in your Beego app.

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.

Go (1.18.2)
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

Go (1.18.2)
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: ...