beego基础使用

路由注册

beego.Get("/",func(ctx *context.Context){
     ctx.Output.Body([]byte("hello world"))
})

beego.Router("/admin", &admin.UserController{})
beego.Router("/api/create", &RestController{}, "post:CreateFood")

namespace

ns :=
beego.NewNamespace("/v1",
    beego.NSCond(func(ctx *context.Context) bool {
        if ctx.Input.Domain() == "api.beego.me" {
            return true
        }
        return false
    }),
    beego.NSBefore(auth),
    beego.NSGet("/notallowed", func(ctx *context.Context) {
        ctx.Output.Body([]byte("notAllowed"))
    }),
    beego.NSNamespace("/shop",
        beego.NSBefore(sentry),
        beego.NSGet("/:id", func(ctx *context.Context) {
            ctx.Output.Body([]byte("notAllowed"))
        }),
    ),
    beego.NSNamespace("/cms",
        beego.NSInclude(
            &controllers.MainController{},
            &controllers.CMSController{},
            &controllers.BlockController{},
        ),
    ),
)
//注册 namespace
beego.AddNamespace(ns)

获取请求数据

this.Ctx.Request // Go原生的Request
this.Ctx.Input.Param(":id") // /user/:id

this.GetString("key") // 获取GET或POST Form数据, 不能获取JSON

// 使用struct获取form表单
type user struct {
    Id    int         `form:"-"`
    Name  interface{} `form:"username"`
    Age   int         `form:"age"`
    Email string
}
func (this *MainController) Post() {
    u := user{}
    if err := this.ParseForm(&u); err != nil {
        //handle error
    }
}

// 获取JSON
// 首先在配置文件里设置 copyrequestbody = true
func (this *ObjectController) Post() {
    var ob models.Object
    var err error
    if err = json.Unmarshal(this.Ctx.Input.RequestBody, &ob); err == nil {
        objectid := models.AddOne(ob)
        this.Data["json"] = "{"ObjectId":"" + objectid + ""}"
    } else {
        this.Data["json"] = err.Error()
    }
    this.ServeJSON()
}

响应

// html
this.Data["Website"] = "beego.me"
this.Data["Email"] = "astaxie@gmail.com"
this.TplName = "index.html"

// JSON
this.Data["key"] = "v"
this.ServeJSON()

// 使用Context
this.Ctx.WriteString("hello")
this.Ctx.Output.JSON()

ORM

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

func init() {
    orm.Debug = true
	orm.RegisterDataBase("default", "mysql", "root:pass@/youxi_new?charset=utf8")
}

模型定义与注册

type User struct {
    Id   int
    Name string
}

func init(){
    // 如果使用 orm.QuerySeter 进行高级查询的话,这个是必须的
    // 如果只使用 Raw 查询和 map struct,无需这一步
    orm.RegisterModel(new(User))
}

日志

beego.Emergency("this is emergency")
beego.Alert("this is alert")
beego.Critical("this is critical")
beego.Error("this is error")
beego.Warning("this is warning")
beego.Notice("this is notice")
beego.Informational("this is informational")
beego.Debug("this is debug")

配置文件

默认位于 conf/app.conf

// 获取方式
beego.AppConfig.String("mysqluser")
原文地址:https://www.cnblogs.com/elimsc/p/14979313.html