How to use with embed and build into binary

71 views Asked by At

I am using Go Echo Labstack framework to build my frontend web app, so far it has been great in development, and now I'm going to deploy to production by building the project into binary using go build. However, as it turns out Go doesn't include all my template / html and static files into the binary file which resulted the production build to get error and so unable to run the production build.

I did some research and found out that I have to use embed to include static files into the binary build, but I have a hard time integrating embed with Echo files and routing. Here is my code.

main.go

package main

import (
    "html/template"
    "io"
    "log"
    "margo/app/controllers"

    "github.com/gorilla/sessions"
    "github.com/labstack/echo-contrib/session"
    "github.com/labstack/echo/v4"
    "github.com/labstack/echo/v4/middleware"

    "margo/app/routes"
    util "margo/app/utils"
)

type TemplateRenderer struct {
    templates *template.Template
}

func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {

    // Add global methods if data is a map
    if viewContext, isMap := data.(map[string]interface{}); isMap {
        viewContext["reverse"] = c.Echo().Reverse
    }

    return t.templates.ExecuteTemplate(w, name, data)
}

func main() {
    echo.NotFoundHandler = func(c echo.Context) error {
        return c.Render(404, "404_not_found", controllers.PageData(c, nil))
    }
    e := echo.New()
    e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
        AllowOrigins: []string{"https://margo.co.id"},
        AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
    }))
    e.Pre(middleware.RemoveTrailingSlash())
    e.Use(session.Middleware(sessions.NewCookieStore([]byte("175f678f62fdef4630b40d388d18bddd469925dd5e4c7428af63fcf0b9dc096c"))))

    renderer := &TemplateRenderer{
        templates: template.Must(template.New("t").Funcs(template.FuncMap{
            "StrToLower":              util.StrToLower,
            //... lots other functions
        }).ParseGlob("app/views/*/*.tmpl")),
    }
    e.Renderer = renderer

    routes.Routes(e)

    e.Use(middleware.Static(""))
    e.Use(middleware.Static("static"))

    log.Println("Web instance started!")

    e.Use(middleware.Logger())
    e.Use(middleware.Recover())
    e.Logger.Fatal(e.Start(":8187"))
}

How can I use embed (https://pkg.go.dev/embed) to integrate with Echo and make sure all routes and web pages run smoothly when building into binary for production? Thanks a lot in advance.

0

There are 0 answers