Beego框架学习整理

42 篇文章 1 订阅
15 篇文章 4 订阅

Beego的介绍与使用

一、路由

普通路由

package main

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

	"github.com/astaxie/beego"
)

func main() {
	// 绑定函数
	//以get方式请求根路径时,通过绑定函数处理
	beego.Get("/", func(ctx *context.Context) {
		//用户数据的获取
		name := ctx.Input.Query("name")
		// 给用户相应数据
		ctx.Output.Context.WriteString("你输入的名字是" + name)
	})

	// 处理POST请求
	beego.Post("/", func(ctx *context.Context) {
		// 用户数据的获取
		age := ctx.Input.Query("age")
		// 给用户相应数据
		ctx.Output.Context.WriteString("age = " + age)
	})

	// 相同location下,顺序绑定函数
	beego.Any("/getmethod", func(ctx *context.Context) {
		method := ctx.Input.Method()
		// 返回方法
		ctx.Output.Context.WriteString("method = " + method)
	})

	beego.Run(":7788")
}

正则路由

package main

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

	"github.com/astaxie/beego"
)

func main() {

	//正则路由
	// URL中定义正则字符串的方式进行匹配
	// 匹配/数字/格式的路由 => 并把匹配的值放入到id参数中
	beego.Get("/?:id(^\\d+$)/", func(ctx *context.Context) {
		id := ctx.Input.Param(":id")
		ctx.WriteString("匹配数字 = " + id)
	})

	beego.Get("/:name(^\\w+$)", func(ctx *context.Context) {
		name := ctx.Input.Param(":name")
		ctx.WriteString("匹配name = " + name)
	})

	//匹配任意
	beego.Get("/:content/", func(ctx *context.Context) {
		content := ctx.Input.Param(":content")
		ctx.WriteString("任意都能匹配 = " + content)
	})

	// 获取文件名
	beego.Get("/file/:file(.*)", func(ctx *context.Context) {
		file := ctx.Input.Param(":file")
		ctx.WriteString("匹配file = "+ file)
	})

	beego.Run(":7788")
}

自定义控制器与路由规则

package main

import "github.com/astaxie/beego"

type PostControler struct {
	beego.Controller
}

func (p *PostControler) Add() {
	p.Ctx.WriteString("调用post的add方法")
}

func (p *PostControler) Query() {
	p.Ctx.WriteString("调用post的Query方法")
}

func main() {
	// post请求交给Add处理,get请求交给qurrey处理
	//分好分割路由规则
	beego.Router("/post/add", &PostControler{},"get:Query;post:Add")
	beego.Run(":7788")
}

自动匹配路由

package main

import "github.com/astaxie/beego"

type Task struct {
	beego.Controller
}

func (t *Task) Del() {
	t.Ctx.WriteString("调用del方法:" + t.Ctx.Input.URI() + "method = " + t.Ctx.Input.Method())
}

func main() {
	// 自动路由
	// task ==> taskcontroller,/task/del  会到Task.Del
	beego.AutoRouter(&Task{})
	beego.Run(":7788")
}

二、从Body、请求中获取数据

获取数据

Params
package main

import (
	"fmt"

	"github.com/astaxie/beego"
)

type InputController struct {
	beego.Controller
}

type InPutForm struct {
	Name string `form:"name"`
}

func (i *InputController) QueryParams() {
	// 拿到url参数的方法:
	// 1、使用原生http.Request.ParseForm,拿到http.Request.Form
	// 2、调用beego的input.Query方法,其实内部也是http包的一个封装
	name := i.Ctx.Input.Query("name")
	i.Ctx.WriteString(fmt.Sprintf("name = %s\n", name))

	// 3、通过scan的方式将结果扫描给一个变量
	var name1 string
	i.Ctx.Input.Bind(&name1, "name1")
	i.Ctx.WriteString(fmt.Sprintf("name1 = %s\n", name1))

	// 4、使用controller的getstring方法
	name2 := i.GetString("name2")
	i.Ctx.WriteString(fmt.Sprintf("name2 = %s\n", name2))

	// 5、将参数解析到结构体中(通过反射原理)
	var Form InPutForm
	i.ParseForm(&Form)
	i.Ctx.WriteString(fmt.Sprintf("Form.Name = %s\n", Form.Name))
}

