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

傷城~ 2022-11-05 14:56 355阅读 0赞

起因

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

分析

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

  1. loc, _ := time.LoadLocation("Asia/Chongqing")
  2. 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 download

    FROM build_bash AS server_builder
    COPY . ./
    RUN GOOS=linux GOARCH=amd64 go build -ldflags=”-w -s” -o /go/bin/your_app

    FROM alpine
    RUN apk add tzdata

    自定义运行阶段的命令

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

发表评论

表情:
评论列表 (有 0 条评论,355人围观)

还没有评论,来说两句吧...

相关阅读