如果在win上没有安装go开发环境,正好go程序又用到时区,会报以下错误
[ORM]2019/09/25 17:36:37 register db Ping `default`, open C:\Go/lib/time/zoneinfo.zip: The system cannot find the file specified.
这个问题如何解决呢?
go是开源的,没看到你这问题,我都没仔细想过,不过花了几分钟看下源码发现下面就可以满足你的要求
你可以在代码里面设置环境变量,也可以手动设置环境变量再执行你的程序
```go
package main
import (
"fmt"
"log"
"syscall"
"time"
)
func main() {
err := syscall.Setenv("ZONEINFO", `C:\zoneinfo.zip`)
if err != nil {
log.Fatal(err)
}
fmt.Println(time.LoadLocation("Europe/Berlin"))
}
```
定位源码如下位置,稍微研究一下就懂了:
```go
// LoadLocation returns the Location with the given name.
//
// If the name is "" or "UTC", LoadLocation returns UTC.
// If the name is "Local", LoadLocation returns Local.
//
// Otherwise, the name is taken to be a location name corresponding to a file
// in the IANA Time Zone database, such as "America/New_York".
//
// The time zone database needed by LoadLocation may not be
// present on all systems, especially non-Unix systems.
// LoadLocation looks in the directory or uncompressed zip file
// named by the ZONEINFO environment variable, if any, then looks in
// known installation locations on Unix systems,
// and finally looks in $GOROOT/lib/time/zoneinfo.zip.
func LoadLocation(name string) (*Location, error) {
if name == "" || name == "UTC" {
return UTC, nil
}
if name == "Local" {
return Local, nil
}
if containsDotDot(name) || name[0] == '/' || name[0] == '\\' {
// No valid IANA Time Zone name contains a single dot,
// much less dot dot. Likewise, none begin with a slash.
return nil, errLocation
}
zoneinfoOnce.Do(func() {
env, _ := syscall.Getenv("ZONEINFO")
zoneinfo = &env
})
var firstErr error
if *zoneinfo != "" {
if zoneData, err := loadTzinfoFromDirOrZip(*zoneinfo, name); err == nil {
if z, err := LoadLocationFromTZData(name, zoneData); err == nil {
return z, nil
}
firstErr = err
} else if err != syscall.ENOENT {
firstErr = err
}
}
if z, err := loadLocation(name, zoneSources); err == nil {
return z, nil
} else if firstErr == nil {
firstErr = err
}
return nil, firstErr
}
```
#5
更多评论