I have the following directory structure:
templates/
a.tmpl
services/
service.go
main.go
Now inside the service.go
file i am calling the below function:
dir, err := filepath.Abs(filepath.Dir("./templates/"))
if err != nil {
return nil, err
}
baseFile := filepath.Join(dir, "a.tmpl")
tmpl, err := template.New("base").ParseFiles(baseFile)
now the above function is parsing my a.tmpl
file as expected.
but once this service is up on docker and kubernetes, i am no longer able to open the file since the file does not exists
why is that?
UPDATE:
FROM golang:1.16-buster AS builder
# Copy the code from the host and compile it
WORKDIR $GOPATH/src/github.com/me/report
COPY . ./
# pack templates to binary
RUN CGO_ENABLED=0 GOOS=linux go build -mod vendor -ldflags "-X github.com/me/report/cmd.version=$(cat .VERSION)" -o /app .
FROM xyz.amazonaws.com/common/platform/base:latest as prod
COPY --from=builder /app ./
ADD ./migrations /migrations
ENTRYPOINT ["/app"]
2
Answers
When you build your binary, go only includes the necessary go files to have your program work. It does not know that your
templates
directory is necessary to the running of the program.There is several solutions to your problem :
templates
directory into your binary using the embed package so that you can access the files at runtimeJust copy the templates folder from the builder, like:
or add the folder like: