首先记录一下如何定时刷新token,并更新配置文件
目的是定时更新Token,并写入配置文件
type Config struct {
APP_ID string `mapstructure:"APP_ID"`
APP_SECRET string `mapstructure:"APP_SECRET"`
Weathe_Key string `mapstructure:"Weathe_Key"`
Weathe_Location string `mapstructure:"Weathe_Location"`
AccessToken string `mapstructure:"AccessToken"`
Baidu_APPID string `mapstructure:"Baidu_APPID"`
Baidu_SECRET string `mapstructure:"Baidu_SECRET"`
}
{
//首先使用viper读取conf路径下的配置文件,然后返回到Config结构体
config, err := conf.LoadConfig("./conf/")
if err != nil {
log.Fatal("读取微信配置时出错,错误为: ", err)
}
//如果想要更新config配置文件
//使用Viper.set()方法更新值
viper.Set("AccessToken", config.AccessToken)
//最后使用Viper.WriteConfig()方法来更新配置文件
err = viper.WriteConfig()
if err != nil {
log.Println("写入配置文件失败", err)
return err
}
}
下面是定时刷新token的操作,打开一个goroutine来定时刷新
func RefreshToken() {
if token.Access_Token == "" {
fmt.Println("token为空")
//刷新Token操作
token = getToken()
}
//设置时间为半小时
interval := 90 * time.Minute
//创建一个定时任务
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
//发送请求获取最新token
token = getToken()
}
}
}
然后是一些文件操作
如何在文件和字节流间转换
func writeFile(){
//打开图像文件,返回一个*os.File类型
file, errFile1 := os.Open("./image/image.jpg")
if errFile1 != nil {
fmt.Println("打开文件错误", errFile1)
return ""
}
//打开文件后一定要记得关闭
defer file.Close()
//将*os.File类型读出转换成[]byte
data, _ :=io.ReadAll(file)
//如果前端body传入图片字节data2,要保存至文件
//创建文件image2
image, _ := os.Create("image.jpg")
defer file2.Close()
//将前端字节流写入文件image.jpg中
file2.Write(data2)
}