一、动态路由

api.go:

package controllers

import (
    "github.com/astaxie/beego"
)

type ApiController struct {
    beego.Controller
}

// http://localhost:8080/api/1
func (c *ApiController) Get() {=(res) [val*2**inx for inx, val in zip(range(len(t)), t)]
            res = res + sum(item)
        return in
    // 获取动态路由的值
    id := c.Ctx.Input.Param(":id")
    c.Ctx.WriteString("api接口--" + id)
}

router.go:

package routers

import (
    "beegodemo02/controllers"
    "github.com/astaxie/beego"
)

func init() {
    beego.Router("/", &controllers.MainController{})

    // http://localhost:8080/api/1
    beego.Router("/api/:id", &controllers.ApiController{})
}

显示:

二、路由伪静态

cms.go:

package controllers

import (
    "github.com/astaxie/beego"
)

type CmsController struct {
    beego.Controller
}

// 路由伪静态
// http://localhost:8080/cms_1.html
func (c *CmsController) Get() {
    cmsId := c.Ctx.Input.Param(":id")
    c.Ctx.WriteString("CMS详情--" + cmsId)
}

router.go:

package routers

import (
    "beegodemo02/controllers"
    "github.com/astaxie/beego"
)

func init() {
    beego.Router("/", &controllers.MainController{})

    // http://localhost:8080/api/1
    beego.Router("/api/:id", &controllers.ApiController{})

    // http://localhost:8080/cms_1.html
    beego.Router("/cms_:id([0-9]+).html", &controllers.CmsController{})
}

显示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6m1nUYdO-1608128103434)(https://cdn.jsdelivr.net/gh/Wonz5130/My-Private-ImgHost/img/Snipaste_2020-11-18_17-22-12.png)]

三、路由跳转

login.go:

package controllers

import (
    "fmt"
    "github.com/astaxie/beego"
)

type LoginController struct {
    beego.Controller
}

// 路由伪静态
// http://localhost:8080/cms_1.html
func (c *LoginController) Get() {
    c.TplName = "login.html"
}

func (c *LoginController) DoLogin() {
    username := c.GetString("username")
    password := c.GetString("password")
    fmt.Println(username, password)

    // 执行跳转

    c.Redirect("/", 302)  // 302 表示重定向
    // c.Redirect("/cms_1.html", 302)  // 302 表示重定向
}

router.go:

package routers

import (
    "beegodemo02/controllers"
    "github.com/astaxie/beego"
)

func init() {
    beego.Router("/", &controllers.MainController{})

    // http://localhost:8080/api/1
    beego.Router("/api/:id", &controllers.ApiController{})

    // http://localhost:8080/cms_1.html
    beego.Router("/cms_:id([0-9]+).html", &controllers.CmsController{})

    beego.Router("/login", &controllers.LoginController{})
    beego.Router("/doLogin", &controllers.LoginController{}, "post:DoLogin")
}

login.html:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
    <form action="/doLogin" method="post">
      用户名: <input type="text" name="username"> <br><br>
      密 码: <input type="text" name="password"> <br><br>

      <input type="submit" value="登录">
    </form>
</body>
</html>

显示:

输完用户名和密码点击登录之后,会跳转到 localhost:8080

控制台有输出:

四、参考教程

Golang 教程 P55