golang :Beego 自建控制器

由於研究k8s相關的開源產品,有時候難免會爲了看個原理究竟 ,去看源碼,偶爾有時間就開始學習golang相關的知識
本篇將使用Beego 框架 ,自建一個控制器
testController.go

package controllers

import (
	"fmt"

	"github.com/astaxie/beego"
)

// TestController  is a test control
type TestController struct {
	beego.Controller
}

// User is  info of  user
type User struct {
	Username string
	Password string
}

// Get is a function  to test
func (c *TestController) Get() {

	c.Ctx.WriteString(`<html><form action="http://127.0.0.1:8080/testcontrol" method="post">
	<p>username: <input type="text" name="Username"></p>
	<p>password: <input type="text" name="Password"></p>
	<input type="submit" value="提交">
  </form></html>`)
}

// Put is a function  to test
func (c *TestController) Put() {
	c.Ctx.WriteString("hello put")
}

// Post is a function  to test
func (c *TestController) Post() {
	u := User{}
	if err := c.ParseForm(&u); err != nil {
		fmt.Println("error")
	}
	c.Ctx.WriteString("username:" + u.Username)
	c.Ctx.WriteString("password:" + u.Password)
}

這段代碼 創建了一個TestController 的控制器,實現了 Get Put Post 方法
其中 Get方法 創建了一個表單 ,Post 方法 使用ParseForm 方法解析了結構體數據
route.go

package routers

import (
	"WEB/controllers"

	"github.com/astaxie/beego"
)

func init() {
	beego.Router("/", &controllers.MainController{})
	beego.Router("/testcontrol", &controllers.TestController{}, "get:Get")
	beego.Router("/testcontrol", &controllers.TestController{}, "post:Post")
}

這段代碼初始化了網頁的訪問路由 ,Get ,Post 分別使用testcontrol 訪問
一個小細節
routes包前面的下劃線 表示只加載 該包的init方法
也就是main方法一進來就會去初始化路由
在這裏插入圖片描述
運行效果:
bee run 啓動項目
瀏覽器訪問 日誌輸出地址:
在這裏插入圖片描述
端口可以在 此處進行配置
在這裏插入圖片描述
在這裏插入圖片描述
輸入 賬戶 admin/admin
瀏覽器中打印出 對應的參數值
在這裏插入圖片描述
後臺日誌
在這裏插入圖片描述
注意:
之前一直輸出的是空 ,獲取不到對應的參數值,檢查之後發現是定義結構體的時候 屬性用的小寫,一定要使用大寫,才能被外部訪問到
原來
在這裏插入圖片描述
修改後
在這裏插入圖片描述
參考
https://www.imooc.com/article/261217?block_id=tuijian_wz

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章