golang构建web服务入门教程-配置管理(三)

上一节我们通过几行简单的代码生成了快速创建了一个web服务,今天我们就来使用配置文件来进一步学习与使用 Orange 框架;

接着上一节的代码继续往下修改:

在 $GOPATH/src目录下创建一个demo文件夹,并在文件夹内创建 main.go 文件,然后再创建一个 config.toml 文件

config.toml文件内容

[app]
    name = "orange"
    key = "be5356716b937d94eae948f102a2074f"
    httpAddr = "0.0.0.0"
    httpPort = 8088

 

main.go文件内容

package main

import (
    "gitee.com/zhucheer/orange/app"
    "gitee.com/zhucheer/orange/cfg"
)

func main(){
    router := &Route{}
    app.AppStart(router)
}

type Route struct {
}

func (s *Route) ServeMux() {
    app.NewRouter("").GET("/", func(ctx *app.Context) error {
        appName:=cfg.GetString("app.name","") //获取配置信息
        return ctx.ToString("Hello world!"+" appName config value:"+appName)
    })
}

func (s *Route) Register() {
}

 

执行启动命令

启动时带上配置文件参数即可读取指定配置

go run main.go --config=config.toml

 

启动后我们就可以在浏览器看到相应的配置信息已经被获取到了;

通过修改配置文件中的 httpAddr/httpPort 信息,我们还能修改 web 服务绑定的ip和端口,有没有很简单,快来试试吧!

 

 

框架源码地址:https://gitee.com/zhucheer/orange

框架文档地址:https://www.kancloud.cn/chase688/orange_framework

posted @ 2020-05-06 23:20  qīqíqǐqì  阅读(245)  评论(0编辑  收藏  举报