一起使用GO(golang) 來做一個後臺管理系統系列(4) 基礎包管理,包括數據庫訪問,配置文件管理

有童鞋反應說讓把,基礎配置部分,包括數據庫訪問,和配置部分也貼出了。

這裏插入一篇文件,單獨做個介紹

首先在主工程目錄創建conf 和db 兩個配置包如圖:

其中app.ini 包含的時候此工程的運行配置,包含端口號,數據庫,redis緩存等等。

這個後面會根據業務的需求,添加不同的配置信息。

創建app.ini

[http]
port = ":8888"

[mongo]
url = "127.0.0.1:27017"
db = "mycol"
username = "testname"
password = "testname"

[redis]
url = "127.0.0.1:6379"

在db包內創建

mgo.go 訪問mongodb的。

package db

import (
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"myProject/myProjectUtils"
	"time"
)

const dbName = "mycol"

/* mongodb */
//func InitMongoDB() (collection *mongo.Database) {
//	if mgo == nil {
//		mgo = connectDB()
//	}
//	return mgo
//}
/* mongodb */
func InitMongoDB2() (collection *mongo.Database) {
	if mgo == nil {
		mgo = connectDB()
	}
	return mgo
}

var mgo *mongo.Database

func connectDB() (collection *mongo.Database) {
	//var url = myProjectUtils.GetConf("mongo", "url")
	//opts := options.ClientOptions{
	//	Hosts: []string{url}
	//}

	config := myProjectUtils.GetConfInfo("mongo")

	opts := options.ClientOptions{Hosts: []string{config.Key("url").String()}}
	credential := options.Credential{
		Username: config.Key("username").String(), Password: config.Key("password").String(),
		AuthSource: config.Key("db").String(),
	}
	opts.Auth = &credential

	client, err := mongo.NewClient(&opts)
	if err != nil {
		panic(err)
		return nil
	}
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	err = client.Connect(ctx)
	if err != nil {
		return nil
	}
	var dbName = myProjectUtils.GetConf("mongo", "db")
	collection = client.Database(dbName)
	return collection
}

/* mongodb table Name */
const (
	User  string = "user"
	Role  string = "role"
	Test  string = "test"
	Test1 string = "test1"
	Test2 string = "test2"
)

創建mysql.go 

package db

import (
	"database/sql"
	"fmt"
)

const (
	DB_Driver = "root:root@tcp(localhost:3306)/hcydb?charset=utf8"
)

func openDB() (success bool, db *sql.DB) {
	var isOpen bool
	db, err := sql.Open("mysql", DB_Driver)
	if err != nil {
		isOpen = false
	} else {
		isOpen = true
	}
	CheckErr(err)
	return isOpen, db
}

var mysqlDB *sql.DB

func InitMysqlDb() *sql.DB {
	if mysqlDB == nil {
		result, DB := openDB()
		if result {
			mysqlDB = DB
		}
	}
	return mysqlDB
}

func CheckErr(err error) {
	if err != nil {
		fmt.Println("err:", err)
	}
}

基本的配置加載就說這麼多了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章