[code Chapter] build your own golang framework step by step from scratch

The last article mentioned that the configuration and log have been initialized, and then the database and redis have been initialized.

Initialize database

I choose xorm for database orm. First, add the corresponding database configuration in config.json and config.go.
config.json:

  "db_config": {
    "db_host": "127.0.0.1",
    "db_port": "3306",
    "db_user": "root",
    "db_password": "123456",
    "db_name": "test"
  }

config.go

type DBConfig struct {
    DbHost     string `json:"db_host"`
    DbPort     string `json:"db_port"`
    DbUser     string `json:"db_user"`
    DbPassword string `json:"db_password"`
    DbName     string `json:"db_name"`
}

Next, initialize the database:

package db

import (
    "github.com/TomatoMr/awesomeframework/config"
    _ "github.com/go-sql-driver/mysql"
    "github.com/go-xorm/xorm"
    "github.com/pkg/errors"
)

var engine *xorm.Engine

func InitEngine() error {
    var err error
    conf := config.GetConfig()
    engine, err = xorm.NewEngine("mysql", conf.DBConfig.DbUser+
        ":"+conf.DBConfig.DbPassword+"@tcp("+conf.DBConfig.DbHost+":"+conf.DBConfig.DbPort+")/"+conf.DBConfig.DbName+"?charset=utf8")
    if err != nil {
        err = errors.Wrap(err, "InitEngine1")
        return err
    }
    err = engine.Ping()
    if err != nil {
        err = errors.Wrap(err, "InitEngine2")
        return err
    }
    return nil
}

func GetEngine() *xorm.Engine {
    return engine
}

Let's create another sql to test the connection later:

DROP DATABASE IF EXISTS `test`;
CREATE DATABASE `test`;
USE `test`;
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users`
(
    `id`   int(11)     NOT NULL AUTO_INCREMENT COMMENT 'id',
    `name` varchar(40) NOT NULL COMMENT 'Name',
    `age`  int         NOT NULL DEFAULT 0 COMMENT 'Age',
    PRIMARY KEY (`id`)
) ENGINE = InnoDB COMMENT 'users';

Initialize redis

Also add configuration first:
config.json:

"redis_config": {
    "addr": "127.0.0.1:6379",
    "password": "",
    "db": 0
  }

config.go:

type RedisConfig struct {
    Addr     string `json:"addr"`
    Password string `json:"password"`
    DB       int    `json:"db"`
}

Initialize redis:

func InitRedis() error {
    conf := config.GetConfig()
    client = redis.NewClient(&redis.Options{
        Addr:     conf.RedisConfig.Addr,
        Password: conf.RedisConfig.Password,
        DB:       conf.RedisConfig.DB,
    })

    pong, err := client.Ping().Result()
    if err != nil {
        err = errors.Wrap(err, "InitRedis")
        return err
    }
    logger.GetLogger().Info("Redis ping:", zap.String("ping", pong))
    return nil
}

Adjust entry file

err = db.InitEngine()
    if err != nil {
        fmt.Printf("Init DB failed. Error is %v", err)
        os.Exit(1)
    }

    err = redis.InitRedis()
    if err != nil {
        fmt.Printf("Init Redis failed. Error is %v", err)
        os.Exit(1)
    }

Test it.

Use the above sql to create a database called test, and then build redis. Then we test:

Compile:

go build

Function:

awesomeframework --config=./config/config.json

Look at the log printing:

2020-01-20T20:09:26.798+0800    info    Redis ping: {"ping": "PONG"}
2020-01-20T20:09:26.798+0800    info    Init success.

Summary

This article describes the initialization of database and redis, which can be found in the https://github.com/TomatoMr/awesomeframework Find today's code. To be continued

Welcome to my public address: onepunchgo, leave a message for me.

Keywords: Go JSON Redis Database github

Added by kendallkamikaze on Wed, 22 Jan 2020 17:44:42 +0200