go 连接mysql 的时间参数loc, parseTime | 青训营笔记

669 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 16 天

ParseTime

Type:           bool
Valid Values:   true, false
Default:        false

如果配置了parseTime=true,MySQL中的DATE、DATETIME等时间类型字段将自动转换为golang中的time.Time类型。 类似的0000-00-00 00:00:00 ,会被转为time.Time的零值。

否则,如果没有配置或配置了parseTime=false, 只会转为 []byte / string 。

loc

Type:           string
Valid Values:   <escaped name>
Default:        UTC

设置转换为 time.Time 类型时, 使用的时区信息 (当设置parseTime=true)。 默认值 UTC,表示解析为UTC时间。 一般设置为Local,表示使用当地时间。

这个设置只表示解析为time.Time类型时,使用的配置。并不改变MySQL的time zone时区信息time_zone setting。

如果需要在连接参数DSN中做这个配置,可参考time_zone system variable。

本人青训项目后端举例:

config.go:

package config

import (
	"fmt"
	"log"
	"strings"

	"github.com/BurntSushi/toml"
)

type Mysql struct {
	Host      string
	Port      int
	Database  string
	Username  string
	Password  string
	Charset   string
	ParseTime bool `toml:"parse_time"`
	Loc       string
}

type Redis struct {
	IP       string
	Port     int
	Database int
}

type Server struct {
	IP   string
	Port int
}

type Path struct {
	FfmpegPath       string `toml:"ffmpeg_path"`
	StaticSourcePath string `toml:"static_source_path"`
}

type Config struct {
	DB     Mysql `toml:"mysql"`
	RDB    Redis `toml:"redis"`
	Server `toml:"server"`
	Path   `toml:"path"`
}

var Info Config

// 包初始化加载时候会调用的函数
func init() {  
	// DecodeFile读取 toml的配置文件
	if _, err := toml.DecodeFile("D:\\tiktok\\dousheng\\config\\config.toml", &Info); err != nil {  
		panic(err)
	}
	//去除左右的空格
	strings.Trim(Info.Server.IP, " ")
	strings.Trim(Info.RDB.IP, " ")
	strings.Trim(Info.DB.Host, " ")
}

// DBConnectString 填充得到数据库连接字符串
func DBConnectString() string {
	arg := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=%v&loc=%s",
		Info.DB.Username, Info.DB.Password, Info.DB.Host, Info.DB.Port, Info.DB.Database,
		Info.DB.Charset, Info.DB.ParseTime, Info.DB.Loc)
	log.Println(arg)
	return arg
}

toml文件的配置

#关系型数据库配置
[mysql]
host = "127.0.0.1"
port = 3306
database = "douyin"
username = "root"
password = "369258147lht"
charset = "utf8mb4"
parse_time = true
loc = "Local"

#nosql配置 用于存储每个用户是否队某个视频点赞 以及关注了某个人(前端反馈情况  比如点赞 变红心)
[redis]
host = "127.0.0.1"
port = 6379
database = 0

#记录当前服务器ip和启动端口号 当前服务器ip用于生成对应的视频链接地址
[server]
ip = "192.168.1.103"
port = 8080

#用于保存资源的路径,用于截图工具的路径 截图工具放在lib目录
[path]
ffmpeg_path = "D:\\tiktok\\dousheng\\lib\\ffmpeg.exe"
static_source_path = "D:\\tiktok\\dousheng\\static"

参考引用:blog.csdn.net/lanyang1234…