检测ZONEINFO在Go中是否失败 [英] Detect if ZONEINFO fails in Go

查看:69
本文介绍了检测ZONEINFO在Go中是否失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中,您可以通过添加ZONEINFO环境变量来指定要使用的特定zoneinfo.zip文件,该变量指向要用于时区信息的特定文件.这很棒,因为它可以确保前端和后端使用的IANA时区数据库的版本相同.

In Go, you can specify a specific zoneinfo.zip file to be used by adding a ZONEINFO environment variable that points to the specific file you'd like to use for time zone information. This is great as it allows me to ensure that the versions of the IANA time zone database that I'm using on my front-end and my back-end are the same.

但是,似乎没有任何方法可以检测对指定区域信息文件的使用是否失败.查看源代码( https://golang.org/src/time/zoneinfo.go ),看起来使用指定文件的任何错误都会悄然失败,然后go将继续检查默认的操作系统位置或默认的$ GOROOT位置,以从那里获取时区信息.这不是我想要的行为,因为我肯定会知道我正在使用指定版本的区域信息.

However, there does not appear to be any way to detect if use of the specified zone info file has failed. Looking at the source code (https://golang.org/src/time/zoneinfo.go), it looks like any errors using the specified file will fail quietly and then go will proceed to check for default OS locations or the default $GOROOT location to pull time zone information from there. This is not the behavior that I would prefer as I would like to know with certainty that I am using my specified version of zone info.

我从解决方案的角度考虑了以下内容,但我对其中的任何一个都不满意.

I've thought of the following in terms of solutions, but I'm not happy with any of them.

  1. 我可以检查自己设置的环境变量,但这充其量只能作为部分解决方案,因为它不会告诉我LoadLocation是否确实可以使用该文件.
  2. 我可以确保不存在区域信息的备份位置.这似乎有点极端,这意味着我必须非常注意在开发和生产设置中运行代码的环境.

有人知道一种更优雅的方式来确保我使用的是我的ZONEINFO环境变量指定的zoneinfo.zip文件吗?

Does anyone know of a more elegant way to ensure that I am using the zoneinfo.zip file specified by my ZONEINFO environment variable?

更新:要解决此问题,我也从@chuckx的解答中得到启发,并将一个Go程序包,该程序可以从正在使用的时区数据库中进行猜测.自述文件中包含有关如何使用Go安装获取正确版本的时区数据库的说明.

Update: To address this problem I too inspiration from @chuckx's answer below and put together a Go package that takes the guess work out of which time zone database is being used. Included in the readme are instructions on how to get the correct version of the time zone database using a Go installation.

推荐答案

也许考虑不依赖环境变量?

Maybe consider not relying on the environment variable?

如果您不反对分发解压缩的文件集,则可以轻松使用 LoadLocationFromTZData(名称字符串,数据[] byte) .第二个参数是单个时区文件的内容.

If you're not averse to distributing the unzipped fileset, you can easily use LoadLocationFromTZData(name string, data []byte). The second argument is the contents of an individual timezone file.

作为参考,可在未导出的函数 loadTzinfoFromZip() .

For reference, the functionality for processing a zip file is found in the unexported function loadTzinfoFromZip().

从@Slotherooo的评论中提取的逐步方法:

Step-by-step approach extracted from @Slotherooo's comment:

  1. 制作 time.loadTzinfoFromZip(zipfile,name string)([] byte,error)
  2. 使用该方法从 timeinfo.zip 文件
  3. 中提取所需位置的 [] byte
  4. 仅使用 time.LoadLocationFromTZData() time.LoadLocation

这篇关于检测ZONEINFO在Go中是否失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