From 2fdbdf60d00e2193d90abf5f7f440e7de9edb92f Mon Sep 17 00:00:00 2001 From: iczc Date: Thu, 5 Aug 2021 00:55:27 +0800 Subject: [PATCH] refactor: using Go's embed package --- .dockerignore | 2 ++ Dockerfile | 2 +- internal/server.go | 6 ++++-- web/embed.go | 19 +++++++++++++++++++ 4 files changed, 26 insertions(+), 3 deletions(-) create mode 100644 .dockerignore create mode 100644 web/embed.go diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..cf30e590 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,2 @@ +web/node_modules +web/public/build diff --git a/Dockerfile b/Dockerfile index e95eddbb..5c126176 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,6 +15,7 @@ RUN apk add --no-cache gcc musl-dev linux-headers WORKDIR /backend-build COPY . . +COPY --from=frontend /frontend-build/public ./web/public RUN go build -o eth-faucet -ldflags "-w -s" @@ -23,7 +24,6 @@ FROM alpine RUN apk add --no-cache ca-certificates WORKDIR /app -COPY --from=frontend /frontend-build/public ./web/public COPY --from=backend /backend-build/eth-faucet . EXPOSE 8080 diff --git a/internal/server.go b/internal/server.go index 9b7206db..ab318fc2 100644 --- a/internal/server.go +++ b/internal/server.go @@ -11,6 +11,8 @@ import ( "github.com/julienschmidt/httprouter" log "github.com/sirupsen/logrus" "github.com/urfave/negroni" + + "github.com/chainflag/eth-faucet/web" ) type server struct { @@ -27,11 +29,11 @@ func (s server) Run(port int) { r.HandlerFunc("GET", "/api/info", s.infoHandler) n := negroni.New(negroni.NewRecovery(), negroni.NewLogger()) - n.Use(negroni.NewStatic(http.Dir("web/public"))) + n.Use(negroni.NewStatic(web.Dist())) n.UseHandler(r) log.Infof("Starting http server %d", port) - http.ListenAndServe(":"+strconv.Itoa(port), n) + log.Fatal(http.ListenAndServe(":"+strconv.Itoa(port), n)) } func (s server) claimHandler(w http.ResponseWriter, r *http.Request) { diff --git a/web/embed.go b/web/embed.go new file mode 100644 index 00000000..18f1eeab --- /dev/null +++ b/web/embed.go @@ -0,0 +1,19 @@ +package web + +import ( + "embed" + "io/fs" + "net/http" +) + +//go:embed public +var static embed.FS + +func Dist() http.FileSystem { + fsys, err := fs.Sub(static, "public") + if err != nil { + panic(err) + } + + return http.FS(fsys) +}