From 884ad3efb311a5b99017f8d671d660360ae81a28 Mon Sep 17 00:00:00 2001 From: Joshua Taylor Date: Thu, 6 Apr 2023 12:42:29 -0500 Subject: [PATCH] Switch to embedding all files --- Dockerfile | 4 ---- web.go | 46 ++++++++++++++++++++++------------------------ 2 files changed, 22 insertions(+), 28 deletions(-) diff --git a/Dockerfile b/Dockerfile index bf12f4f..515f3e4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,10 +10,6 @@ FROM alpine WORKDIR /cfwidget COPY --from=builder /go/bin/cfwidget /go/bin/cfwidget -COPY --from=builder /cfwidget/favicon.ico /cfwidget/favicon.ico -COPY --from=builder /cfwidget/css /cfwidget/css -COPY --from=builder /cfwidget/js /cfwidget/js -COPY --from=builder /cfwidget/templates /cfwidget/templates EXPOSE 8080 diff --git a/web.go b/web.go index 7f33921..a95fdbe 100644 --- a/web.go +++ b/web.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "embed" "fmt" "github.com/cfwidget/cfwidget/env" "github.com/cfwidget/cfwidget/widget" @@ -14,7 +15,6 @@ import ( "html/template" "log" "net/http" - "os" "strings" "time" ) @@ -24,20 +24,27 @@ type ApiWebResponse struct { Accepted bool `json:"accepted,omitempty"` } -var AllowedFiles = []string{"favicon.ico", "css/app.css"} - const AuthorPath = "author/" var templateEngine *template.Template - var messagePrinter = message.NewPrinter(language.English) +//go:embed favicon.ico +var faviconFile []byte + +//go:embed css/app.css +var cssFile []byte + +//go:embed templates/* +var templates embed.FS + func RegisterApiRoutes(e *gin.Engine) { - templates, err := template.New("").ParseGlob("templates/*.tmpl") + var err error + templateEngine, err = template.New("").ParseFS(templates, "templates/*.tmpl") if err != nil { panic(err) } - templateEngine = templates + e.SetHTMLTemplate(templateEngine) e.GET("/*projectPath", setTransaction, readFromCache, Resolve, GetAuthor, GetProject) @@ -67,24 +74,15 @@ func Resolve(c *gin.Context) { } } - for _, v := range AllowedFiles { - if v == path { - var contentType string - if strings.HasSuffix(v, ".css") { - contentType = "text/css" - } else if strings.HasSuffix(v, ".ico") { - contentType = "image/x-icon" - } - - file, _ := os.ReadFile(v) - SetInCache(c.Request.Host, c.Request.URL.RequestURI(), http.StatusOK, contentType, file) - c.Data(http.StatusOK, contentType, file) - c.Abort() - return - } - } - - if path == "service-worker.js" || path == "service-worker-dev.js" || path == "robots.txt" { + if path == "favicon.ico" { + c.Data(http.StatusOK, "image/x-icon", faviconFile) + c.Abort() + return + } else if path == "css/app.css" { + c.Data(http.StatusOK, "text/css", cssFile) + c.Abort() + return + } else if path == "service-worker.js" || path == "service-worker-dev.js" || path == "robots.txt" { SetInCache(c.Request.URL.Host, c.Request.URL.RequestURI(), http.StatusNotFound, "", nil) c.AbortWithStatus(http.StatusNotFound) return