func (c *InputController) GetDataFromUrlAndBody() {
	name := c.GetString("name")
	c.Ctx.WriteString(fmt.Sprintf("GetDataFromUrlAndBody.Name = %s\n", name))
}

func main() {
	// 提交数据的方式:
	// Get ?queryoaram
	// Post ?queryoarams
	// request budy
	// content-type:
	// 1、application/json
	// 2、multipart
	// 3、application/x-www-form-urlencoded

	beego.AutoRouter(&InputController{})
	beego.Run(":7788")
}
json

beego默认不会处理body中的数据,需要手动在conf/app.conf配置文件添加 CopyRequestBody = true

func (i *InputController) Json() {
	// beego默认不会处理body中的数据,需要手动在配置文件添加 CopyRequestBody = true
	// data := i.Ctx.Input.CopyBody(10 * 1024 * 1024)
	// var inputjson *InputJson
	var inputjson map[string]interface{}
	err := json.Unmarshal(i.Ctx.Input.RequestBody, &inputjson)
	if err != nil {
		fmt.Println("json err", err)
		i.Ctx.WriteString(string(err.Error()))
		return
	}
	fmt.Println(inputjson)
	i.Ctx.WriteString("OK")
}
form
func (i *InputController) Form() {
	form1 := i.GetString("form1") 
	i.Ctx.WriteString("form1 = " +  form1)
}
file
func (i *InputController) File() {
	// 1使用request对象
	// 2、使用controller中的getfile
	// i.GetFile("name")
	//3、saveto
	filename := i.GetString("img")
	i.SaveToFile("img", "./upload/a.jpg")
	i.Ctx.WriteString(fmt.Sprintf("filename = %s\n", filename))
}

三、Cokkie

获取客户端的cookie

func (c *CookieController) GetCookie() {
	// //1、第一种方式
	// cokkie, err := c.Ctx.Request.Cookie("name")
	// if err != nil {
	// 	c.Ctx.WriteString(err.Error())
	// }
	// c.Ctx.WriteString(cokkie.Name + cokkie.Value)

	// 2、 对第一种方式的一种封装
	name := c.Ctx.Input.Cookie("name")
	c.Ctx.WriteString(name)
}

设置客户端的cookie

func (c *CookieController) Setcokkie() {
	c.Ctx.SetCookie("name", "chenteng")
	c.Ctx.WriteString("set cookie ok")
}

设置客户端中的secret cookie

使用密钥设置secret cookie,使cokkie加密,防止客户端对cokkie进行篡改

func (c *CookieController) SetSecretcokkie() {
	c.Ctx.SetSecureCookie(CokkieKey, "key", "value")
	c.Ctx.WriteString("SetSecretcokkie ok ")
}

在这里插入图片描述

获取客户端中的secret cookie

func (c *CookieController) GetSecretcokkie() {
	value, ok := c.Ctx.GetSecureCookie(CokkieKey, "key")
	if !ok {
		c.Ctx.WriteString("获取sec cookie 失败")
	}
	fmt.Println("value = ", value)
	c.Ctx.WriteString("GetSecretcokkie ok ")
}

四、响应

响应文字内容

// 第一种发送
func (c *OutputController) Write() {
	c.Ctx.WriteString("内容")
}

// 第二种发送
func (c *OutputController) OutPutWriteString() {
	c.Ctx.Output.Context.WriteString("内容")
}

// 第三种发送
func (c *OutputController) OutPutBody() {
	c.Ctx.Output.Body([]byte("内容"))
}

响应模板文件

// 响应模板文件
func (c *OutputController) Tpl() {
	c.TplName = "output.html"
}

在这里插入图片描述

响应json

func (c *OutputController) Json() {
	c.Data["json"] = map[string]string{"a": "123", "b": "yyy"}
	c.ServeJSON()
}

