beego项目简单案例

先创建一个beego项目
项目结构
beego项目简单案例_第1张图片
1.conf
这个目录做一些配置,项目名称、不同运行环境端口、数据库用户名、密码、端口,开启调试等

appname = myapp1
runmode = dev
[dev]
httpport=8080
[prod]
httpport=8081
[test]
httpport = 8082
mysqladdr="127.0.0.1
mysqlport=9090
mysqluser=root
mysqlpassword=123456
copyrequestbody=true

2.路由配置
controller的名称、方式为get还是post
router.go

package routers

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


func init() {

    beego.Router("/index", &controllers.MainController{},"post:Post")
    beego.Router("/",&controllers.MainController{},"get:Get;post:Post")
	beego.Router("/index1",&controllers.MainController{},"get:Get")
	beego.Router("/index2",&controllers.MainController{},"*:Get")
    beego.Router("/test",&controllers.TestControler{},"get:Get;post:Post")
    beego.Router("/test_input",&controllers.Test_InputController{},"get:Get;post:Post")
    beego.Router("/test_login",&controllers.Test_loginController{},"get:Login;post:Post")
    beego.Router("/testModel",&controllers.Test_ModelController{},"get:Get;post:Post")
	beego.Router("/testModel2",&controllers.TestModel2Controller{},"get:Get;post:Post")
    beego.Router("/login",&controllers.LoginController{},"get:Get;post:Post")
}

3.models层:数据处理
最常用的是操作数据库
user.go

package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

type Users struct{
	Id int
	Username string
	Password string
}
var db orm.Ormer
func init(){
	//开启调试模式
	orm.Debug=true
	//获取数据库
	orm.RegisterDataBase("default","mysql","root:123456@tcp(127.0.0.1:3306)/testgo?charset=utf8",30)
	orm.RegisterModel(new(Users))
	db=orm.NewOrm()
	fmt.Println("init success")
}
func AddUsers(users *Users) (int64,error){

	fmt.Println(users.Username,users.Password)


	//id,err:=db.InsertOrUpdate(users)
	id,err:=db.Insert(users)
	fmt.Println(id,err)
	if err!=nil{
		db.Rollback()
	}
	return id,err
}
func ReadAllUser() []Users{
	var users []Users
	qb,_:=orm.NewQueryBuilder("mysql")
	qb.Select("*").From("users")
	sql:=qb.String()
	db.Raw(sql).QueryRows(&users)
	return users
}

4.controller层
这里调用models层方法返回数据,在通过数据方式传递给view层,并指明tpl模板,是view层和models层的桥梁
login.tpl

package controllers

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

type LoginController struct {
	beego.Controller
}
func (c *LoginController) Get(){
	c.Data["website"]="https://www.baidu.com"
	c.Data["isDisplay"]=false
	c.Data["content1"]="content1"
	c.Data["content2"]="content2"
	users:=models.ReadAllUser()

	c.Data["users"]=users
	c.Data["len"]= len(users)
	c.TplName="login.tpl"
}

5.view层,接受controller传递的数据,显示到网页
login.tpl




    
    Title
    


    
用户名:
密码:

{{if .isDisplay}} {{.content1}} {{else}} {{.content2}} {{end}}

Users表

{{range .users}} {{end}}
IdusernamePassword
{{.Id}}{{.Username}}{{.Password}}

运行结果如下
beego项目简单案例_第2张图片

你可能感兴趣的:(Go)