Home >Backend Development >Golang >What is beego in go language?

What is beego in go language?

青灯夜游
青灯夜游Original
2023-01-07 13:50:309870browse

beego is an application Web framework developed using Go language. The purpose is to provide everyone with an efficient Web application development framework, which uses module encapsulation. Beego can be used to quickly develop various applications such as API, Web, and back-end services. It is a RESTFul framework. The main design inspiration comes from the three frameworks of tornado, sinatra, and flask, but it combines some features of Go itself (interface, A framework designed for struct inheritance, etc.).

What is beego in go language?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

1. Introduction to Beego

1.1 What is beego

Beego is an application web framework developed using the Go language. The framework was started in 2012 with the purpose of providing everyone with an efficient web application development framework. The framework is encapsulated in modules and is simple to use and easy to learn. For programmers, beego is very simple to master. They only need to focus on business logic implementation. The framework automatically provides different module functions for project needs.

Beego can be used to quickly develop various applications such as API, Web, and back-end services. It is a RESTFul framework. The main design inspiration comes from the three frameworks of tornado, sinatra, and flask, but it is combined with Go itself. A framework designed for some features (interface, struct inheritance, etc.).

Features

  • ##Simplification: Support RESTful style, MVC model; you can use bee tool classes to improve development efficiency, such as monitoring code Modify and perform rich development and debugging functions such as hot compilation, automated testing of code, and automated packaging and deployment.
  • Intelligent: The beego framework encapsulates the routing module, supports intelligent routing, intelligent monitoring, and can monitor memory consumption, CPU usage and goroutine operating status, making it convenient for developers to implement online applications. Carry out monitoring and analysis.
  • Modularization: beego decouples and encapsulates the code based on functions, forming independent modules such as Session, Cache, Log, configuration parsing, performance monitoring, context operations, ORM, etc., which is convenient Developers use it
  • High performance: beego uses Go's native http request, and the concurrency efficiency of goroutine can cope with high-traffic web applications and API references.

1.2 Command line tool Bee

bee

bee is a development tool , assisting Beego framework development projects is a tool for creating projects, running projects, hot deployment and other related project management. Beego is the source code responsible for development, and bee is the tool responsible for building and managing projects.

USAGE
    bee command [arguments]

AVAILABLE COMMANDS

    version     Prints the current Bee version // 打印当前bee版本
    migrate     Runs database migrations	// 运行数据库的
    api         Creates a Beego API application // 构建一个beego的API应用
    bale        Transforms non-Go files to Go source files// 转义非go的文件到go的src中区
    fix         Fixes your application by making it compatible with newer versions of Beego
// 通过使得新版本的beego兼容来修复应用
    pro         Source code generator// 源代码生成器
    dev         Commands which used to help to develop beego and bee// 辅助开发beego和bee的
    dlv         Start a debugging session using Delve// 使用delve进行debbugging
    dockerize   Generates a Dockerfile for your Beego application // 为beego应用生成dockfile
    generate    Source code generator// 源代码生成器
    hprose      Creates an RPC application based on Hprose and Beego frameworks
    new         Creates a Beego application// 创建beego应用
    pack        Compresses a Beego application into a single file // 压缩beego项目文件
    rs          Run customized scripts// 运行自定义脚本
    run         Run the application by starting a local development server
// 通过启动本地开发服务器运行应用
    server      serving static content over HTTP on port// 通过HTTP在端口上提供静态内容
    update      Update Bee// 更新bee
// 创建一个beego项目
bee new FirstBeego
// 运行beego项目
bee run

What is beego in go language?

2. Install beego
// 下载beego的安装包
go get -u github.com/beego/beego/v2@v2.0.0
// 可能会与遇到错误,如下图所示,然后开启set GO111MODULE=on即可,go env可以看环境变量配置,mac/Linux使用export GO111MODULE=on即可
set GO111MODULE=on

What is beego in go language?

If installed Still no response

set GO111MODULE=on
set GOPROXY=https://goproxy.io

// 然后再执行,即可完成安装beego和bee
$ go get -u github.com/beego/beego/v2
$ go get -u github.com/beego/bee/v2

