gin框架讀取配置文件的兩種方法 ④


上接:gin框架實現一個簡單的項目 ③

在一個項目中,為了方便后期上線,一般會將需要改動的條件存放在配置文件中,比如監聽的端口號,連接數據的語句等,下面介紹一下本人使用過的兩種讀取配置文件的方法:

文件結構如下:

controller->index.go

package controller

import (
    "fmt"
    "project/controller/second"

    "github.com/gin-gonic/gin"
)

func GinRouter(r *gin.Engine) *gin.Engine {
    rr := r.Group("/")
    rr.GET("/first", func(c *gin.Context) {
        fmt.Println("first .........")
    })
    rr = r.Group("/a")
    second.Routers(rr)
    return r
}
View Code

controller->second->index.go

package second

import (
    "fmt"
    "net/http"
    ms "project/model/second"
    ss "project/services/second"

    "github.com/gin-gonic/gin"
)

func Routers(r *gin.RouterGroup) {
    rr := r.Group("")
    rr.POST("/second", Function)
    return
}
func Function(c *gin.Context) {
    var input ms.Input
    if err := c.BindJSON(&input); err != nil {
        fmt.Println(err)
    }
    if output, err := ss.Function(c, input); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{
            "code": http.StatusBadRequest,
            "msg":  "獲取數據失敗",
            "data": output,
        })
    } else {
        c.JSON(http.StatusOK, gin.H{
            "code": http.StatusOK,
            "msg":  "獲取數據成功",
            "data": output,
        })
    }
    return
}
View Code

model->second->index.go

package second

type Input struct {
    //view:用於注釋
    //json:json形式
    //from:解釋該字段來自哪里,比如那個表
    //binding: required:必須字段 email:email形式
    //grom:數據庫中列名
    Id int `view:"id號" json:"id" from:"id" binding:"required" gorm:"column:id"`
}

type Output struct {
    Database DatabaseConfig `json:"database"`
    Self     SelfConfig     `json:"self"`
}

type DatabaseConfig struct {
    Types  string `json:"types"`
    Local  string `json:"local"`
    Online string `json:"online"`
}

type SelfConfig struct {
    Port string `json:"port"`
    Flag int    `json:"flag"`
    Tag  int    `json:"tag"`
}
View Code

services->second->index.go

package second

import (
    "fmt"
    ms "project/model/second"
    u "project/utils"

    "github.com/gin-gonic/gin"
)

func Function(c *gin.Context, input ms.Input) (output ms.Output, err error) {
    fmt.Println("second .........,input:", input.Id)
    if input.Id == 1 {
        output.Database.Types = u.Config().Database.Types
        output.Database.Local = u.Config().Database.Local
        output.Database.Online = u.Config().Database.Online
        output.Self.Flag = u.Config().Self.Flag
        output.Self.Port = u.Config().Self.Port
        output.Self.Tag = u.Config().Self.Tag
    } else if input.Id == 2 {
        output.Database.Types, output.Database.Local, output.Database.Online, err = u.GetDatabase()
        if err != nil {
            return output, err
        }
        output.Self.Port, output.Self.Flag, output.Self.Tag, err = u.GetSelf()
        if err != nil {
            return output, err
        }
    }
    return output, nil
}
View Code

utils->read_config_ini.go //讀取配置文件1

package utils

import (
    "fmt"
    "strconv"

    "github.com/Unknwon/goconfig"
)

var cfg *goconfig.ConfigFile

func GetConfigIni(filepath string) (err error) {
    config, err := goconfig.LoadConfigFile(filepath)
    if err != nil {
        fmt.Println("配置文件讀取錯誤,找不到配置文件", err)
        return err
    }
    cfg = config
    return nil
}

func GetDatabase() (types, local, online string, err error) {
    if types, err = cfg.GetValue("database", "types"); err != nil {
        fmt.Println("配置文件中不存在types", err)
        return types, local, online, err
    }
    if local, err = cfg.GetValue("database", "local"); err != nil {
        fmt.Println("配置文件中不存在local", err)
        return types, local, online, err
    }
    if online, err = cfg.GetValue("database", "online"); err != nil {
        fmt.Println("配置文件中不存在online", err)
        return types, local, online, err
    }
    return types, local, online, nil
}

func GetSelf() (port string, flag, tag int, err error) {
    if port, err = cfg.GetValue("self", "port"); err != nil {
        fmt.Println("配置文件中不存在port", err)
        return port, flag, tag, err
    }

    flag_temp, err := cfg.GetValue("self", "flag")
    if err != nil {
        fmt.Println("配置文件中不存在flag", err)
        return port, flag, tag, err
    }
    flag, err = strconv.Atoi(flag_temp)
    if err != nil {
        fmt.Println("配置文件中flag類型有誤", err)
        return port, flag, tag, err
    }

    tag_temp, err := cfg.GetValue("self", "tag")
    if err != nil {
        fmt.Println("配置文件中不存在tag", err)
        return port, flag, tag, err
    }
    tag, err = strconv.Atoi(tag_temp)
    if err != nil {
        fmt.Println("配置文件中tag類型有誤", err)
        return port, flag, tag, err
    }

    return port, flag, tag, nil
}
View Code

utils->read_config_json.go //讀取配置文件2

package utils

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "sync"
)

type GlobalConfig struct {
    Database DatabaseConfig `json:"database"`
    Self     SelfConfig     `json:"self"`
}

type DatabaseConfig struct {
    Types  string `json:"types"`
    Local  string `json:"local"`
    Online string `json:"online"`
}

type SelfConfig struct {
    Port string `json:"port"`
    Flag int    `json:"flag"`
    Tag  int    `json:"tag"`
}

var (
    globalconfig *GlobalConfig
    configMux    sync.RWMutex
)

func Config() *GlobalConfig {
    return globalconfig
}

func InitConfigJson(fliepath string) error {
    var config GlobalConfig
    file, err := ioutil.ReadFile(fliepath)
    if err != nil {
        fmt.Println("配置文件讀取錯誤,找不到配置文件", err)
        return err
    }

    if err = json.Unmarshal(file, &config); err != nil {
        fmt.Println("配置文件讀取失敗", err)
        return err
    }

    configMux.Lock()
    globalconfig = &config
    configMux.Unlock()
    return nil
}
View Code

config.ini //配置文件1

#連接數據庫
[database]
types=mysql
local=root:root@tcp(10.9.195.130:3306)/project?parseTime=true
online=root:aaa@tcp(1.1.1:3306)/project?parseTime=true
#監聽端口、**、**
[self]
port=8080
flag=2
tag=2
View Code

config.json //配置文件2

{
    "database":{
        "types":"mysql",
        "local":"root:root@tcp(10.9.195.130:3306)/project?parseTime=true",
        "online":"root:aaa@tcp(1.1.1:3306)/project?parseTime=true"
    },
    "self":{
        "port":"8080",
        "flag":1,
        "tag":1
    }
}
View Code

index.go

package main

import (
    c "project/controller"
    u "project/utils"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    rr := c.GinRouter(r)

    //初始化配置文件
    err := u.InitConfigJson("config.json")
    if err != nil {
        panic(err)
    }

    err = u.GetConfigIni("config.ini")
    if err != nil {
        panic(err)
    }

    // 監聽並在 0.0.0.0:8080 上啟動服務
    rr.Run(":8080")
}
View Code

訪問方式及結果

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM