Light Blog Development--the third lecture on Project Integration (iii)

Source: Internet
Author: User

"Chick Software" using frame: Beego + Grom +xianyan

Objective of this chapter: to add page routing, to access the Light blog page normally
GitHub Address: When open, click the Star button in the upper right corner

Beego adding routing Capabilities

Beego add a route by modifying the routers--> Router.go file to implement, Beego implementation of the route there are a variety of points I look at the Beego routing document, we use annotated routing

//注解路由 // path路由路径,method路由方法:get、put、post...// @router path [method]func (this *Controller) Doit() {  ...}
//在 router.go 中通过如下方式注册路由:beego.Include(&CMSController{})

Beego controller controllers have a number of methods, including Init, Prepare, and so on. Where the Prepare method is a method that is called every time a request is made, we need to create a "base class" to override the prepare method of the struct.
The relationship between the controller and the route is like: the user to the bank, the route tells which window, the controller is how to provide specific services to the user.
The inheritance of Golang is simulated by the combination, and the Golang polymorphism is implemented by the interface (interface).
Golang interface Implementation, there is no mandatory convention. As long as all the methods of the interface definition are implemented, the interface is implemented.

    1. Let's first create a controllers-->base.go, a new struct Basecontroller inherits Beego.controller, and a prepare () method added for Basecontroller. All child controllers that inherit the Basecontroller call the Basecontroller prepare () method every time, so let's agree that all the child controllers will inherit Basecontroller, The general logic of each request can be written in the Basecontroller prepare method.
    2. What if all the methods inside the child controller, in addition to calling the general logic of the prepare method inside the Basecontroller, have some general logic for the current child controller? Does each method of the current child controller write the same code again? There is a way, we ourselves define an interface in the Basecontroller, in the Basecontroller prepare method to determine whether the child controller implements the interface. If implemented, we call the interface method.
      Here is the code for the file Base.go
import (    "github.com/astaxie/beego"    "log")// 约定:如果子controller 存在NestPrepare()方法,就实现了该接口,type NestPreparer interface {    NestPrepare()}type BaseController struct {    beego.Controller}func (ctx *BaseController) Prepare() {    log.Println("BaseControll")    // 判断子类是否实现了NestPreparer接口,如果实现了就调用接口方法。    if app, ok := ctx.AppController.(NestPreparer); ok {        app.NestPrepare()    }}
    1. We define the base controller Basecontroller above. Here we add a controllers-->index.go file, define the Indexcontroller code as follows:
package controllerstype IndexController struct {    BaseController}//首页// @router / [get]func (c *IndexController) Get() {    c.TplName = "index.html"}//留言// @router /message [get]func (c *IndexController) GetMessage() {    c.TplName = "message.html"}//关于// @router /about [get]func (c *IndexController) GetAbout() {    c.TplName = "about.html"}
    1. We've got 3 routes already in place, but we need to adjust the routers->router.go to take effect.
import (    "github.com/jicg/liteblog/controllers"    "github.com/astaxie/beego")func init() {   //注解路由 需要调用Include。    beego.Include(&controllers.IndexController{})}

We have defined the Golang part of the code (back-end code), but also need to slightly adjust the next front-end code, the normal all pages.

Beego template rendering can be customized (further encapsulation of the Html/template package for Golang)

Template customization method, defined in the following way:

 beego.AddFuncMap("模版中调用的方法名", 具体函数)
    1. We have header.html out of the ground. The route has already been defined, so let's adjust the views->comm->header.html.
      Modify header.html To change the routing path to what we define now.
<div class= "header" > <div class= "header-wrap" > 

    1. After adjusting we found that "layui-this" This CSS style we currently write dead tune, should be based on the current page, select the corresponding Li, which need to get the current page path, but also to have the method to determine whether the path is the same
      2.1 Gets the path of the current page, which belongs to the general function, the prepare method in Basecontrollers, adds the output of the variable
func (ctx *BaseController) Prepare() {    // 将页面路径 保存到 Path变量里面    ctx.Data["Path"] = ctx.Ctx.Request.RequestURI    if app, ok := ctx.AppController.(NestPreparer); ok {        app.NestPrepare()    }}

2.2 Let's define the Equrl template method to see if the path is the same. Let's write it in the Main.go file.

package mainimport (    _ "github.com/jicg/liteblog/routers"    "github.com/astaxie/beego"    "strings")func main() {    initTemplate()    beego.Run()}func initTemplate() {    beego.AddFuncMap("equrl", func(x, y string) bool {        s1 := strings.Trim(x, "/")        s2 := strings.Trim(y, "/")        return strings.Compare(s1, s2) == 0    })}

2.3 Then modify the code inside the views->comm->header.html, plus the logic of the path comparison:

......<div class="blog-nav pull-right">            <ul class="layui-nav pull-left">                <li class="layui-nav-item {{if equrl "/" .Path }}layui-this{{end}}"><a href="/" >首页</a></li>                <li class="layui-nav-item {{if equrl "/message" .Path }}layui-this{{end}}"><a href="/message">留言</a></li>                <li class="layui-nav-item {{if equrl "/about" .Path }}layui-this{{end}} "><a href="/about">关于</a></li>            </ul>            <a href="#" class="personal pull-left">                <i class="layui-icon layui-icon-username"></i>            </a>        </div>.......

Here, the page can be viewed normally.

Have we ever thought that if we could ask the address, the page would be like this? The answer is that Beego will provide a default error for the page to return. Therefore, the default error interface for Beego needs to be modified.

Beego provides the file description address of the page fault

    1. Add a Controllers->error.go file, define the Errorcontroller controller, which defines the Error404, Error501 method. The code is as follows
package controllerstype ErrorController struct {    BaseController}func (c *ErrorController) Error404() {    c.Data["content"] = "page not found"    c.TplName = "error/404.html"}
    1. The Errorcontroller is then injected into the Beego, modifying the default error handling page and modifying the method to Beego. Errorcontroller (the wrong controller), let's modify the Router.go file, and then the INIT function to start adding the code to modify, the code is as follows:
func init() {    beego.ErrorController(&controllers.ErrorController{})    beego.Include(&controllers.IndexController{})}

Golang syntax: This _ "xxx" appears where Golang introduced the package, which means that the Init method under the XXX package is called.
Mian.go is an ingress function, there is no arbitrary method of calling Router.go, but note that there is "github.com/jicg/liteblog/routers" in the place where the package is introduced, and the Init method under the routers package is called by default.
Finally, the project has been integrated, but the data is static, and the journey to our light blog begins. We'll see you next time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.