当前位置: 代码迷 >> 综合 >> panic: time: missing Location in call to Time.In
  详细解决方案

panic: time: missing Location in call to Time.In

热度:42   发布时间:2024-01-05 08:54:23.0

起因

在处理与时间验证相关的代码时,特意指定了time的location, 在本地运行通过,放到某个docker容器中直接报:panic: time: missing Location in call to Time.In错误

分析

主要代码
省去业务相关代码,只保留最关键的一个

loc, _ := time.LoadLocation("Asia/Chongqing")
return time.Now().In(loc)

官方文档
// 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.

时间的位置信息是从本地文件系统中提取的,大多数系统都支持它,但还是取决于当前系统。具体的配置存储路径:

$ cd /usr/share/zoneinfo

进入该目录就可以看到各时区的配置信息

解决办法

  1. 在base 容器中添加上相关时区信息
    示例 Dockerfile
FROM golang:1.12-alpine as build_base
RUN apk add --update bash make git
WORKDIR /go/src/github.com/your_repo/your_app/
ENv GO111MODULE on
COPY go.mod .
COPY go.sum .
RUN go mod downloadFROM build_bash AS server_builder
COPY . ./
RUN GOOS=linux GOARCH=amd64 go build -ldflags="-w -s" -o /go/bin/your_appFROM alpine
RUN apk add tzdata# 自定义运行阶段的命令

最主要的就是增加了RUN apk add tzdata 这条命令

  相关解决方案