公司的项目一般都是这种,然后config是接收配置文件,custom的ini文件是配置文件,config如下`
package config
import (
"fmt"
"os"
"github.com/tobyzxj/uuid"
"github.com/unknwon/com"
"gopkg.in/ini.v1"
)
type Config struct {
AppName string `ini:"name"` // app name
UUID string `ini:"-"` // app 每次启动都会创建一个唯一的uuid
Env string `ini:"env"` // development or production
Server Server `ini:"server"` // http server listen port
Log Logs `ini:"logs"` // log
TimeZone TimeZone `ini:"time"` // time zone info
JWT JWT `ini:"jwt"` // jwt
Test Database `ini:"test"` // main db info
Redis Redis `ini:"redis"` // redis
}
type Server struct {
Domain string `ini:"domain"`
Addr string `ini:"addr"`
Port string `ini:"port"`
}
// JWT jwt 接口信息配置
type JWT struct {
Issuer string `ini:"issuer"`
Subject string `ini:"subject"`
Audience string `ini:"audience"`
ExpirationTime int `ini:"expiration_time"`
}
type Logs struct {
MaxLines string `ini:"maxlines"`
MaxSize string `ini:"maxsize"`
Daily bool `ini:"daily"`
MaxDays string `ini:"maxdays"`
Rotate bool `ini:"rotate"`
Level string `ini:"level"`
}
type TimeZone struct {
TimeStandard string `ini:"time_standard"`
TimeZone string `ini:"time_zone"`
}
type Database struct {
Url string `ini:"url"`
Username string `ini:"username"`
Password string `ini:"password"`
TableName string `ini:"tbname"`
}
type Redis struct {
Host string `ini:"host"`
Db string `ini:"db"`
MaxIdle int `ini:"maxidle"`
MaxActive int `ini:"maxactive"`
IdleTimeOut int `ini:"idletimeout"`
Password string `ini:"password"`
Twemproxy bool `ini:"twemproxy"`
}
var GCfg Config
var debug_enable bool
func init() {
debug_enable = true
}
func Load() error {
fmt.Println("Load app configure ...")
var conf *ini.File
// check whether custom/app.ini exists
if com.IsExist("custom/app.ini") {
fmt.Println("Found custom/app.ini")
cfg, err := ini.Load("custom/app.ini")
if err != nil {
fmt.Println("Loading custom/app.ini error", err)
os.Exit(0)
}
conf = cfg
} else {
// load default config file
cfg, err := ini.Load("config/app/app.ini")
if err != nil {
fmt.Println("Loading app.ini error", err)
os.Exit(0)
}
conf = cfg
}
err := conf.MapTo(&GCfg)
if err != nil {
fmt.Println("app.ini format error", err)
os.Exit(0)
}
// debug
if debug_enable {
GCfg.debug()
}
GCfg.UUID = uuid.New()
return nil
}
func Debug(enable bool) {
if enable {
debug_enable = true
return
}
debug_enable = false
}
func (c *Config) debug() {
fmt.Println("Name:", c.AppName)
fmt.Println("Env:", c.Env)
fmt.Println("Test.Url:", c.Test.Url)
fmt.Println("Test.Username:", c.Test.Username)
fmt.Println("Test.Password:", c.Test.Password)
fmt.Println("Test.TableName:", c.Test.TableName)
fmt.Println("Redis.IdleTimeOut:", c.Redis.IdleTimeOut)
fmt.Println("Redis.MaxActive:", c.Redis.MaxActive)
fmt.Println("Redis.MaxIdle:", c.Redis.MaxIdle)
fmt.Println("Redis.RedisDb:", c.Redis.Db)
fmt.Println("Redis.RedisHost:", c.Redis.Host)
fmt.Println("Redis.Password:", c.Redis.Password)
fmt.Println("Redis.Twemproxy:", c.Redis.Twemproxy)
fmt.Println("JWT.Issuer:", c.JWT.Issuer)
fmt.Println("JWT.Subject:", c.JWT.Subject)
fmt.Println("JWT.Audience:", c.JWT.Audience)
fmt.Println("JWT.ExpirationTime:", c.JWT.ExpirationTime)
}
首先我们需要在出事这些连接,包括MySQL,这是文件main
package main
import (
"hello/config"
"hello/log"
"hello/models"
"hello/web"
"os"
)
func main() {
// Load configure
// Must Call before log.Init()
config.Load()
log.Init()
// Test for log module
log.GLog.Info("Starting App --> %s ...", config.GCfg.AppName)
// Init databse
err := models.InitDB()
if err != nil {
log.GLog.Error("Init db failed, err: %s", err)
os.Exit(0)
}
// Init Redis
models.InitRedis(
config.GCfg.Redis.Host,
config.GCfg.Redis.Db,
config.GCfg.Redis.Password,
config.GCfg.Redis.MaxIdle,
config.GCfg.Redis.MaxActive,
config.GCfg.Redis.IdleTimeOut,
config.GCfg.Redis.Twemproxy)
// Start beego
web.BeegoRun()
}
连接MySQL文件
package models
import (
"errors"
"fmt"
"hello/config"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
// _ "github.com/lib/pq"
"net/url"
_"time"
)
// InitDatabase Mysql init
func InitDatabase(url, username, password, dbname, timezone string, name string) error {
dsn := username + ":" + password + "@(" + url + ")/" + dbname + "?charset=utf8" + timezone
err := orm.RegisterDataBase(name, "mysql", dsn)
return err
}
// InitDB database init
func InitDB() error {
var err error
var errStr string
fmt.Println(config.GCfg.Test.Url,config.GCfg.Test.Username,
config.GCfg.Test.Password,
config.GCfg.Test.TableName)
// load dcgc mysql database
err = InitDatabase(
config.GCfg.Test.Url,
config.GCfg.Test.Username,
config.GCfg.Test.Password,
config.GCfg.Test.TableName,
"&loc="+url.QueryEscape(config.GCfg.TimeZone.TimeZone),
"default")
if err != nil {
errStr = errStr + fmt.Sprintf("models dcgcdb init failed, %s.", err)
}
if errStr != "" {
return errors.New(errStr)
}
return nil
}
使用MySQL的时候直接在各个表下面使用orm就可以操作数据库了如下
package models
import (
"github.com/astaxie/beego/orm"
)
type User struct {
ID int64 `orm:"column(id);pk;auto"`
Username string `orm:"column(username);size(32);unique"` // 用户名
Password string `orm:"column(password);size(64)"` // 加密后的密码
}
func GetUserByAccessID(accessID string) (v *User, err error) {
o := orm.NewOrm()
if err = o.Read(v, "access_id"); err == nil {
return v, nil
}
return nil, err
}
连接Redis
package models
import (
"github.com/gomodule/redigo/redis"
// "github.com/astaxie/beego/cache/redis"
"hello/log"
"time"
)
var (
// 定义常量
rc *redis.Pool
)
// InitRedis init redis client
func InitRedis(host, db, password string, maxIdle, maxActive, idleTimeout int, twemproxy bool) {
// 建立连接池
rc = &redis.Pool{
MaxIdle: maxIdle,
MaxActive: maxActive,
IdleTimeout: time.Duration(idleTimeout) * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", host)
if err != nil {
log.GLog.Error("[Redis] tcp dial err, %s", err)
return nil, err
}
if !twemproxy {
// 选择db
if password != "" {
c.Do("auth", password)
}
if db != "0" {
c.Do("SELECT", db)
}
}
return c, nil
},
}
}
// RedisCacheSet SET key value
// 将字符串值 value 关联到 key 。
// 如果 key 已经持有其他值, SET 就覆写旧值,无视类型。
func RedisCacheSet(key string, value interface{}) error {
redisConnect := rc.Get()
defer redisConnect.Close()
_, err := redisConnect.Do("SET", key, value) // 获取redis中key对应的值
return err
}
// RedisGetBytes GET key
// 返回 key 所关联的字符串值。
// 如果 key 不存在那么返回特殊值 nil 。
func RedisGetBytes(key string) (value []byte, err error) {
redisConnect := rc.Get()
defer redisConnect.Close()
value, err = redis.Bytes(redisConnect.Do("GET", key)) // 获取redis中key对应的值
return
}