Skip to content

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.

Fix various static-check/idiom warnings.

Kailash Nadh92e5d630cac0
diff --git a/cmd/admin.go b/cmd/admin.go
index 2541dbfb..e4207487 100644
--- a/cmd/admin.go
+++ b/cmd/admin.go
@@ -37,7 +37,7 @@ func handleGetServerConfig(c echo.Context) error {
}
// Language list.
- langList, err := getI18nLangList(app.constants.Lang, app)
+ langList, err := getI18nLangList(app)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError,
fmt.Sprintf("Error loading language list: %v", err))
diff --git a/cmd/auth.go b/cmd/auth.go
index 2d368ba7..de7cf106 100644
--- a/cmd/auth.go
+++ b/cmd/auth.go
@@ -316,7 +316,7 @@ func doLogin(c echo.Context) error {
}
// Resist potential constant-time-comparison attacks with a min response time.
- if ms := time.Now().Sub(start).Milliseconds(); ms < 100 {
+ if ms := time.Since(start).Milliseconds(); ms < 100 {
time.Sleep(time.Duration(ms))
}
diff --git a/cmd/bounce.go b/cmd/bounce.go
index 33b7b549..6afcc132 100644
--- a/cmd/bounce.go
+++ b/cmd/bounce.go
@@ -161,7 +161,6 @@ func handleBounceWebhook(c echo.Context) error {
app.log.Printf("error processing SNS (SES) subscription: %v", err)
return echo.NewHTTPError(http.StatusBadRequest, app.i18n.T("globals.messages.invalidData"))
}
- break
// Bounce notification.
case "Notification":
diff --git a/cmd/handlers.go b/cmd/handlers.go
index 0c38adb2..c123325a 100644
--- a/cmd/handlers.go
+++ b/cmd/handlers.go
@@ -8,7 +8,6 @@ import (
"regexp"
"github.com/knadh/listmonk/internal/auth"
- "github.com/knadh/paginator"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
@@ -17,11 +16,6 @@ const (
// stdInputMaxLen is the maximum allowed length for a standard input field.
stdInputMaxLen = 2000
- sortAsc = "asc"
- sortDesc = "desc"
-
- basicAuthd = "basicauthd"
-
// URIs.
uriAdmin = "/admin"
)
@@ -30,25 +24,8 @@ type okResp struct {
Data interface{} `json:"data"`
}
-// pagination represents a query's pagination (limit, offset) related values.
-type pagination struct {
- PerPage int `json:"per_page"`
- Page int `json:"page"`
- Offset int `json:"offset"`
- Limit int `json:"limit"`
-}
-
var (
- reUUID = regexp.MustCompile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
- reLangCode = regexp.MustCompile("[^a-zA-Z_0-9\\-]")
-
- paginate = paginator.New(paginator.Opt{
- DefaultPerPage: 20,
- MaxPerPage: 50,
- NumPageNums: 10,
- PageParam: "page",
- PerPageParam: "per_page",
- })
+ reUUID = regexp.MustCompile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
)
// registerHandlers registers HTTP handlers.
@@ -352,9 +329,8 @@ func validateUUID(next echo.HandlerFunc, params ...string) echo.HandlerFunc {
for _, p := range params {
if !reUUID.MatchString(c.Param(p)) {
- return c.Render(http.StatusBadRequest, tplMessage,
- makeMsgTpl(app.i18n.T("public.errorTitle"), "",
- app.i18n.T("globals.messages.invalidUUID")))
+ return c.Render(http.StatusBadRequest, tplMessage, makeMsgTpl(app.i18n.T("public.errorTitle"), "",
+ app.i18n.T("globals.messages.invalidUUID")))
}
}
return next(c)
@@ -363,7 +339,7 @@ func validateUUID(next echo.HandlerFunc, params ...string) echo.HandlerFunc {
// subscriberExists middleware checks if a subscriber exists given the UUID
// param in a request.
-func subscriberExists(next echo.HandlerFunc, params ...string) echo.HandlerFunc {
+func subscriberExists(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
var (
app = c.Get("app").(*App)
@@ -386,7 +362,7 @@ func subscriberExists(next echo.HandlerFunc, params ...string) echo.HandlerFunc
}
// noIndex adds the HTTP header requesting robots to not crawl the page.
-func noIndex(next echo.HandlerFunc, params ...string) echo.HandlerFunc {
+func noIndex(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Response().Header().Set("X-Robots-Tag", "noindex")
return next(c)
diff --git a/cmd/i18n.go b/cmd/i18n.go
index 8b9dc74e..261c79ea 100644
--- a/cmd/i18n.go
+++ b/cmd/i18n.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"net/http"
+ "regexp"
"sort"
"github.com/knadh/listmonk/internal/i18n"
@@ -21,6 +22,8 @@ type i18nLangRaw struct {
Name string `json:"_.name"`
}
+var reLangCode = regexp.MustCompile(`[^a-zA-Z_0-9\\-]`)
+
// handleGetI18nLang returns the JSON language pack given the language code.
func handleGetI18nLang(c echo.Context) error {
app := c.Get("app").(*App)
@@ -39,7 +42,7 @@ func handleGetI18nLang(c echo.Context) error {
}
// getI18nLangList returns the list of available i18n languages.
-func getI18nLangList(lang string, app *App) ([]i18nLang, error) {
+func getI18nLangList(app *App) ([]i18nLang, error) {
list, err := app.fs.Glob("/i18n/*.json")
if err != nil {
return nil, err
@@ -52,15 +55,12 @@ func getI18nLangList(lang string, app *App) ([]i18nLang, error) {
return out, fmt.Errorf("error reading lang file: %s: %v", l, err)
}
- var lang i18nLangRaw
- if err := json.Unmarshal(b.ReadBytes(), &lang); err != nil {
+ var r i18nLangRaw
+ if err := json.Unmarshal(b.ReadBytes(), &r); err != nil {
return out, fmt.Errorf("error parsing lang file: %s: %v", l, err)
}
- out = append(out, i18nLang{
- Code: lang.Code,
- Name: lang.Name,
- })
+ out = append(out, i18nLang(r))
}
sort.SliceStable(out, func(i, j int) bool {
diff --git a/cmd/init.go b/cmd/init.go
index c9067528..50932504 100644
--- a/cmd/init.go
+++ b/cmd/init.go
@@ -317,7 +317,7 @@ func initDB() *sqlx.DB {
}
// readQueries reads named SQL queries from the SQL queries file into a query map.
-func readQueries(sqlFile string, db *sqlx.DB, fs stuffbin.FileSystem) goyesql.Queries {
+func readQueries(sqlFile string, fs stuffbin.FileSystem) goyesql.Queries {
// Load SQL queries.
qB, err := fs.Read(sqlFile)
if err != nil {
@@ -673,7 +673,7 @@ func initMediaStore() media.Store {
// initNotifTemplates compiles and returns e-mail notification templates that are
// used for sending ad-hoc notifications to admins and subscribers.
-func initNotifTemplates(path string, fs stuffbin.FileSystem, i *i18n.I18n, cs *constants) *notifTpls {
+func initNotifTemplates(fs stuffbin.FileSystem, i *i18n.I18n, cs *constants) *notifTpls {
tpls, err := stuffbin.ParseTemplatesGlob(initTplFuncs(i, cs), fs, "/static/email-templates/*.html")
if err != nil {
lo.Fatalf("error parsing e-mail notif templates: %v", err)
diff --git a/cmd/install.go b/cmd/install.go
index 3d61ca2a..f313e43e 100644
--- a/cmd/install.go
+++ b/cmd/install.go
@@ -15,7 +15,7 @@ import (
// install runs the first time setup of setting up the database.
func install(lastVer string, db *sqlx.DB, fs stuffbin.FileSystem, prompt, idempotent bool) {
- qMap := readQueries(queryFilePath, db, fs)
+ qMap := readQueries(queryFilePath, fs)
fmt.Println("")
if !idempotent {
@@ -244,7 +244,7 @@ func recordMigrationVersion(ver string, db *sqlx.DB) error {
func newConfigFile(path string) error {
if _, err := os.Stat(path); !os.IsNotExist(err) {
- return fmt.Errorf("%s exists. Remove it to generate a new one.", path)
+ return fmt.Errorf("%s exists. Remove it to generate a new one", path)
}
// Initialize the static file system into which all
diff --git a/cmd/main.go b/cmd/main.go
index e7de4092..6e538bbb 100644
--- a/cmd/main.go
+++ b/cmd/main.go
@@ -157,7 +157,7 @@ func init() {
checkUpgrade(db)
// Read the SQL queries from the queries file.
- qMap := readQueries(queryFilePath, db, fs)
+ qMap := readQueries(queryFilePath, fs)
// Load settings from DB.
if q, ok := qMap["get-settings"]; ok {
@@ -223,7 +223,7 @@ func main() {
// for new user setup.
app.needsUserSetup = !hasUsers
- app.notifTpls = initNotifTemplates("/email-templates/*.html", fs, app.i18n, app.constants)
+ app.notifTpls = initNotifTemplates(fs, app.i18n, app.constants)
initTxTemplates(app.manager, app)
if ko.Bool("bounce.enabled") {
diff --git a/cmd/manager_store.go b/cmd/manager_store.go
index e0d82fc2..72c3c5da 100644
--- a/cmd/manager_store.go
+++ b/cmd/manager_store.go
@@ -1,8 +1,6 @@
package main
import (
- "net/http"
-
"github.com/gofrs/uuid/v5"
"github.com/knadh/listmonk/internal/core"
"github.com/knadh/listmonk/internal/manager"
@@ -17,7 +15,6 @@ type store struct {
queries *models.Queries
core *core.Core
media media.Store
- h *http.Client
}
type runningCamp struct {
diff --git a/cmd/notifications.go b/cmd/notifications.go
index eece80ed..5ae296e3 100644
--- a/cmd/notifications.go
+++ b/cmd/notifications.go
@@ -20,13 +20,6 @@ var (
reTitle = regexp.MustCompile(`(?s)<title\s*data-i18n\s*>(.+?)</title>`)
)
-// notifData represents params commonly used across different notification
-// templates.
-type notifData struct {
- RootURL string
- LogoURL string
-}
-
// sendNotification sends out an e-mail notification to admins.
func (app *App) sendNotification(toEmails []string, subject, tplName string, data interface{}, headers textproto.MIMEHeader) error {
if len(toEmails) == 0 {
diff --git a/cmd/subscribers.go b/cmd/subscribers.go
index 4d775a0f..ef9983ab 100644
--- a/cmd/subscribers.go
+++ b/cmd/subscribers.go
@@ -3,7 +3,6 @@ package main
import (
"encoding/csv"
"encoding/json"
- "errors"
"fmt"
"net/http"
"net/textproto"
@@ -34,16 +33,6 @@ type subQueryReq struct {
All bool `json:"all"`
}
-// subProfileData represents a subscriber's collated data in JSON
-// for export.
-type subProfileData struct {
- Email string `db:"email" json:"-"`
- Profile json.RawMessage `db:"profile" json:"profile,omitempty"`
- Subscriptions json.RawMessage `db:"subscriptions" json:"subscriptions,omitempty"`
- CampaignViews json.RawMessage `db:"campaign_views" json:"campaign_views,omitempty"`
- LinkClicks json.RawMessage `db:"link_clicks" json:"link_clicks,omitempty"`
-}
-
// subOptin contains the data that's passed to the double opt-in e-mail template.
type subOptin struct {
models.Subscriber
@@ -60,10 +49,6 @@ var (
UUID: dummyUUID,
Attribs: models.JSON{"city": "Bengaluru"},
}
-
- subQuerySortFields = []string{"email", "name", "created_at", "updated_at"}
-
- errSubscriberExists = errors.New("subscriber already exists")
)
// handleGetSubscriber handles the retrieval of a single subscriber by ID.
@@ -175,7 +160,7 @@ loop:
if err != nil {
return err
}
- if out == nil || len(out) == 0 {
+ if len(out) == 0 {
break
}
@@ -416,8 +401,7 @@ func handleDeleteSubscribers(c echo.Context) error {
app.i18n.Ts("globals.messages.errorInvalidIDs", "error", err.Error()))
}
if len(i) == 0 {
- return echo.NewHTTPError(http.StatusBadRequest,
- app.i18n.Ts("subscribers.errorNoIDs", "error", err.Error()))
+ return echo.NewHTTPError(http.StatusBadRequest, app.i18n.T("subscribers.errorNoIDs"))
}
subIDs = i
}
diff --git a/cmd/upgrade.go b/cmd/upgrade.go
index 414c5178..c74f2c28 100644
--- a/cmd/upgrade.go
+++ b/cmd/upgrade.go
@@ -115,7 +115,7 @@ func checkUpgrade(db *sqlx.DB) {
// getPendingMigrations gets the pending migrations by comparing the last
// recorded migration in the DB against all migrations listed in `migrations`.
func getPendingMigrations(db *sqlx.DB) (string, []migFunc, error) {
- lastVer, err := getLastMigrationVersion()
+ lastVer, err := getLastMigrationVersion(db)
if err != nil {
return "", nil, err
}
@@ -135,7 +135,7 @@ func getPendingMigrations(db *sqlx.DB) (string, []migFunc, error) {
// getLastMigrationVersion returns the last migration semver recorded in the DB.
// If there isn't any, `v0.0.0` is returned.
-func getLastMigrationVersion() (string, error) {
+func getLastMigrationVersion(db *sqlx.DB) (string, error) {
var v string
if err := db.Get(&v, `
SELECT COALESCE(
diff --git a/cmd/users.go b/cmd/users.go
index 9c259cce..0ca78c02 100644
--- a/cmd/users.go
+++ b/cmd/users.go
@@ -15,7 +15,7 @@ import (
)
var (
- reUsername = regexp.MustCompile("^[a-zA-Z0-9_\\-\\.]+$")
+ reUsername = regexp.MustCompile(`^[a-zA-Z0-9_\\-\\.]+$`)
)
// handleGetUsers retrieves users.
diff --git a/cmd/utils.go b/cmd/utils.go
index 7c48ab66..ebbf7e46 100644
--- a/cmd/utils.go
+++ b/cmd/utils.go
@@ -1,16 +1,12 @@
package main
import (
- "bytes"
"crypto/rand"
"fmt"
"path/filepath"
"regexp"
"strconv"
"strings"
-
- "golang.org/x/text/cases"
- "golang.org/x/text/language"
)
var (
@@ -99,27 +95,3 @@ func generateRandomString(n int) (string, error) {
func strHasLen(str string, min, max int) bool {
return len(str) >= min && len(str) <= max
}
-
-// strSliceContains checks if a string is present in the string slice.
-func strSliceContains(str string, sl []string) bool {
- for _, s := range sl {
- if s == str {
- return true
- }
- }
-
- return false
-}
-
-func trimNullBytes(b []byte) string {
- return string(bytes.Trim(b, "\x00"))
-}
-
-func titleCase(input string) string {
- parts := strings.Fields(input)
- for n, p := range parts {
- parts[n] = cases.Title(language.Und).String(p)
- }
-
- return strings.Join(parts, " ")
-}