Notes Display
Learn to create an API to read and render a note from the database.
We'll cover the following...
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 routersimport ("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 controllersimport ("beego_notes/models""fmt""net/http""strconv"beego "github.com/beego/beego/v2/server/web")// NotesController operations for Notestype NotesController struct {beego.Controller}func (c *NotesController) NotesIndex() {// Get all notesnotes := models.NotesGetAll()c.Data["notes"] = notesc.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"] = notec.TplName = "notes/show.tpl"}
The NotesShow()
function is responsible for showing a note. Details of the function are as follows: ...