Add embedding of static assets for standalone dist binary

This is a big commit that involves drastic changes to how static assets
(.sql and template files, the whole frontend bundle) are handled.
listmonk distribution should be a self-contained single binary
distribution, hence all static assets should be bundled. After
evaluating several solutions, srtkkou/zgok seemed like the best bet but
it lacked several fundamental features, namely the ability to fall back
to the local filesystem in the absence of embedded assets (for instance,
in the dev mode). Moreover, there was a lot of room for cleanup.

After a PR went unanswered, github.com/knadh/stuffbin was created. Just
like zgok, this enables arbitrary files and assets to be embedded into a
compiled Go binary that can be read during runtime. These changes
followed:

- Compress and embed all static files into the binary during
  the build (Makefile) to make it standalone and distributable
- Refactor static paths (/public/* for public facing assets,
  /frontend/* for the frontend app's assets)
- Add 'logo_url' to config
- Remove 'assets_path' from config
- Tweak yarn build to not produce symbol maps and override
  the default /static (%PUBLIC_URL%) path to /frontend
This commit is contained in:
Kailash Nadh 2019-01-03 16:48:47 +05:30
parent 46f4a0e2aa
commit 7eeb813f19
20 changed files with 228 additions and 185 deletions

View File

@ -1,4 +1,5 @@
BIN := listmonk BIN := listmonk
STATIC := config.toml.sample schema.sql queries.sql public email-templates frontend/my/build:/frontend
HASH := $(shell git rev-parse --short HEAD) HASH := $(shell git rev-parse --short HEAD)
COMMIT_DATE := $(shell git show -s --format=%ci ${HASH}) COMMIT_DATE := $(shell git show -s --format=%ci ${HASH})
@ -6,7 +7,11 @@ BUILD_DATE := $(shell date '+%Y-%m-%d %H:%M:%S')
VERSION := ${HASH} (${COMMIT_DATE}) VERSION := ${HASH} (${COMMIT_DATE})
build: build:
go build -o ${BIN} -ldflags="-X 'main.buildVersion=${VERSION}' -X 'main.buildDate=${BUILD_DATE}'" go build -o ${BIN} -ldflags="-s -w -X 'main.buildVersion=${VERSION}' -X 'main.buildDate=${BUILD_DATE}'"
stuffbin -a stuff -in ${BIN} -out ${BIN} ${STATIC}
deps:
go get -u github.com/knadh/stuffbin/...
test: test:
go test go test

View File

@ -4,7 +4,17 @@ address = "0.0.0.0:9000"
# Public root URL of the listmonk installation that'll be used # Public root URL of the listmonk installation that'll be used
# in the messages for linking to images, unsubscribe page etc. # in the messages for linking to images, unsubscribe page etc.
root = "http://listmonk.mysite.com" root = "https://listmonk.mysite.com"
# (Optional) full URL to the static logo to be displayed on
# user facing view such as the unsubscription page.
# eg: https://mysite.com/images/logo.svg
logo_url = ""
# (Optional) full URL to the static favicon to be displayed on
# user facing view such as the unsubscription page.
# eg: https://mysite.com/images/favicon.png
favicon_url = ""
# The default 'from' e-mail for outgoing e-mail campaigns. # The default 'from' e-mail for outgoing e-mail campaigns.
from_email = "listmonk <from@mail.com>" from_email = "listmonk <from@mail.com>"
@ -22,9 +32,6 @@ upload_path = "uploads"
# under this URI, for instance, list.yoursite.com/uploads. # under this URI, for instance, list.yoursite.com/uploads.
upload_uri = "/uploads" upload_uri = "/uploads"
# Directory where the app's static assets are stored (index.html, ./static etc.)
asset_path = "frontend/my/build"
# Maximum concurrent workers that will attempt to send messages # Maximum concurrent workers that will attempt to send messages
# simultaneously. This should depend on the number of CPUs the # simultaneously. This should depend on the number of CPUs the
# machine has and also the number of simultaenous e-mails the # machine has and also the number of simultaenous e-mails the

View File

@ -16,15 +16,9 @@
"react-router-dom": "^4.3.1", "react-router-dom": "^4.3.1",
"react-scripts": "1.1.4" "react-scripts": "1.1.4"
}, },
"xxscripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"scripts": { "scripts": {
"start": "react-app-rewired start", "start": "react-app-rewired start",
"build": "react-app-rewired build", "build": "GENERATE_SOURCEMAP=false PUBLIC_URL=/frontend/ react-app-rewired build",
"test": "react-app-rewired test --env=jsdom", "test": "react-app-rewired test --env=jsdom",
"eject": "react-scripts eject" "eject": "react-scripts eject"
}, },

View File

@ -4,11 +4,11 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000"> <meta name="theme-color" content="#000000">
<script src="%PUBLIC_URL%/api/config.js" type="text/javascript"></script> <script src="/api/config.js" type="text/javascript"></script>
<link href="https://fonts.googleapis.com/css?family=IBM+Plex+Sans:400,600" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=IBM+Plex+Sans:400,600" rel="stylesheet">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json"> <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.png"> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.png">
<title>%PUBLIC_URL%</title> <title>listmonk</title>
</head> </head>
<body> <body>
<noscript> <noscript>

View File

@ -2,16 +2,14 @@ package main
import ( import (
"encoding/json" "encoding/json"
"net/http"
"net/url" "net/url"
"path/filepath"
"strconv" "strconv"
"strings" "strings"
"github.com/asaskevich/govalidator" "github.com/asaskevich/govalidator"
"github.com/gorilla/sessions"
"github.com/labstack/echo" "github.com/labstack/echo"
"github.com/labstack/echo-contrib/session"
) )
const ( const (
@ -40,39 +38,99 @@ type pagination struct {
Limit int `json:"limit"` Limit int `json:"limit"`
} }
// auth is a middleware that handles session authentication. If a session is not set, // registerHandlers registers HTTP handlers.
// it creates one and redirects the user to the login page. If a session is set, func registerHandlers(e *echo.Echo) {
// it's authenticated before proceeding to the handler. e.GET("/", handleIndexPage)
func authSession(next echo.HandlerFunc) echo.HandlerFunc { e.GET("/api/config.js", handleGetConfigScript)
return func(c echo.Context) error { e.GET("/api/dashboard/stats", handleGetDashboardStats)
sess, _ := session.Get("session", c) e.GET("/api/users", handleGetUsers)
e.POST("/api/users", handleCreateUser)
e.DELETE("/api/users/:id", handleDeleteUser)
// It's a brand new session. Persist it. e.GET("/api/subscribers/:id", handleGetSubscriber)
if sess.IsNew { e.POST("/api/subscribers", handleCreateSubscriber)
sess.Options = &sessions.Options{ e.PUT("/api/subscribers/:id", handleUpdateSubscriber)
Path: "/", e.PUT("/api/subscribers/blacklist", handleBlacklistSubscribers)
MaxAge: 86400 * 7, e.PUT("/api/subscribers/:id/blacklist", handleBlacklistSubscribers)
HttpOnly: true, e.PUT("/api/subscribers/lists/:id", handleManageSubscriberLists)
// Secure: true, e.PUT("/api/subscribers/lists", handleManageSubscriberLists)
} e.DELETE("/api/subscribers/:id", handleDeleteSubscribers)
e.DELETE("/api/subscribers", handleDeleteSubscribers)
sess.Values["user_id"] = 1 // Subscriber operations based on arbitrary SQL queries.
sess.Values["user"] = "kailash" // These aren't very REST-like.
sess.Values["role"] = "superadmin" e.POST("/api/subscribers/query/delete", handleDeleteSubscribersByQuery)
sess.Values["user_email"] = "kailash@zerodha.com" e.PUT("/api/subscribers/query/blacklist", handleBlacklistSubscribersByQuery)
e.PUT("/api/subscribers/query/lists", handleManageSubscriberListsByQuery)
sess.Save(c.Request(), c.Response()) e.GET("/api/subscribers", handleQuerySubscribers)
}
return next(c) e.GET("/api/import/subscribers", handleGetImportSubscribers)
} e.GET("/api/import/subscribers/logs", handleGetImportSubscriberStats)
e.POST("/api/import/subscribers", handleImportSubscribers)
e.DELETE("/api/import/subscribers", handleStopImportSubscribers)
e.GET("/api/lists", handleGetLists)
e.GET("/api/lists/:id", handleGetLists)
e.POST("/api/lists", handleCreateList)
e.PUT("/api/lists/:id", handleUpdateList)
e.DELETE("/api/lists/:id", handleDeleteLists)
e.GET("/api/campaigns", handleGetCampaigns)
e.GET("/api/campaigns/running/stats", handleGetRunningCampaignStats)
e.GET("/api/campaigns/:id", handleGetCampaigns)
e.GET("/api/campaigns/:id/preview", handlePreviewCampaign)
e.POST("/api/campaigns/:id/preview", handlePreviewCampaign)
e.POST("/api/campaigns/:id/test", handleTestCampaign)
e.POST("/api/campaigns", handleCreateCampaign)
e.PUT("/api/campaigns/:id", handleUpdateCampaign)
e.PUT("/api/campaigns/:id/status", handleUpdateCampaignStatus)
e.DELETE("/api/campaigns/:id", handleDeleteCampaign)
e.GET("/api/media", handleGetMedia)
e.POST("/api/media", handleUploadMedia)
e.DELETE("/api/media/:id", handleDeleteMedia)
e.GET("/api/templates", handleGetTemplates)
e.GET("/api/templates/:id", handleGetTemplates)
e.GET("/api/templates/:id/preview", handlePreviewTemplate)
e.POST("/api/templates/preview", handlePreviewTemplate)
e.POST("/api/templates", handleCreateTemplate)
e.PUT("/api/templates/:id", handleUpdateTemplate)
e.PUT("/api/templates/:id/default", handleTemplateSetDefault)
e.DELETE("/api/templates/:id", handleDeleteTemplate)
// Subscriber facing views.
e.GET("/unsubscribe/:campUUID/:subUUID", handleUnsubscribePage)
e.POST("/unsubscribe/:campUUID/:subUUID", handleUnsubscribePage)
e.GET("/link/:linkUUID/:campUUID/:subUUID", handleLinkRedirect)
e.GET("/campaign/:campUUID/:subUUID/px.png", handleRegisterCampaignView)
// Static views.
e.GET("/lists", handleIndexPage)
e.GET("/subscribers", handleIndexPage)
e.GET("/subscribers/lists/:listID", handleIndexPage)
e.GET("/subscribers/import", handleIndexPage)
e.GET("/campaigns", handleIndexPage)
e.GET("/campaigns/new", handleIndexPage)
e.GET("/campaigns/media", handleIndexPage)
e.GET("/campaigns/templates", handleIndexPage)
e.GET("/campaigns/:campignID", handleIndexPage)
} }
// handleIndex is the root handler that renders the login page if there's no // handleIndex is the root handler that renders the login page if there's no
// authenticated session, or redirects to the dashboard, if there's one. // authenticated session, or redirects to the dashboard, if there's one.
func handleIndexPage(c echo.Context) error { func handleIndexPage(c echo.Context) error {
app := c.Get("app").(*App) app := c.Get("app").(*App)
return c.File(filepath.Join(app.Constants.AssetPath, "index.html"))
b, err := app.FS.Read("/frontend/index.html")
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError,
err)
}
c.Response().Header().Set("Content-Type", "text/html")
return c.String(http.StatusOK, string(b))
} }
// makeAttribsBlob takes a list of keys and values and creates // makeAttribsBlob takes a list of keys and values and creates

View File

@ -29,9 +29,10 @@ func install(app *App, qMap goyesql.Queries) {
emRegex, _ = regexp.Compile("(.+?)@(.+?)") emRegex, _ = regexp.Compile("(.+?)@(.+?)")
) )
fmt.Println("")
fmt.Println("** First time installation. **") fmt.Println("** First time installation. **")
fmt.Println("** IMPORTANT: This will wipe existing listmonk tables and types. **") fmt.Println("** IMPORTANT: This will wipe existing listmonk tables and types. **")
fmt.Println("\n") fmt.Println("")
for len(email) == 0 { for len(email) == 0 {
fmt.Print("Enter the superadmin login e-mail: ") fmt.Print("Enter the superadmin login e-mail: ")
@ -83,7 +84,7 @@ func install(app *App, qMap goyesql.Queries) {
} }
// Migrate the tables. // Migrate the tables.
err = installMigrate(app.DB) err = installMigrate(app.DB, app)
if err != nil { if err != nil {
logger.Fatalf("Error migrating DB schema: %v", err) logger.Fatalf("Error migrating DB schema: %v", err)
} }
@ -152,8 +153,8 @@ func install(app *App, qMap goyesql.Queries) {
} }
// installMigrate executes the SQL schema and creates the necessary tables and types. // installMigrate executes the SQL schema and creates the necessary tables and types.
func installMigrate(db *sqlx.DB) error { func installMigrate(db *sqlx.DB, app *App) error {
q, err := ioutil.ReadFile("schema.sql") q, err := app.FS.Read("/schema.sql")
if err != nil { if err != nil {
return err return err
} }

172
main.go
View File

@ -15,14 +15,16 @@ import (
"github.com/knadh/listmonk/manager" "github.com/knadh/listmonk/manager"
"github.com/knadh/listmonk/messenger" "github.com/knadh/listmonk/messenger"
"github.com/knadh/listmonk/subimporter" "github.com/knadh/listmonk/subimporter"
"github.com/knadh/stuffbin"
"github.com/labstack/echo" "github.com/labstack/echo"
flag "github.com/spf13/pflag" flag "github.com/spf13/pflag"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
type constants struct { type constants struct {
AssetPath string `mapstructure:"asset_path"`
RootURL string `mapstructure:"root"` RootURL string `mapstructure:"root"`
LogoURL string `mapstructure:"logo_url"`
FaviconURL string `mapstructure:"favicon_url"`
UploadPath string `mapstructure:"upload_path"` UploadPath string `mapstructure:"upload_path"`
UploadURI string `mapstructure:"upload_uri"` UploadURI string `mapstructure:"upload_uri"`
FromEmail string `mapstructure:"from_email"` FromEmail string `mapstructure:"from_email"`
@ -37,6 +39,7 @@ type App struct {
Queries *Queries Queries *Queries
Importer *subimporter.Importer Importer *subimporter.Importer
Manager *manager.Manager Manager *manager.Manager
FS stuffbin.FileSystem
Logger *log.Logger Logger *log.Logger
NotifTpls *template.Template NotifTpls *template.Template
Messenger messenger.Messenger Messenger messenger.Messenger
@ -77,84 +80,36 @@ func init() {
} }
} }
// registerHandlers registers HTTP handlers. // initFileSystem initializes the stuffbin FileSystem to provide
func registerHandlers(e *echo.Echo) { // access to bunded static assets to the app.
e.GET("/", handleIndexPage) func initFileSystem(binPath string) (stuffbin.FileSystem, error) {
e.GET("/api/config.js", handleGetConfigScript) fs, err := stuffbin.UnStuff("./listmonk")
e.GET("/api/dashboard/stats", handleGetDashboardStats) if err == nil {
e.GET("/api/users", handleGetUsers) return fs, nil
e.POST("/api/users", handleCreateUser) }
e.DELETE("/api/users/:id", handleDeleteUser)
e.GET("/api/subscribers/:id", handleGetSubscriber) // Running in local mode. Load the required static assets into
e.POST("/api/subscribers", handleCreateSubscriber) // the in-memory stuffbin.FileSystem.
e.PUT("/api/subscribers/:id", handleUpdateSubscriber) logger.Printf("unable to initialize embedded filesystem: %v", err)
e.PUT("/api/subscribers/blacklist", handleBlacklistSubscribers) logger.Printf("using local filesystem for static assets")
e.PUT("/api/subscribers/:id/blacklist", handleBlacklistSubscribers) files := []string{
e.PUT("/api/subscribers/lists/:id", handleManageSubscriberLists) "config.toml.sample",
e.PUT("/api/subscribers/lists", handleManageSubscriberLists) "queries.sql",
e.DELETE("/api/subscribers/:id", handleDeleteSubscribers) "schema.sql",
e.DELETE("/api/subscribers", handleDeleteSubscribers) "email-templates",
"public",
// Subscriber operations based on arbitrary SQL queries. // The frontend app's static assets are aliased to /frontend
// These aren't very REST-like. // so that they are accessible at localhost:port/frontend/static/ ...
e.POST("/api/subscribers/query/delete", handleDeleteSubscribersByQuery) "frontend/my/build:/frontend",
e.PUT("/api/subscribers/query/blacklist", handleBlacklistSubscribersByQuery) }
e.PUT("/api/subscribers/query/lists", handleManageSubscriberListsByQuery)
e.GET("/api/subscribers", handleQuerySubscribers) fs, err = stuffbin.NewLocalFS("/", files...)
if err != nil {
return nil, fmt.Errorf("failed to initialize local file for assets: %v", err)
}
e.GET("/api/import/subscribers", handleGetImportSubscribers) return fs, nil
e.GET("/api/import/subscribers/logs", handleGetImportSubscriberStats)
e.POST("/api/import/subscribers", handleImportSubscribers)
e.DELETE("/api/import/subscribers", handleStopImportSubscribers)
e.GET("/api/lists", handleGetLists)
e.GET("/api/lists/:id", handleGetLists)
e.POST("/api/lists", handleCreateList)
e.PUT("/api/lists/:id", handleUpdateList)
e.DELETE("/api/lists/:id", handleDeleteLists)
e.GET("/api/campaigns", handleGetCampaigns)
e.GET("/api/campaigns/running/stats", handleGetRunningCampaignStats)
e.GET("/api/campaigns/:id", handleGetCampaigns)
e.GET("/api/campaigns/:id/preview", handlePreviewCampaign)
e.POST("/api/campaigns/:id/preview", handlePreviewCampaign)
e.POST("/api/campaigns/:id/test", handleTestCampaign)
e.POST("/api/campaigns", handleCreateCampaign)
e.PUT("/api/campaigns/:id", handleUpdateCampaign)
e.PUT("/api/campaigns/:id/status", handleUpdateCampaignStatus)
e.DELETE("/api/campaigns/:id", handleDeleteCampaign)
e.GET("/api/media", handleGetMedia)
e.POST("/api/media", handleUploadMedia)
e.DELETE("/api/media/:id", handleDeleteMedia)
e.GET("/api/templates", handleGetTemplates)
e.GET("/api/templates/:id", handleGetTemplates)
e.GET("/api/templates/:id/preview", handlePreviewTemplate)
e.POST("/api/templates/preview", handlePreviewTemplate)
e.POST("/api/templates", handleCreateTemplate)
e.PUT("/api/templates/:id", handleUpdateTemplate)
e.PUT("/api/templates/:id/default", handleTemplateSetDefault)
e.DELETE("/api/templates/:id", handleDeleteTemplate)
// Subscriber facing views.
e.GET("/unsubscribe/:campUUID/:subUUID", handleUnsubscribePage)
e.POST("/unsubscribe/:campUUID/:subUUID", handleUnsubscribePage)
e.GET("/link/:linkUUID/:campUUID/:subUUID", handleLinkRedirect)
e.GET("/campaign/:campUUID/:subUUID/px.png", handleRegisterCampaignView)
// Static views.
e.GET("/lists", handleIndexPage)
e.GET("/subscribers", handleIndexPage)
e.GET("/subscribers/lists/:listID", handleIndexPage)
e.GET("/subscribers/import", handleIndexPage)
e.GET("/campaigns", handleIndexPage)
e.GET("/campaigns/new", handleIndexPage)
e.GET("/campaigns/media", handleIndexPage)
e.GET("/campaigns/templates", handleIndexPage)
e.GET("/campaigns/:campignID", handleIndexPage)
} }
// initMessengers initializes various messaging backends. // initMessengers initializes various messaging backends.
@ -163,7 +118,7 @@ func initMessengers(r *manager.Manager) messenger.Messenger {
var srv []messenger.Server var srv []messenger.Server
for name := range viper.GetStringMapString("smtp") { for name := range viper.GetStringMapString("smtp") {
if !viper.GetBool(fmt.Sprintf("smtp.%s.enabled", name)) { if !viper.GetBool(fmt.Sprintf("smtp.%s.enabled", name)) {
logger.Printf("skipped SMTP config %s", name) logger.Printf("skipped SMTP: %s", name)
continue continue
} }
@ -173,7 +128,7 @@ func initMessengers(r *manager.Manager) messenger.Messenger {
s.SendTimeout = s.SendTimeout * time.Millisecond s.SendTimeout = s.SendTimeout * time.Millisecond
srv = append(srv, s) srv = append(srv, s)
logger.Printf("loaded SMTP config %s (%s@%s)", s.Name, s.Username, s.Host) logger.Printf("loaded SMTP: %s (%s@%s)", s.Name, s.Username, s.Host)
} }
msgr, err := messenger.NewEmailer(srv...) msgr, err := messenger.NewEmailer(srv...)
@ -203,22 +158,34 @@ func main() {
viper.UnmarshalKey("app", &c) viper.UnmarshalKey("app", &c)
c.RootURL = strings.TrimRight(c.RootURL, "/") c.RootURL = strings.TrimRight(c.RootURL, "/")
c.UploadURI = filepath.Clean(c.UploadURI) c.UploadURI = filepath.Clean(c.UploadURI)
c.AssetPath = filepath.Clean(c.AssetPath) c.UploadPath = filepath.Clean(c.UploadPath)
// Initialize the static file system into which all
// required static assets (.sql, .js files etc.) are loaded.
fs, err := initFileSystem(os.Args[0])
if err != nil {
logger.Fatal(err)
}
// Initialize the app context that's passed around. // Initialize the app context that's passed around.
app := &App{ app := &App{
Constants: &c, Constants: &c,
DB: db, DB: db,
Logger: logger, Logger: logger,
FS: fs,
} }
// Load SQL queries. // Load SQL queries.
qMap, err := goyesql.ParseFile("queries.sql") qB, err := fs.Read("/queries.sql")
if err != nil { if err != nil {
logger.Fatalf("error loading SQL queries: %v", err) logger.Fatalf("error reading queries.sql: %v", err)
}
qMap, err := goyesql.ParseBytes(qB)
if err != nil {
logger.Fatalf("error parsing SQL queries: %v", err)
} }
// First time installation. // Run the first time installation.
if viper.GetBool("install") { if viper.GetBool("install") {
install(app, qMap) install(app, qMap)
return return
@ -231,7 +198,7 @@ func main() {
} }
app.Queries = q app.Queries = q
// Importer. // Initialize the bulk subscriber importer.
importNotifCB := func(subject string, data map[string]interface{}) error { importNotifCB := func(subject string, data map[string]interface{}) error {
return sendNotification(notifTplImport, subject, data, app) return sendNotification(notifTplImport, subject, data, app)
} }
@ -240,14 +207,14 @@ func main() {
db.DB, db.DB,
importNotifCB) importNotifCB)
// System e-mail templates. // Read system e-mail templates.
notifTpls, err := template.ParseGlob("templates/*.html") notifTpls, err := stuffbin.ParseTemplatesGlob(fs, "/email-templates/*.html")
if err != nil { if err != nil {
logger.Fatalf("error loading system templates: %v", err) logger.Fatalf("error loading system e-mail templates: %v", err)
} }
app.NotifTpls = notifTpls app.NotifTpls = notifTpls
// Campaign daemon. // Initialize the campaign manager.
campNotifCB := func(subject string, data map[string]interface{}) error { campNotifCB := func(subject string, data map[string]interface{}) error {
return sendNotification(notifTplCampaign, subject, data, app) return sendNotification(notifTplCampaign, subject, data, app)
} }
@ -270,11 +237,15 @@ func main() {
// Add messengers. // Add messengers.
app.Messenger = initMessengers(app.Manager) app.Messenger = initMessengers(app.Manager)
// Initialize the workers that push out messages.
go m.Run(time.Duration(time.Second * 5)) go m.Run(time.Duration(time.Second * 5))
m.SpawnWorkers() m.SpawnWorkers()
// Initialize the server. // Initialize the HTTP server.
var srv = echo.New() var srv = echo.New()
srv.HideBanner = true
// Register app (*App) to be injected into all HTTP handlers.
srv.Use(func(next echo.HandlerFunc) echo.HandlerFunc { srv.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
c.Set("app", app) c.Set("app", app)
@ -282,25 +253,22 @@ func main() {
} }
}) })
// User facing templates. // Parse user facing templates.
tpl, err := template.ParseGlob("public/templates/*.html") tpl, err := stuffbin.ParseTemplatesGlob(fs, "/public/templates/*.html")
if err != nil { if err != nil {
logger.Fatalf("error parsing public templates: %v", err) logger.Fatalf("error parsing public templates: %v", err)
} }
srv.Renderer = &Template{ srv.Renderer = &tplRenderer{
templates: tpl, templates: tpl,
} RootURL: c.RootURL,
srv.HideBanner = true LogoURL: c.LogoURL,
FaviconURL: c.FaviconURL}
// Register HTTP middleware. // Register HTTP handlers and static file servers.
// e.Use(session.Middleware(sessions.NewCookieStore([]byte("secret")))) fSrv := app.FS.FileServer()
// e.Use(authSession) srv.GET("/public/*", echo.WrapHandler(fSrv))
srv.Static("/static", filepath.Join(filepath.Clean(viper.GetString("app.asset_path")), "static")) srv.GET("/frontend/*", echo.WrapHandler(fSrv))
srv.Static("/static/public", "frontend/my/public") srv.Static(c.UploadURI, c.UploadURI)
srv.Static("/public/static", "public/static")
srv.Static(filepath.Clean(viper.GetString("app.upload_uri")),
filepath.Clean(viper.GetString("app.upload_path")))
registerHandlers(srv) registerHandlers(srv)
srv.Logger.Fatal(srv.Start(viper.GetString("app.address"))) srv.Logger.Fatal(srv.Start(viper.GetString("app.address")))
} }

View File

@ -1,5 +0,0 @@
{
"dependencies": {
"qs": "^6.5.2"
}
}

View File

@ -13,9 +13,21 @@ import (
"github.com/labstack/echo" "github.com/labstack/echo"
) )
// Template wraps a template.Template for echo. // tplRenderer wraps a template.tplRenderer for echo.
type Template struct { type tplRenderer struct {
templates *template.Template templates *template.Template
RootURL string
LogoURL string
FaviconURL string
}
// tplData is the data container that is injected
// into public templates for accessing data.
type tplData struct {
RootURL string
LogoURL string
FaviconURL string
Data interface{}
} }
type publicTpl struct { type publicTpl struct {
@ -31,7 +43,6 @@ type unsubTpl struct {
type errorTpl struct { type errorTpl struct {
publicTpl publicTpl
ErrorTitle string ErrorTitle string
ErrorMessage string ErrorMessage string
} }
@ -42,8 +53,13 @@ var (
) )
// Render executes and renders a template for echo. // Render executes and renders a template for echo.
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error { func (t *tplRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data) return t.templates.ExecuteTemplate(w, name, tplData{
RootURL: t.RootURL,
LogoURL: t.LogoURL,
FaviconURL: t.FaviconURL,
Data: data,
})
} }
// handleUnsubscribePage unsubscribes a subscriber and renders a view. // handleUnsubscribePage unsubscribes a subscriber and renders a view.
@ -66,7 +82,7 @@ func handleUnsubscribePage(c echo.Context) error {
return c.Render(http.StatusBadRequest, "error", return c.Render(http.StatusBadRequest, "error",
makeErrorTpl("Invalid request", "", makeErrorTpl("Invalid request", "",
`The unsubscription request contains invalid IDs. `The unsubscription request contains invalid IDs.
Please click on the correct link.`)) Please follow the correct link.`))
} }
// Unsubscribe. // Unsubscribe.
@ -74,7 +90,8 @@ func handleUnsubscribePage(c echo.Context) error {
res, err := app.Queries.Unsubscribe.Exec(campUUID, subUUID, blacklist) res, err := app.Queries.Unsubscribe.Exec(campUUID, subUUID, blacklist)
if err != nil { if err != nil {
app.Logger.Printf("Error unsubscribing : %v", err) app.Logger.Printf("Error unsubscribing : %v", err)
return echo.NewHTTPError(http.StatusBadRequest, "There was an internal error while unsubscribing you.") return echo.NewHTTPError(http.StatusBadRequest,
"There was an internal error while unsubscribing you.")
} }
if !blacklist { if !blacklist {
@ -82,7 +99,7 @@ func handleUnsubscribePage(c echo.Context) error {
if num == 0 { if num == 0 {
return c.Render(http.StatusBadRequest, "error", return c.Render(http.StatusBadRequest, "error",
makeErrorTpl("Already unsubscribed", "", makeErrorTpl("Already unsubscribed", "",
`Looks like you are not subscribed to this mailing list. `You are not subscribed to this mailing list.
You may have already unsubscribed.`)) You may have already unsubscribed.`))
} }
} }
@ -110,7 +127,8 @@ func handleLinkRedirect(c echo.Context) error {
if err := app.Queries.RegisterLinkClick.Get(&url, linkUUID, campUUID, subUUID); err != nil { if err := app.Queries.RegisterLinkClick.Get(&url, linkUUID, campUUID, subUUID); err != nil {
app.Logger.Printf("error fetching redirect link: %s", err) app.Logger.Printf("error fetching redirect link: %s", err)
return c.Render(http.StatusInternalServerError, "error", return c.Render(http.StatusInternalServerError, "error",
makeErrorTpl("Error opening link", "", "There was an error opening the link. Please try later.")) makeErrorTpl("Error opening link", "",
"There was an error opening the link. Please try later."))
} }
return c.Redirect(http.StatusTemporaryRedirect, url) return c.Redirect(http.StatusTemporaryRedirect, url)
@ -143,7 +161,6 @@ func drawTransparentImage(h, w int) []byte {
img = image.NewRGBA(image.Rect(0, 0, w, h)) img = image.NewRGBA(image.Rect(0, 0, w, h))
out = &bytes.Buffer{} out = &bytes.Buffer{}
) )
png.Encode(out, img) png.Encode(out, img)
return out.Bytes() return out.Bytes()
} }

View File

@ -53,7 +53,7 @@ h1, h2, h3, h4 {
} }
.header .logo img { .header .logo img {
width: auto; width: auto;
max-height: 24px; max-width: 150px;
} }
.unsub-all { .unsub-all {

View File

@ -1,9 +1,9 @@
{{ define "error" }} {{ define "error" }}
{{ template "header" .}} {{ template "header" .}}
<h2>{{ .ErrorTitle }}</h2> <h2>{{ .Data.ErrorTitle }}</h2>
<div> <div>
{{ .ErrorMessage }} {{ .Data.ErrorMessage }}
</div> </div>
{{ template "footer" .}} {{ template "footer" .}}

View File

@ -1,3 +0,0 @@
{{ define "hello" }}
hello
{{ end }}

View File

@ -1,3 +0,0 @@
{{ define "hello" }}
hello2
{{ end }}

View File

@ -3,22 +3,32 @@
<html> <html>
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{{ .Title }}</title> <title>{{ .Data.Title }}</title>
<meta name="description" content="{{ .Description }}" /> <meta name="description" content="{{ .Data.Description }}" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400' rel='stylesheet' type='text/css'> <link href="https://fonts.googleapis.com/css?family=IBM+Plex+Sans:400,600" rel="stylesheet">
<link href="/public/static/style.css" rel="stylesheet" type="text/css" /> <link href="/public/static/style.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="/public/static/favicon.png" type="image/x-icon" />
{{ if ne .FaviconURL "" }}
<link rel="shortcut icon" href="{{ .FaviconURL }}" type="image/x-icon" />
{{ else }}
<link rel="shortcut icon" href="/public/static/favicon.png" type="image/x-icon" />
{{ end }}
</head> </head>
<body> <body>
<div class="container wrap"> <div class="container wrap">
<header class="header"> <header class="header">
<div class="logo"><img src="/public/static/logo.svg" /></div> <div class="logo">
{{ if ne .LogoURL "" }}
<img src="{{ .LogoURL }}" alt="{{ .Data.Title }}" />
{{ else }}
<img src="/public/static/logo.svg" alt="{{ .Data.Title }}" />
{{ end }}
</div>
</header> </header>
{{ end }} {{ end }}
{{ define "footer" }} {{ define "footer" }}
</div> </div>

View File

@ -1,7 +1,7 @@
{{ define "unsubscribe" }} {{ define "unsubscribe" }}
{{ template "header" .}} {{ template "header" .}}
{{ if not .Unsubscribe }} {{ if not .Data.Unsubscribe }}
<h2>Unsubscribe</h2> <h2>Unsubscribe</h2>
<p>Do you wish to unsubscribe from this mailing list?</p> <p>Do you wish to unsubscribe from this mailing list?</p>
<form method="post"> <form method="post">
@ -13,7 +13,7 @@
{{ else }} {{ else }}
<h2>You have been unsubscribed</h2> <h2>You have been unsubscribed</h2>
{{ if not .Blacklist }} {{ if not .Data.Blacklist }}
<div class="unsub-all"> <div class="unsub-all">
<p> <p>
Unsubscribe from all future communications? Unsubscribe from all future communications?

View File

@ -1,6 +0,0 @@
[postgres]
dbname="listmonk"
host="localhost"
port=5432
user="postgres"
pass="postgres"