在Docker构建期间无法`获取`依赖项

I'm fairly new to both Docker and go, so this might be something obvious, but my google searches haven't found anything.

I'm trying to build a simple go program with docker, but I'm havign trouble with dependencies.

go file:

package main

import (
    "fmt"
    "log"
    "html"
    "net/http"

    "github.com/gorilla/mux"
)

func hello(writer http.ResponseWriter, r *http.Request) {
    path := mux.Vars(r)["rest"]
    fmt.Fprintf(writer, "Hello, %q", html.EscapeString(path))
}

func main() {
    router := mux.NewRouter().StrictSlash(true)

    router.HandleFunc("/{rest:.*}", hello)

    log.Println("Listening...")
    log.Fatal(http.ListenAndServe(":8080", router))
}

Docker file:

FROM golang:latest
RUN mkdir /app
ADD ./HelloWorld.go /app/
WORKDIR /app
RUN go get ./*.go
RUN go build -o main .
CMD ["/app/main"]

Error:

Sending build context to Docker daemon  6.482MB
Step 1/7 : FROM golang:latest
 ---> 138bd936fa29
...
Step 5/7 : RUN go get ./*.go
 ---> Running in 1e29844961a2
HelloWorld.go:9:5: cannot find package "github.com/gorilla/mux" in any of:
        /usr/local/go/src/github.com/gorilla/mux (from $GOROOT)
        /go/src/github.com/gorilla/mux (from $GOPATH)
The command '/bin/sh -c go get ./*.go' returned a non-zero code: 1

You may use my Dockerfile as a base. First stage produces working image. That’s enough for many cases. https://github.com/lisitsky/go-site-search-string/blob/light-docker/Dockerfile

If you want to shrink image size from ~800MB to about ~10-20MB use second stage too.

Just use $GOPATH everywhere in your path to build your images, e.g. $GOPATH/src/app instead of /app

Full example of multistage build:

FROM golang:alpine as builder

RUN apk add --update git

RUN mkdir -p $GOPATH/src/build

ADD . $GOPATH/src/build/

WORKDIR $GOPATH/src/build

RUN go get ./...

RUN go build -o main .

FROM alpine

RUN adduser -S -D -H -h /app appuser

USER appuser

COPY --from=builder /go/src/build/main /app/

WORKDIR /app

CMD ["./main"]