##3. Beego startup process analysis

3.1 Program entry

import (
	_ "FirstBeego/routers"
	beego "github.com/beego/beego/v2/server/web"
)

func main() {
	beego.Run()
}

// -------------------routers-------------------
import (
	"FirstBeego/controllers"
	beego "github.com/beego/beego/v2/server/web"
)

func init() {// 会先执行init()函数
    beego.Router("/", &controllers.MainController{})
}

// -------------------MainController-------------------
type MainController struct {
	beego.Controller
}

func (c *MainController) Get() {
	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "index.tpl"
}

Go language execution sequence

What is beego in go language?

Beego’s beego.Run() logic

##Complete execution After the init() method, the program continues to execute downwards to the main function. At this time,

beego.Run()
is executed in the main function, and the following main things are done:

Parse the configuration file, that is, the app.conf file, and obtain the port, application name and other information.

    Check whether the session is enabled. If the session is enabled, a session object will be initialized.
  • Whether it is compiled Templates, the beego framework will precompile all templates in the views directory according to the configuration when the project is started, and then store them in the map. This can effectively improve the efficiency of template operation and does not require multiple compilations
  • Listening service port, configure the port according to the app.conf file, and start monitoring
##4. Beego organizational structure

Project configuration: conf

Controllers: controllers

This directory is the directory where the controller files are stored. The so-called controller is the control Which business logic is called by the application? After the controller handles the HTTP request, it is responsible for returning it to the front-end caller.

Data layer: models

The models layer can be interpreted as the entity layer or the data layer, and the processing of user and business data is implemented in the models layer , some operations mainly related to database tables will be implemented in this directory, and then the result data after execution will be returned to the controller layer. The operations of adding, deleting, modifying and checking are all implemented in models.

Routing layer: routers

路由层,即分发,对进来的后天的请求进行分发操作,当浏览器进行一个http请求达到后台的web项目的时候,必须要让程序能够根据浏览器的请求url进行不同的业务处理,从接受前端请求到判断执行具体的业务逻辑的过程的工作,就让routers来实现。

静态资源目录:static

在static目录下,存放的是web项目的静态资源文件,主要有css、img、js、html这几类文件。html中会存放应用的静态页面文件。

视图模板:views

views中存放的就是应用存放html模板页面的目录,所谓模板,就是页面框架和布局是已经用html写好了的,只需要在进行访问和展示的时候,将获取到的数据动态填充到页面中,能够提高渲染效率。因此,模板文件是非常常见的一种方式。

整个项目的架构就是MVC的运行模式。

5. beego框架路由设置

在beego框架中,支持四种路由设置,分别是:基础路由固定路由正则路由自动路由

基础路由

直接给过beego.Get()beego.Post()beego.Put()beego.Delete()等方法进行路由的映射,。

beego.Get("",func) // 表示Get
beego.Post("",func) // 表示Post

固定路由

beego.Router("/",controller)

Get请求就会对应到Get方法,Post对应到post方法,Delete对应到Delete方法,Header方法对应到Header方法。

正则路由

正则路由是指可以在进行固定路由的基础上,支持匹配一定格式的正则表达式,比如:id:username自定义正则,file的路径和后缀切换以及全匹配等操作。

自定义路由

在开发的时候用固定匹配想要直接执行对应的逻辑控制方法,因此beego提供了可以自定义的自定义路由配置。

beego.Router("/",&IndexController{},"")

// Router adds a patterned controller handler to BeeApp.
// it's an alias method of HttpServer.Router.
// usage:
//  simple router
//  beego.Router("/admin", &admin.UserController{})
//  beego.Router("/admin/index", &admin.ArticleController{})
//
//  regex router
//
//  beego.Router("/api/:id([0-9]+)", &controllers.RController{})
//
//  custom rules
//  beego.Router("/api/list",&RestController{},"*:ListFood")
//  beego.Router("/api/create",&RestController{},"post:CreateFood")
//  beego.Router("/api/update",&RestController{},"put:UpdateFood")
//  beego.Router("/api/delete",&RestController{},"delete:DeleteFood")

6. 静态文件的设置

在go的web项目中,一些静态资源文件,如果用户要访问静态资源文件,则我们也是能够访问到的,这需要我们的项目中进行静态资源设置。

beego.SetStaticPath("/down1","download1")

这里的download目录是指的非go web项目的static目录下目录,而是开发者重新新建的另外的目录。

7. Beego博客项目

beego的orm是可以自动创建表的,与python的django框架有的一拼。

在Go中Object类型的数据使用interface{}空的接口类型来代替。

如果有js文件失效,注意清除缓存之后再来玩,否则添加的js不会生效。

// 首页显示内容,f
func MakeHomeBlocks(articles []Article, isLogin bool) template.HTML {
	htmlHome := ""
	// for index, value := range objects{} 实现遍历
	for _, art := range articles {
		// 转换为模板所需要的数据
		homePageParam := HomeBlockParam{}
		homePageParam.Id = art.Id
		homePageParam.Title = art.Title
		homePageParam.Tags = createTagsLinks(art.Tags)
		homePageParam.Short = art.Short
		homePageParam.Content = art.Content
		homePageParam.Author = art.Author
		homePageParam.CreateTime = utils.SwitchTimeStampToData(art.CreateTime)
		homePageParam.Link = "/article/" + strconv.Itoa(art.Id)
		homePageParam.UpdateLink = "/article/update?id=" + strconv.Itoa(art.Id)
		homePageParam.DeleteLink = "/article/delete?id=" + strconv.Itoa(art.Id)
		homePageParam.IsLogin = isLogin

		// 处理变量,利用ParseFile解析该文件,用于插入变量
		t, _ := template.ParseFiles("views/block/home_block.html")
		buffer := bytes.Buffer{}
		t.Execute(&buffer, homePageParam)
		htmlHome += buffer.String()
	}
	fmt.Println("htmlHome ===>", htmlHome)
	return template.HTML(htmlHome)
}
// 这里可以实现html模板的渲染和追加 最后以html代码的形式插入到具体的前端html展示页面

博客项目大概做了三天吧。就搞完了。基本的代码都是MVC结构,跟Java比较像,不过对HTML的支持,感觉beego做的更好一些。让人使用起来就很舒服的感觉。其他的就下面总结一下吧:

beego的项目目录结构如下:

What is beego in go language?

负责和数据库交互的是model,model主要存放实体类和承接具体的数据请求等相关的方法操作,提供数据给controller层。

What is beego in go language?

路由的话主要有四种:

  • 默认路由:beego自带模块Post、Put、Delete、Head、Get等网络请求类型的对应方法

  • 自动路由:自动实现映射到Post、Put、Delete、Get等

  • 正则表达式路由:"/article/:id"接收参数的时候需要idStr := this.Ctx.Input.Param(":id")

  • 自定义路由:在博客开发中基本就是自定义路由了/article/add

Session的处理:

  • 配置文件中配置session相关的配置
  • 代码中通过SessionConfig进行参数配置

操作session

  • SetSession:设置session值
  • GetSession:获取session值
  • DelSession:删除session值

View视图模板:

  • controller.TplName指定渲染当前页面的模板文件全称
  • 模板文件中通过{{.param}}实现变量数据的获取操作
  • controller.Data["param"]=xxx实现对页面的需要使用的变量进行赋值操作

项目打包运行

// 项目可以部署在linux上面,一般通过bee来实现直接打包,打包命令为
bee pack -be GOOS=linux // linux上可以没有go的环境

如果直接通过这个命令打包的话,会生成一个tar.gz的压缩文件,此时我们可以tar -zxvf xxx.tar.gz进行解压缩。

然后对项目文件赋予执行权:chmod +x myblog即可配置到执行权。如果现在直接执行的话会报错:

beego panic: err: go command required, not found: exec: “go”: executable file not found in $PATH: stderr:

解决办法是把conf中的runmode=dev修改为runmode=prod即可实现执行。

【相关推荐:Go视频教程编程教学

The above is the detailed content of What is beego in go language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn