• 服务配置
    • go.mod
    • 配置文件
    • 启动设置

    服务配置

    我们使用go.mod来管理项目依赖。

    go.mod

    /go.mod

    1. module github.com/gogf/gf-demos
    2. require github.com/gogf/gf latest

    其中注意module名称设置为github.com/gogf/gf-demos

    在实际项目的包依赖管理中会遇到很多细节问题,因此我们为您准备了《项目依赖管理》章节。

    配置文件

    这里主要配置了数据库的连接信息。

    /config/config.toml

    1. # 应用系统设置
    2. [setting]
    3. logpath = "/tmp/log/gf-demos"
    4. # 数据库连接
    5. [database]
    6. [[database.default]]
    7. host = "127.0.0.1"
    8. port = "3306"
    9. user = "root"
    10. pass = "12345678"
    11. name = "test"
    12. type = "mysql"

    启动设置

    /boot/boot.go

    1. package boot
    2. import (
    3. "github.com/gogf/gf/g"
    4. "github.com/gogf/gf/g/os/glog"
    5. "github.com/gogf/gf/g/net/ghttp"
    6. )
    7. func init() {
    8. v := g.View()
    9. c := g.Config()
    10. s := g.Server()
    11. // 模板引擎配置
    12. v.AddPath("template")
    13. v.SetDelimiters("${", "}")
    14. // glog配置
    15. logpath := c.GetString("setting.logpath")
    16. glog.SetPath(logpath)
    17. glog.SetStdoutPrint(true)
    18. // Web Server配置
    19. s.SetServerRoot("public")
    20. s.SetLogPath(logpath)
    21. s.SetNameToUriType(ghttp.NAME_TO_URI_TYPE_ALLLOWER)
    22. s.SetErrorLogEnabled(true)
    23. s.SetAccessLogEnabled(true)
    24. s.SetPort(8199)
    25. }

    可以看到,我们的包初始化管理使用了包初始化方法init,这样做的好处是可以在boot目录中使用不同的go文件注册不同的init来分别实现不同的初始化配置管理,在业务比较复杂的项目中比较实用。如果仅仅是需要一个初始化方法即可完成配置,那么开发者可以自定义一个初始化方法,在main包中直接调用即可。