在这里插入图片描述

重定向

func (c *OutputController) Redir() {
	c.Redirect("http://www.baidu.com", 302)
}

五、获取header中的信息

header是一个map

func (c *OutputController) GetHeader() {
	method := c.Ctx.Request.Method
	url := c.Ctx.Request.URL
	header := c.Ctx.Request.Header["User-Agent"]
	fmt.Fprintf(c.Ctx.ResponseWriter, "method = %v \n,url = %v, \nheader.User-Agent = %v", method, url, header)
}

六、实现模板中的变量或函数

向html文件中发送数据,与自定义函数

先看一下index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=100, initial-scale=1.0">
    <title>index</title>
</head>
<body>
    <h1>我是主页 index</h1>
    <p>name = {{.name}}</p>
    <h2>if语句</h2>
    {{if .Gender}}
    男
    {{ else }}
    女
    {{end}}<br />
    <h2>遍历切片</h2>
    {{ range $index,$value := .scores }}
    {{$index}} = {{$value}}<br />
    {{end}}
    <h2>遍历map</h2>
    {{range $userid,$username := .users }}
    {{$userid}} : {{$username}}<br />
    {{end}}

    <h2>调用函数</h2>
    {{lower .content}}
</body>
</html>

后端代码如下:

package main

import (
	"strings"

	"github.com/astaxie/beego"
)

type HomeController struct {
	beego.Controller
}

func (c *HomeController) Index() {
	c.Data["name"] = "chenteng" // 向模板中传递数据
	c.Data["Gender"] = true     // 想模板中传递布尔值
	c.Data["scores"] = []float32{1, 2, 3}
	c.Data["users"] = map[int]string{1: "chenteng", 2: "zhangfei"}
	c.TplName = "index.html" // 默认后缀只支持html,tpl
	c.Data["content"] = "ChenTeng"
}

func main() {
	beego.AddFuncMap("lower", func(in string) string {
		return strings.ToLower(in)
	})
	beego.AutoRouter(&HomeController{})
	beego.Run(":7788")
}

页面显示
在这里插入图片描述

七、Beego中的配置

参数配置

beego 目前支持 INI、XML、JSON、YAML 格式的配置文件解析,但是默认采用了 INI 格式解析,用户可以通过简单的配置就可以获得很大的灵活性
beego 默认会解析当前应用下的 conf/app.conf 文件。

通过这个文件你可以初始化很多 beego 的默认参数:

appname = "{$appname||myapp}"  ## 从环境变量中获取配置,并带有默认值
httpaddr = "127.0.0.1"
httpport = 9090
runmode ="dev"   ## 可以再页面上看到错误信息,生产模式只会在后台报错
autorender = false
recoverpanic = false
viewspath = "myview"  ## 默认文件夹
StaticDir=“static”  ## 静态文件文件夹
CopyRequestbody = true ## 拷贝body数据
MaxMemry = 104857600  ## 上传文件缓存内存
ServerName=chenteng 
include "app2.conf"  ## 加载其他配置文件,有相同key会被覆盖掉

上面这些参数会替换 beego 默认的一些参数, beego 的参数主要有哪些呢?
请参考https://godoc.org/github.com/astaxie/beego#pkg-constants 。
BConfig 就是 beego 里面的默认的配置,你也可以直接通过beego.BConfig.AppName="beepkg"这样来修改,
和上面的配置效果一样,只是一个在代码里面写死了, 而配置文件就会显得更加灵活。

你也可以在配置文件中配置应用需要用的一些配置信息,例如下面所示的数据库信息:

mysqluser = "root"
mysqlpass = "rootpass"
mysqlurls = "127.0.0.1"
mysqldb   = "beego"

那么你就可以通过如下的方式获取设置的配置信息:

beego.AppConfig.String("mysqluser")
beego.AppConfig.String("mysqlpass")
beego.AppConfig.String("mysqlurls")
beego.AppConfig.String("mysqldb")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈小c

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值