golang web框架设计7:整合框架

golang web framework 框架系列文章:

把前面写好的路由器,控制器,日志,都整合在一起

全局变量和初始化

定义一些框架的全局变量

var (
    BeeApp *App
    AppName string
    AppPath string
    StaticDir map[string]string
    HttpAddr string
    HttpPort int
    RecoverPanic bool
    AutoRender bool
    ViewsPath string
    RunMode string
    AppConfig *Config
)

配置文件初始化:

func init() {
    BeeApp = NewApp()
    AppPath, _ = os.Getwd()
    StaticDir = make(map[string]string)
    var err error
    AppConfig, err = LoadConfig(path.Join(AppPath, "conf", "app.conf"))
    if err != nil {
        Trace("open config err: ", err)
        HttpAddr = ""
        HttpPort = 8080
        AppName = "beego"
        RunMode = "prod"
        AutoRender = true
        RecoverPanic = true
        ViewsPath = "views"
    } else {
        HttpAddr = AppConfig.String("httpaddr")
        if v, err := AppConfig.Int("httpport"); err != nil {
            HttpPort = 8080
        } else {
            HttpPort = v
        }
        AppName = AppConfig.String("appname")
        if runmode := AppConfig.String("runmode"); runmode != "" {
            RunMode = runmode
        } else {
            RunMode = "prod"
        }
        if ar, err := AppConfig.Bool("autorender"); err != nil {
            AutoRender = true
        } else {
            AutoRender = ar
        }
        if ar, err := AppConfig.Bool("autorecover"); err != nil {
            RecoverPanic = true
        } else {
            RecoverPanic = ar
        }
        if views := AppConfig.String("viewspath"); views == "" {
            ViewsPath = "views"
        } else {
            ViewsPath = views
        }
    }
    StaticDir["/static"] = "static"
}

完整代码

代码地址 beego.go

简单使用

package main

import (
    "github.com/jiujuan/beego"
)

type MainController struct {
    beego.Controller
}

func (c *MainController) Get() {
    c.Ctx.WriteString("hello world")
}

func main() {
    beego.BeeApp.RegisterController("/", &MainController{})
    beego.BeeApp.Run()
}
posted @ 2019-11-20 00:40  九卷  阅读(867)  评论(0编辑  收藏  举报