您的位置 首页 golang

gin项目配置


1.概述

项目配置是整个项目中很重要的一部分,一般项目的配置有数据库配置,应用配置(地址,端口等),缓存配置,第三方扩展的配置,中间件配置等等,可见配置在一个项目中的地位是很重要的,但是,gin中没有提供相关的配置管理的组件,我们可以使用go的第三方包来做配置管理,集成到gin中。

常用的第三方包有:

本教程主要讲解ini,其他的请执行Google

2.ini的使用

目录结构我们使用前面推荐项目结构

  • 安装gopkg.in/ini.v1
go get gopkg.in/ini.v1
  • 在conf下创建app.ini配置文件
[server]address = 0.0.0.0port = 8080
  • 在pkg中创建config目录,并创建server.go,配置Server配置
package configimport (    "cn.sockstack/gin_demo/pkg/helper"    "gopkg.in/ini.v1")var Server *servertype server struct {    Address string    Port int    source *ini.File}func (s *server) Load(path string) *server {    var err error    //判断配置文件是否存在    exists, err := helper.PathExists(path)    if !exists {        return s    }    s.source, err = ini.Load(path)    if err != nil {        panic(err)    }    return s}func (s *server)Init() *server {    //判断配置是否加载成功    if s.source == nil {        return s    }    s.Address = s.source.Section("server").Key("address").MustString("0.0.0.0")    s.Port = s.source.Section("server").Key("port").MustInt(8080)    return s}

注意:helper.PathExists(path)是pkg/helper/util.go的工具方法,实现如下

package helperimport "os"func PathExists(path string) (bool, error) {    _, err := os.Stat(path)    if err == nil {        return true, nil    }    if os.IsNotExist(err) {        return false, nil    }    return false, err}
  • 测试配置,在pkg/config目录下创建server_test.go,并运行
package configimport (    "fmt"    "testing")func TestServer(t *testing.T) {    Server = (&server{}).Load("../../conf/app.ini").Init()    fmt.Println(Server)    if Server == nil {        t.Fail()    }}
  • 测试结果,测试通过
=== RUN   TestServer&{0.0.0.0 8081 0xc000118000}--- PASS: TestServer (0.00s)PASSProcess finished with exit code 0
  • 在pkg/config目录下创建init.go,初始化配置
package configfunc init() {    Server = (&server{}).Load("conf/app.ini").Init()}
  • gin整合配置,使用快速入门的例子
package main// 导入gin包import (    "cn.sockstack/gin_demo/pkg/config"    "fmt"    "github.com/gin-gonic/gin")// 入口函数func main() {    // 初始化一个http服务对象    r := gin.Default()    // 设置一个get请求的路由,url为/hello, 处理函数(或者叫控制器函数)是一个闭包函数。    r.GET("/hello", func(c *gin.Context) {        // 通过请求上下文对象Context, 直接往客户端返回一个json        c.JSON(200, gin.H{            "message": "hello world",        })    })    r.Run(fmt.Sprintf("%s:%d", config.Server.Address, config.Server.Port)) // 监听并在 0.0.0.0:8080 上启动服务}
  • 控制台输出
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env:   export GIN_MODE=release - using code:  gin.SetMode(gin.ReleaseMode)[GIN-debug] GET    /hello                    --> main.main.func1 (3 handlers)[GIN-debug] Listening and serving HTTP on 0.0.0.0:8080
  • 浏览器输入localhost:8080/hello测试,响应结果
{    "message": "hello world"}

3.后记

本教程使用了ini配置,其他的配置使用方式类似,有兴趣的可以自行实现。

出处gin从入门到实践更多精彩文章,请关注我的博客SOCKSTACK,分享我的工作经验。


文章来源:智云一二三科技

文章标题:gin项目配置

文章地址:https://www.zhihuclub.com/5603.shtml

关于作者: 智云科技

热门文章

网站地图