skip to Main Content

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


  1. 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 :

    • Create an environment variable pointing to were the templates are and use it on runtime.
    • Embed the templates directory into your binary using the embed package so that you can access the files at runtime
    Login or Signup to reply.
  2. Just copy the templates folder from the builder, like:

    COPY --from=builder /app ./
    ADD ./migrations /migrations
    COPY --from=builder ./templates /templates
    
    

    or add the folder like:

    COPY --from=builder /app ./
    ADD ./migrations /migrations
    ADD ./templates /templates
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search