完成了框架的基本架构
This commit is contained in:
149
13.4.md
149
13.4.md
@@ -6,10 +6,157 @@
|
||||
MVC设计模式是目前Web应用开发中最常见的一种架构模式,通过分离 Model(模型)、View(视图)和 Controller(控制器),可以更容易实现易于扩展的UI。Model指后台返回的数据;View指需要渲染的页面,通常是模板页面,渲染后的结果通常是HTML;Controller指Web开发人员编写的处理不同URL的控制器,如前面小节讲述的路由就是转发到控制器的过程,controller在整个的MVC框架中起到了一个核心的作用,处理业务逻辑,因此控制器是整个框架中必不可少的一部分,Model和View会更具不同的业务可以不写,例如没有数据处理的逻辑处理,没有页面输出的302调整之类的就不需要Model和View,但是controller是必不可少的。
|
||||
|
||||
## beego的REST设计
|
||||
前面小节介绍了路由实现了注册struct的功能,而struct中实现了REST方式,因此我们需要设计一个用于逻辑处理controller的基类,这里主要设计了两个类型,一个struct、一个interface
|
||||
|
||||
type Controller struct {
|
||||
Ct *Context
|
||||
Tpl *template.Template
|
||||
Data map[interface{}]interface{}
|
||||
ChildName string
|
||||
TplNames string
|
||||
Layout []string
|
||||
TplExt string
|
||||
}
|
||||
|
||||
type ControllerInterface interface {
|
||||
Init(ct *Context, cn string) //初始化上下文和子类名称
|
||||
Prepare() //开始执行之前的一些处理
|
||||
Get() //method=GET的处理
|
||||
Post() //method=POST的处理
|
||||
Delete() //method=DELETE的处理
|
||||
Put() //method=PUT的处理
|
||||
Head() //method=HEAD的处理
|
||||
Patch() //method=PATCH的处理
|
||||
Options() //method=OPTIONS的处理
|
||||
Finish() //执行完成之后的处理 Render() error //执行完method对应的方法之后渲染页面
|
||||
}
|
||||
|
||||
那么前面介绍的路由add的时候是定义了ControllerInterface类型,因此,只要我们实现这个接口就可以,所以我们的基类Controller实现如下的方法:
|
||||
|
||||
func (c *Controller) Init(ct *Context, cn string) {
|
||||
c.Data = make(map[interface{}]interface{})
|
||||
c.Layout = make([]string, 0)
|
||||
c.TplNames = ""
|
||||
c.ChildName = cn
|
||||
c.Ct = ct
|
||||
c.TplExt = "tpl"
|
||||
}
|
||||
|
||||
func (c *Controller) Prepare() {
|
||||
|
||||
}
|
||||
|
||||
func (c *Controller) Finish() {
|
||||
|
||||
}
|
||||
|
||||
func (c *Controller) Get() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Post() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Delete() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Put() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Head() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Patch() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Options() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Render() error {
|
||||
if len(c.Layout) > 0 {
|
||||
var filenames []string
|
||||
for _, file := range c.Layout {
|
||||
filenames = append(filenames, path.Join(ViewsPath, file))
|
||||
}
|
||||
t, err := template.ParseFiles(filenames...)
|
||||
if err != nil {
|
||||
Trace("template ParseFiles err:", err)
|
||||
}
|
||||
err = t.ExecuteTemplate(c.Ct.ResponseWriter, c.TplNames, c.Data)
|
||||
if err != nil {
|
||||
Trace("template Execute err:", err)
|
||||
}
|
||||
} else {
|
||||
if c.TplNames == "" {
|
||||
c.TplNames = c.ChildName + "/" + c.Ct.Request.Method + "." + c.TplExt
|
||||
}
|
||||
t, err := template.ParseFiles(path.Join(ViewsPath, c.TplNames))
|
||||
if err != nil {
|
||||
Trace("template ParseFiles err:", err)
|
||||
}
|
||||
err = t.Execute(c.Ct.ResponseWriter, c.Data)
|
||||
if err != nil {
|
||||
Trace("template Execute err:", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Controller) Redirect(url string, code int) {
|
||||
c.Ct.Redirect(code, url)
|
||||
}
|
||||
|
||||
上面的controller基类完成了接口定义的函数,通过路由根据url执行相应的controller的原则,会以此执行如下的函数:
|
||||
|
||||
Init() 初始化
|
||||
Prepare() 执行之前的初始化,每个继承的子类可以来实现该函数
|
||||
method() 根据不同的method执行不同的函数:GET、POST、PUT、HEAD等,子类来实现这些函数,如果没实现,那么默认都是403
|
||||
Render() 可选,根据全局变量AutoRender来判断是否执行
|
||||
Finish() 执行完之后执行的操作,每个继承的子类可以来实现该函数
|
||||
|
||||
## 应用指南
|
||||
上面beego框架中完成了controller基类的设计,那么我们在我们的应用中可以这样来设计我们的方法:
|
||||
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"github.com/astaxie/beego"
|
||||
)
|
||||
|
||||
type MainController struct {
|
||||
beego.Controller
|
||||
}
|
||||
|
||||
func (this *MainController) Get() {
|
||||
this.Data["Username"] = "astaxie"
|
||||
this.Data["Email"] = "astaxie@gmail.com"
|
||||
this.TplNames = "index.tpl"
|
||||
}
|
||||
|
||||
上面的方式我们实现了子类MainController,实现了Get方法,那么如果用户通过其他的方式(POST/HEAD等)来访问该资源都将返回403,而如果是Get来访问,因为我们设置了AutoRender=true,那么在执行玩Get方法之后会自动执行Render函数,就会显示如下界面:
|
||||
|
||||

|
||||
|
||||
index.tpl的代码如下所示,我们可以看到数据的设置和显示都是相当的简单方便:
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>beego welcome template</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello, world!{{.Username}},{{.Email}}</h1>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
* 上一章: [自定义路由器设计](<13.3.md>)
|
||||
* 下一节: [数据库操作](<13.5.md>)
|
||||
* 下一节: [日志和配置设计](<13.5.md>)
|
||||
244
13.5.md
244
13.5.md
@@ -1,4 +1,246 @@
|
||||
# 13.5 数据库操作
|
||||
# 13.5 日志和配置设计
|
||||
|
||||
## 日志和配置的重要性
|
||||
前面已经介绍过日志在我们程序开发中起着很重要的作用,通过日志我们可以记录调试我们的信息,当初介绍过一个日志系统seelog,根据不同的level输出不同的日志,这个对于程序开发和程序部署来说至关重要。我们可以在程序开发中设置level低一点,部署的时候把level设置高,这样我们开发中的调试信息可以屏蔽掉。
|
||||
|
||||
配置模块对于应用部署牵涉到服务器不同的一些配置信息非常有用,例如一些数据库配置信息、监听端口、监听地址等都是可以通过配置文件来配置,这样我们的应用程序就具有很强的灵活性,可以通过配置文件的配置部署在不同的机器上,可以连接不同的数据库之类的。
|
||||
|
||||
## beego的日志设计
|
||||
beego的日志设计部署思路来自于seelog,根据不同的level来记录日志,但是beego设计的日志系统比较轻量级,采用了系统的log.Logger接口,默认输出到os.Stdout,用户可以实现这个接口然后通过beego.SetLogger设置自定义的输出,详细的实现如下所示:
|
||||
|
||||
|
||||
// Log levels to control the logging output.
|
||||
const (
|
||||
LevelTrace = iota
|
||||
LevelDebug
|
||||
LevelInfo
|
||||
LevelWarning
|
||||
LevelError
|
||||
LevelCritical
|
||||
)
|
||||
|
||||
// logLevel controls the global log level used by the logger.
|
||||
var level = LevelTrace
|
||||
|
||||
// LogLevel returns the global log level and can be used in
|
||||
// own implementations of the logger interface.
|
||||
func Level() int {
|
||||
return level
|
||||
}
|
||||
|
||||
// SetLogLevel sets the global log level used by the simple
|
||||
// logger.
|
||||
func SetLevel(l int) {
|
||||
level = l
|
||||
}
|
||||
|
||||
上面这一段实现了日志系统的日志分级,默认的级别是Trace,用户通过SetLevel可以设置不同的分级。
|
||||
|
||||
// logger references the used application logger.
|
||||
var BeeLogger = log.New(os.Stdout, "", log.Ldate|log.Ltime)
|
||||
|
||||
// SetLogger sets a new logger.
|
||||
func SetLogger(l *log.Logger) {
|
||||
BeeLogger = l
|
||||
}
|
||||
|
||||
// Trace logs a message at trace level.
|
||||
func Trace(v ...interface{}) {
|
||||
if level <= LevelTrace {
|
||||
BeeLogger.Printf("[T] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Debug logs a message at debug level.
|
||||
func Debug(v ...interface{}) {
|
||||
if level <= LevelDebug {
|
||||
BeeLogger.Printf("[D] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Info logs a message at info level.
|
||||
func Info(v ...interface{}) {
|
||||
if level <= LevelInfo {
|
||||
BeeLogger.Printf("[I] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Warning logs a message at warning level.
|
||||
func Warn(v ...interface{}) {
|
||||
if level <= LevelWarning {
|
||||
BeeLogger.Printf("[W] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Error logs a message at error level.
|
||||
func Error(v ...interface{}) {
|
||||
if level <= LevelError {
|
||||
BeeLogger.Printf("[E] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Critical logs a message at critical level.
|
||||
func Critical(v ...interface{}) {
|
||||
if level <= LevelCritical {
|
||||
BeeLogger.Printf("[C] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
上面这一段代码默认初始化了一个BeeLogger对象,默认输出到os.Stdout,用户可以通过beego.SetLogger来设置实现了logger的接口输出。这里面实现了六个函数:
|
||||
|
||||
- Trace(一般的记录信息,举例如下:)
|
||||
- "Entered parse function validation block"
|
||||
- "Validation: entered second 'if'"
|
||||
- "Dictionary 'Dict' is empty. Using default value"
|
||||
- Debug(调试信息,举例如下:)
|
||||
- "Web page requested: http://somesite.com Params='...'"
|
||||
- "Response generated. Response size: 10000. Sending."
|
||||
- "New file received. Type:PNG Size:20000"
|
||||
- Info(打印信息,举例如下:)
|
||||
- "Web server restarted"
|
||||
- "Hourly statistics: Requested pages: 12345 Errors: 123 ..."
|
||||
- "Service paused. Waiting for 'resume' call"
|
||||
- Warn(警告信息,举例如下:)
|
||||
- "Cache corrupted for file='test.file'. Reading from back-end"
|
||||
- "Database 192.168.0.7/DB not responding. Using backup 192.168.0.8/DB"
|
||||
- "No response from statistics server. Statistics not sent"
|
||||
- Error(错误信息,举例如下:)
|
||||
- "Internal error. Cannot process request #12345 Error:...."
|
||||
- "Cannot perform login: credentials DB not responding"
|
||||
- Critical(致命错误,举例如下:)
|
||||
- "Critical panic received: .... Shutting down"
|
||||
- "Fatal error: ... App is shutting down to prevent data corruption or loss"
|
||||
|
||||
可以看到每个函数里面都有对level的判断,所以如果我们在部署的时候设置了level=LevelWarning,那么Trace、Debug、Info这三个函数都不会有任何的输出,以此类推。
|
||||
|
||||
## beego的配置设计
|
||||
配置信息的解析,beego实现了一个key=value的配置文件读取,类似ini配置文件的格式,就是一个文件解析的过程,然后把解析的数据保存到map中,最后在调用的时候通过几个string、int之类的函数调用返回相应的值,具体的实现请看下面:
|
||||
|
||||
首先定义了一些ini配置文件的一些全局性常量 :
|
||||
|
||||
var (
|
||||
bComment = []byte{'#'}
|
||||
bEmpty = []byte{}
|
||||
bEqual = []byte{'='}
|
||||
bDQuote = []byte{'"'}
|
||||
)
|
||||
|
||||
定义了配置文件的格式:
|
||||
|
||||
// A Config represents the configuration.
|
||||
type Config struct {
|
||||
filename string
|
||||
comment map[int][]string // id: []{comment, key...}; id 1 is for main comment.
|
||||
data map[string]string // key: value
|
||||
offset map[string]int64 // key: offset; for editing.
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
定义了解析文件的函数,解析文件的过程是打开文件,然后一行一行的读取,解析注释、空行和key=value数据:
|
||||
|
||||
// ParseFile creates a new Config and parses the file configuration from the
|
||||
// named file.
|
||||
func LoadConfig(name string) (*Config, error) {
|
||||
file, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg := &Config{
|
||||
file.Name(),
|
||||
make(map[int][]string),
|
||||
make(map[string]string),
|
||||
make(map[string]int64),
|
||||
sync.RWMutex{},
|
||||
}
|
||||
cfg.Lock()
|
||||
defer cfg.Unlock()
|
||||
defer file.Close()
|
||||
|
||||
var comment bytes.Buffer
|
||||
buf := bufio.NewReader(file)
|
||||
|
||||
for nComment, off := 0, int64(1); ; {
|
||||
line, _, err := buf.ReadLine()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if bytes.Equal(line, bEmpty) {
|
||||
continue
|
||||
}
|
||||
|
||||
off += int64(len(line))
|
||||
|
||||
if bytes.HasPrefix(line, bComment) {
|
||||
line = bytes.TrimLeft(line, "#")
|
||||
line = bytes.TrimLeftFunc(line, unicode.IsSpace)
|
||||
comment.Write(line)
|
||||
comment.WriteByte('\n')
|
||||
continue
|
||||
}
|
||||
if comment.Len() != 0 {
|
||||
cfg.comment[nComment] = []string{comment.String()}
|
||||
comment.Reset()
|
||||
nComment++
|
||||
}
|
||||
|
||||
val := bytes.SplitN(line, bEqual, 2)
|
||||
if bytes.HasPrefix(val[1], bDQuote) {
|
||||
val[1] = bytes.Trim(val[1], `"`)
|
||||
}
|
||||
|
||||
key := strings.TrimSpace(string(val[0]))
|
||||
cfg.comment[nComment-1] = append(cfg.comment[nComment-1], key)
|
||||
cfg.data[key] = strings.TrimSpace(string(val[1]))
|
||||
cfg.offset[key] = off
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
下面实现了一些读取配置文件的函数,返回的值确定为bool、int、float64或string:
|
||||
|
||||
// Bool returns the boolean value for a given key.
|
||||
func (c *Config) Bool(key string) (bool, error) {
|
||||
return strconv.ParseBool(c.data[key])
|
||||
}
|
||||
|
||||
// Int returns the integer value for a given key.
|
||||
func (c *Config) Int(key string) (int, error) {
|
||||
return strconv.Atoi(c.data[key])
|
||||
}
|
||||
|
||||
// Float returns the float value for a given key.
|
||||
func (c *Config) Float(key string) (float64, error) {
|
||||
return strconv.ParseFloat(c.data[key], 64)
|
||||
}
|
||||
|
||||
// String returns the string value for a given key.
|
||||
func (c *Config) String(key string) string {
|
||||
return c.data[key]
|
||||
}
|
||||
|
||||
## 应用指南
|
||||
下面这个函数是我一个应用中的例子,用来获取远程url地址的json数据,实现如下:
|
||||
|
||||
func GetJson() {
|
||||
resp, err := http.Get(beego.AppConfig.String("url"))
|
||||
if err != nil {
|
||||
beego.Critical("http get info error")
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
err = json.Unmarshal(body, &AllInfo)
|
||||
if err != nil {
|
||||
beego.Critical("error:", err)
|
||||
}
|
||||
}
|
||||
|
||||
函数中调用了框架的日志函数`beego.Critical`函数用来报错,调用了`beego.AppConfig.String("url")`用来获取配置文件中的信息,配置文件的信息如下(app.conf):
|
||||
|
||||
appname = hs
|
||||
url ="http://www.api.com/api.html"
|
||||
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
|
||||
2
13.md
2
13.md
@@ -8,7 +8,7 @@
|
||||
* 2 [数据库设计](13.2.md)
|
||||
* 3 [自定义路由器设计](13.3.md)
|
||||
* 4 [controller设计](13.4.md)
|
||||
* 5 [数据库操作](13.5.md)
|
||||
* 5 [日志和配置设计](13.5.md)
|
||||
* 6 [实现博客的增删改](13.6.md)
|
||||
* 7 [小结](13.7.md)
|
||||
|
||||
|
||||
@@ -43,11 +43,6 @@
|
||||
- [BianJiang](https://github.com/border) (编写go开发工具Vim和Emacs的设置)
|
||||
- [Oling Cat](https://github.com/OlingCat)(review代码)
|
||||
- [Wenlei Wu](mailto:spadesacn@gmail.com)(提供一些图片展示)
|
||||
|
||||
##友情链接
|
||||
目前Go开发的比较成熟的一个框架是由我们国人开发的,目前版本已经比较成熟,而且提供了很多的应用demo,方便快速开发Web应用,该框架是由海意和BianJiang开发维护,推荐大家看看:
|
||||
|
||||
[golangers框架](https://github.com/golangers/framework)
|
||||
|
||||
## 授权许可
|
||||
除特别声明外,本书中的内容使用[CC BY-SA 3.0 License](http://creativecommons.org/licenses/by-sa/3.0/)(创作共用 署名-相同方式共享3.0许可协议)授权,代码遵循[BSD 3-Clause License](<https://github.com/astaxie/build-web-application-with-golang/blob/master/LICENSE.md>)(3项条款的BSD许可协议)。
|
||||
|
||||
BIN
images/13.4.beego.png
Normal file
BIN
images/13.4.beego.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 46 KiB |
@@ -81,7 +81,7 @@
|
||||
- 13.2 [数据库设计](13.2.md)
|
||||
- 13.3 [自定义路由器设计](13.3.md)
|
||||
- 13.4 [controller设计](13.4.md)
|
||||
- 13.5 [数据库操作](13.5.md)
|
||||
- 13.5 [日志和配置设计](13.5.md)
|
||||
- 13.6 [实现博客的增删改](13.6.md)
|
||||
- 13.7 [小结](13.7.md)
|
||||
* 14.扩展博客管理系统
|
||||
|
||||
Reference in New Issue
Block a user