First we need to install Gorm this open source ORM library and mysql driver

go get -u gorm.io/gorm

go get -u gorm.io/driver/mysql
Copy the code

Open the internal new database folder and create database.go

package database

import (
  "fmt"
  "go-blog-server/global"
  "go-blog-server/pkg/setting"
  "gorm.io/driver/mysql"
  "gorm.io/gorm"
  "gorm.io/gorm/logger"
  "log"
  "os"
  "time"
)

func NewDBEngine(databaseSetting *setting.DatabaseSettings) (*gorm.DB, error) {
  newLogger := logger.New(
    log.New(os.Stdout, "\r\n", log.LstdFlags), // IO writer (log output object, prefix, and log content)
    logger.Config{
      SlowThreshold:             time.Second,   // Slow SQL threshold
      LogLevel:                  logger.Silent, // Log level
      IgnoreRecordNotFoundError: true.// Ignore the ErrRecordNotFound error
      Colorful:                  false.// Disable color printing
    },
  )

  dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s? charset=%s&parseTime=%t&loc=Local",
    databaseSetting.UserName, databaseSetting.Password, databaseSetting.Host, databaseSetting.DBName, databaseSetting.Charset, databaseSetting.ParseTime,
  )

  dbConfig := &gorm.Config{}

  if global.ServerSetting.RunMode == "debug" {
    dbConfig = &gorm.Config{Logger: newLogger}
  }
  db, err := gorm.Open(mysql.Open(dsn), dbConfig)
  iferr ! =nil {
    return nil, err
  }

  sqlDB, err := db.DB()
  iferr ! =nil {
    return nil, err
  }

  sqlDB.SetMaxIdleConns(databaseSetting.MaxIdleConns)
  sqlDB.SetMaxOpenConns(databaseSetting.MaxOpenConns)

  return db, nil
}
Copy the code

Our DB instance should be globally accessible

Add db.go to the gobla folder under the project directory

package global

import "gorm.io/gorm"

var (
  DBEngine *gorm.DB
)
Copy the code

New setupDBEngine method in main.go and call it in init function.

package main

import (
  "fmt"
  "go-blog-server/global"
  "go-blog-server/internal/database"
  "go-blog-server/internal/routers"
  "go-blog-server/pkg/setting"
  "log"
  "net/http"
  "time"
)

func init(a) {
  err := setupSetting()
  iferr ! =nil {
    log.Fatalf("init setupSetting Error : %v", err)
  }
  err = setupDBEngine()
  iferr ! =nil {
    log.Fatalf("init setupSetting Error : %v", err)
  }
}

func main(a) {
  // Instantiate the route handler
  router := routers.NewRouter()
  // Customize the HTTP Server
  s := &http.Server{
    // Set the listening port
    Addr: ":" + global.ServerSetting.HttpPort,
    // Add the handler we wrote
    Handler: router,
    // Sets the maximum time allowed to read and write
    ReadTimeout:  global.ServerSetting.ReadTimeout,
    WriteTimeout: global.ServerSetting.WriteTimeout,
    // set the maximum number of bytes in the request header to 2^20bytes 1Mb
    MaxHeaderBytes: 1 << 20,
  }
  err := s.ListenAndServe()
  iferr ! =nil {
    fmt.Println(err)
  }
}

//setupSetting
func setupSetting(a) error {
  mySetting, err := setting.NewSetting()
  iferr ! =nil {
    return err
  }
  err = mySetting.ReadSection("Server", &global.ServerSetting)
  iferr ! =nil {
    return err
  }
  err = mySetting.ReadSection("App", &global.AppSetting)
  iferr ! =nil {
    return err
  }
  err = mySetting.ReadSection("Database", &global.DatabaseSetting)
  iferr ! =nil {
    return err
  }

  // Set the data to seconds
  global.ServerSetting.ReadTimeout *= time.Second
  global.ServerSetting.WriteTimeout *= time.Second

  return nil
}

func setupDBEngine(a) error {
  var err error
  global.DBEngine, err = database.NewDBEngine(global.DatabaseSetting)
  iferr ! =nil {
    return err
  }
  return nil
}
Copy the code

Note that starting Mysql in phpStudy and running the main.go console all works if the connection to the database is successful.