Настройка приложения модулей go, ориентированных на пакетное проектирование

#docker #go #module #package

#docker #Вперед #модуль #пакет

Вопрос:

Я нахожусь в процессе тестирования модулей go в режиме пакетного проектирования, как описано здесь, чтобы можно было «настроить» несколько исполняемых сервисов, но я изо всех сил пытаюсь правильно подключить все в одном репозитории. Я не могу получить успешное изображение docker, созданное с использованием этого подхода. Большинство примеров в Интернете ориентированы на одномодульный подход, где main.go и dockerfile находятся в корневой папке.

Моя структура каталогов выглядит следующим образом project1 — api — build — service1 — dockerfile — service2 — dockerfile — cmd — service1 — main.go — service2 — main.go — deployments — docs — internal — third_party — go.mod — go.sum — Makefile — vendor

 # Accept the Go version for the image to be set as a build argument.
# Default to Go 1.11
ARG GO_VERSION=1.11

# First stage: build the executable.
FROM golang:${GO_VERSION}-alpine AS builder

# Create the user and group files that will be used in the running container to
# run the process as an unprivileged user.
RUN mkdir /user amp;amp; 
    echo 'nobody:x:65534:65534:nobody:/:' > /user/passwd amp;amp; 
    echo 'nobody:x:65534:' > /user/group

# Install the Certificate-Authority certificates for the service1 to be able to make
# calls to HTTPS endpoints.
RUN apk add --no-cache ca-certificates

# Set the environment variables for the go command:
# * CGO_ENABLED=0 to build a statically-linked executable
# * GOFLAGS=-mod=vendor to force `go build` to look into the `/vendor` folder.
ENV CGO_ENABLED=0 GOFLAGS=-mod=vendor

# Set the working directory outside $GOPATH to enable the support for modules.
WORKDIR /src

# Import the code from the context.
COPY ./ ./

# Build the executable to `/service1`. Mark the build as statically linked.
RUN go build 
    -installsuffix 'static' 
    -o /service1 .

# Final stage: the running container.
FROM scratch AS final

# Import the user and group files from the first stage.
COPY --from=builder /user/group /user/passwd /etc/

# Import the Certificate-Authority certificates for enabling HTTPS.
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

# Import the compiled executable from the second stage.
COPY --from=builder /service1 /service1

EXPOSE 8080

# # Run the compiled binary.
ENTRYPOINT ["/service1"]

  

Когда я запускаю a docker build -t service1:v0.0.1 . , я получаю эту ошибку для всех моих зависимостей

  /go/src/github.com/.../project1/internal/pkg/common (from $GOPATH)
main.go:15:2: cannot find package "github.com/.../project1/internal/pkg/delegates" in any of:
        /usr/local/go/src/github.com/.../project1/internal/pkg/delegates (from $GOROOT)
        /go/src/github.com/.../project1/internal/pkg/delegates (from $GOPATH)
main.go:16:2: cannot find package "github.com/.../project1/internal/pkg/secure" in any of:
        /usr/local/go/src/github.com/.../project1/internal/pkg/secure (from $GOROOT)
        /go/src/github.com/.../project1/internal/pkg/secure (from $GOPATH)
main.go:17:2: cannot find package "github.com/.../project1/statik" in any of:
        /usr/local/go/src/github.com/.../project1/statik (from $GOROOT)
        /go/src/github.com/.../project1/statik (from $GOPATH)
main.go:18:2: cannot find package "github.com/grpc-ecosystem/grpc-gateway/runtime" in any of:
        /usr/local/go/src/github.com/grpc-ecosystem/grpc-gateway/runtime (from $GOROOT)
        /go/src/github.com/grpc-ecosystem/grpc-gateway/runtime (from $GOPATH)
main.go:19:2: cannot find package "github.com/heptiolabs/healthcheck" in any of:
        /usr/local/go/src/github.com/heptiolabs/healthcheck (from $GOROOT)
        /go/src/github.com/heptiolabs/healthcheck (from $GOPATH)
main.go:21:2: cannot find package "github.com/rakyll/statik/fs" in any of:
        /usr/local/go/src/github.com/rakyll/statik/fs (from $GOROOT)
        /go/src/github.com/rakyll/statik/fs (from $GOPATH)
main.go:22:2: cannot find package "github.com/sirupsen/logrus" in any of:
        /usr/local/go/src/github.com/sirupsen/logrus (from $GOROOT)
        /go/src/github.com/sirupsen/logrus (from $GOPATH)
main.go:23:2: cannot find package "google.golang.org/grpc" in any of:
        /usr/local/go/src/google.golang.org/grpc (from $GOROOT)
        /go/src/google.golang.org/grpc (from $GOPATH)

  

По сути, он не может найти все зависимости…

Ответ №1:

Похоже, что вы создаете проект без включенных экспериментальных модулей, находясь вне GOPATH.

Попробуйте скопировать свои исходные /go/src/github.com/your-name/project1 тексты и создать проект там.

Ответ №2:

Тот факт, на который ссылается сообщение об ошибке GOPATH , указывает на то, что go команда не выполняется в режиме модуля.

Наиболее вероятными причинами этого являются отсутствующий go.mod файл или рабочий каталог внутри $GOPATH/src . (Я заметил, что вы явно меняете рабочий каталог на /src , но если $GOPATH равно / , это все равно не активирует режим модуля.)

Попробуйте добавить GO111MODULE=on в среду. (Это должно, по крайней мере, решить непосредственную проблему, но может выявить некоторые новые.)