Skip to content

Commit

Permalink
Lint fixes and improvements.
Browse files Browse the repository at this point in the history
  • Loading branch information
bengarrett committed Apr 12, 2024
1 parent 70539d6 commit 739014a
Show file tree
Hide file tree
Showing 16 changed files with 256 additions and 266 deletions.
27 changes: 15 additions & 12 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# The .golangci.yaml file is used to configure the golangci-lint linter.
# A linter is a tool that analyzes source code to flag programming errors,
# A linter is a tool that analyzes source code to flag programming errors,
# bugs, stylistic errors, and suspicious constructs.
#
# https://golangci-lint.run/
Expand All @@ -21,15 +21,15 @@ linters:
- structcheck
- varcheck
# disabled
- depguard # overkill.
- depguard # overkill.
- exhaustive
- exhaustruct
- ireturn # conflicts with sqlboiler.
- nlreturn # fussy over whitespace.
- paralleltest # overkill.
- varnamelen # not idomatic?
- ireturn # conflicts with sqlboiler.
- nlreturn # fussy over whitespace.
- paralleltest # overkill.
- varnamelen # not idomatic?
- wrapcheck
- wsl # fussy over whitespace.
- wsl # fussy over whitespace.
# temporary disabled
#- godox
issues:
Expand Down Expand Up @@ -91,6 +91,9 @@ issues:
- gocognit
- lll
- tagalign
- path: internal/demozoo/demozoo.go
linters:
- tagliatelle
- path: internal/pouet/pouet.go
linters:
- tagliatelle
Expand Down Expand Up @@ -230,7 +233,7 @@ issues:
- path: internal/postgres/sql.go
linters:
- goconst

linters-settings:
cyclop:
# The maximal code complexity to report.
Expand All @@ -248,14 +251,14 @@ linters-settings:
# Values always ignored: `.+_test.go`
# Default: []
ignored-files: # magic number false positives.
- 'milestone.go'
- 'interview.go'
- 'zoo.go'
- "milestone.go"
- "interview.go"
- "zoo.go"
misspell:
# Correct spellings using locale preferences for US or UK.
# Setting locale to US will correct the British spelling of 'colour' to 'color'.
# Default is to use a neutral variety of English.
locale: US
# Default: []
ignore-words:
- 'Teh' # Teh Scene.
- "Teh" # Teh Scene.
30 changes: 17 additions & 13 deletions handler/app/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ const (
records = "records"
sep = ";"
txt = ".txt" // txt file extension
az = ", a-z"
byyear = ", by year"
alpha = "alphabetically"
year = "by year"
)

// ArtifactErr renders the error page for the artifact links.
Expand Down Expand Up @@ -276,7 +280,7 @@ func FTP(logr *zap.SugaredLogger, c echo.Context) error {
data[key] = r
data["stats"] = map[string]string{
"pubs": fmt.Sprintf("%d sites", len(r)),
"orderBy": "alphabetically",
"orderBy": alpha,
}
err = c.Render(http.StatusOK, name, data)
if err != nil {
Expand Down Expand Up @@ -2154,18 +2158,18 @@ func bbsHandler(logr *zap.SugaredLogger, c echo.Context, orderBy model.OrderBy)
var order string
switch orderBy {
case model.Alphabetical:
s := logo + ", a-z"
s := logo + az
data["logo"] = s
order = "alphabetically"
order = alpha
case model.Prolific:
s := logo + ", by count"
data["logo"] = s
order = "by file artifact count"
case model.Oldest:
tmpl = "bbs-year"
s := logo + ", by year"
s := logo + byyear
data["logo"] = s
order = "by year"
order = year
}
data["stats"] = map[string]string{
"pubs": fmt.Sprintf("%d boards", len(r)),
Expand Down Expand Up @@ -2353,16 +2357,16 @@ func magazines(logr *zap.SugaredLogger, c echo.Context, chronological bool) erro
if err := r.Magazine(ctx, db); err != nil {
return DatabaseErr(logr, c, name, err)
}
s := title + ", by year"
s := title + byyear
data["logo"] = s
order = "by year"
order = year
case false:
if err := r.MagazineAZ(ctx, db); err != nil {
return DatabaseErr(logr, c, name, err)
}
s := title + ", a-z"
s := title + az
data["logo"] = s
order = "alphabetically"
order = alpha
}
data[key] = r
data["stats"] = map[string]string{
Expand Down Expand Up @@ -2606,18 +2610,18 @@ func releasers(logr *zap.SugaredLogger, c echo.Context, orderBy model.OrderBy) e
var order string
switch orderBy {
case model.Alphabetical:
s := logo + ", a-z"
s := logo + az
data["logo"] = s
order = "alphabetically"
order = alpha
case model.Prolific:
s := logo + ", by count"
data["logo"] = s
order = "by file artifact count"
case model.Oldest:
tmpl = "releaser-year"
s := logo + ", by year"
s := logo + byyear
data["logo"] = s
order = "by year"
order = year
}
data["stats"] = map[string]string{
"pubs": fmt.Sprintf("%d releasers and groups", len(r)),
Expand Down
101 changes: 54 additions & 47 deletions handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"fmt"
"html/template"
"io"
"io/fs"
"maps"
"net"
"net/http"
Expand Down Expand Up @@ -70,75 +71,66 @@ type Configuration struct {

// Controller is the primary instance of the Echo router.
func (c Configuration) Controller() *echo.Echo {
logr := c.Logger
configs := c.Import

e := echo.New()
e.HideBanner = true
e.HTTPErrorHandler = c.Import.CustomErrorHandler
e.HTTPErrorHandler = configs.CustomErrorHandler

templates, err := c.Registry()
if err != nil {
logr.Fatal(err)
logger := c.Logger
if tmpl, err := c.Registry(); err != nil {
logger.Fatal(err)
} else {
e.Renderer = tmpl
}
e.Renderer = templates

e.Pre(
middlewares := []echo.MiddlewareFunc{
middleware.Rewrite(rewrites()),
// redirect www.defacto2.net requests to defacto2.net
middleware.NonWWWRedirect(),
)
httpsRedirect := c.Import.HTTPSRedirect && c.Import.TLSPort > 0
if httpsRedirect {
// redirect http://defacto2.net requests to https://defacto2.net
e.Pre(middleware.HTTPSRedirect())
}
// ********************************************************************************
// Middleware configurations note
// NEVER USE the middleware.Timeout()
// It is broken and should not be in the echo library as it causes server crashes.
// ********************************************************************************
e.Use(
// XSS cross-site scripting protection
}
if httpsRedirect := configs.HTTPSRedirect && configs.TLSPort > 0; httpsRedirect {
middlewares = append(middlewares, middleware.HTTPSRedirect())
}
e.Pre(middlewares...)

// *******************************************
// NOTEL: NEVER USE the middleware.Timeout()
// It is broken and should not be in the
// echo library as it causes server crashes.
// *******************************************
middlewares = []echo.MiddlewareFunc{
middleware.Secure(),
// custom HTTP logging middleware
middleware.RequestLoggerWithConfig(c.configZapLogger()),
// add X-Robots-Tag to all responses
c.NoCrawl,
// remove trailing slashes
middleware.RemoveTrailingSlashWithConfig(configRTS()),
)
logr.Info("Middleware configured.")
switch strings.ToLower(c.Import.Compression) {
}
switch strings.ToLower(configs.Compression) {
case "gzip":
e.Use(middleware.Gzip())
middlewares = append(middlewares, middleware.Gzip())
case "br":
e.Use(br.Brotli())
middlewares = append(middlewares, br.Brotli())
}
if c.Import.ProductionMode {
e.Use(middleware.Recover()) // recover from panics
if configs.ProductionMode {
middlewares = append(middlewares, middleware.Recover()) // recover from panics
}
// Static embedded web assets that get distributed in the binary
e = c.EmbedDirs(e)
// Routes for the web application
e, err = c.Moved(e)
if err != nil {
logr.Fatal(err)
}
e, err = c.Routes(e, c.Public)
e.Use(middlewares...)

e = EmbedDirs(e, c.Public)
e = MovedPermanently(e)
e = htmx.Routes(e, logger)
e, err := c.FilesRoutes(e, c.Public)
if err != nil {
logr.Fatal(err)
logger.Fatal(err)
}
e = htmx.Routes(logr, e)
// Routes for the retro web tables
old := html3.Routes(logr, e)
old.GET(Downloader, c.downloader)
group := html3.Routes(e, logger)
group.GET(Downloader, c.downloader)
return e
}

// EmbedDirs serves the static files from the directories embed to the binary.
func (c Configuration) EmbedDirs(e *echo.Echo) *echo.Echo {
func EmbedDirs(e *echo.Echo, currentFs fs.FS) *echo.Echo {
if e == nil {
c.Logger.Fatal(ErrRoutes)
panic(ErrRoutes)
}
dirs := map[string]string{
"/image/artpack": "public/image/artpack",
Expand All @@ -147,7 +139,7 @@ func (c Configuration) EmbedDirs(e *echo.Echo) *echo.Echo {
"/image/milestone": "public/image/milestone",
}
for path, fsRoot := range dirs {
e.StaticFS(path, echo.MustSubFS(c.Public, fsRoot))
e.StaticFS(path, echo.MustSubFS(currentFs, fsRoot))
e.GET(path, func(_ echo.Context) error {
return echo.NewHTTPError(http.StatusNotFound)
})
Expand Down Expand Up @@ -224,6 +216,9 @@ func (c Configuration) Registry() (*TemplateRegistry, error) {
// ShutdownHTTP waits for a Ctrl-C keyboard press to initiate a graceful shutdown of the HTTP web server.
// The shutdown procedure occurs a few seconds after the key press.
func (c *Configuration) ShutdownHTTP(e *echo.Echo) {
if e == nil {
panic(ErrRoutes)
}
// Wait for interrupt signal to gracefully shutdown the server
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
Expand Down Expand Up @@ -274,6 +269,9 @@ func (c *Configuration) ShutdownHTTP(e *echo.Echo) {

// Start the HTTP, and-or the TLS servers.
func (c *Configuration) Start(e *echo.Echo, configs config.Config) error {
if e == nil {
panic(ErrRoutes)
}
switch {
case configs.UseTLS() && configs.UseHTTP():
go func() {
Expand Down Expand Up @@ -301,6 +299,9 @@ func (c *Configuration) Start(e *echo.Echo, configs config.Config) error {

// StartHTTP starts the insecure HTTP web server.
func (c *Configuration) StartHTTP(e *echo.Echo) {
if e == nil {
panic(ErrRoutes)
}
port := c.Import.HTTPPort
if port == 0 {
return
Expand All @@ -313,6 +314,9 @@ func (c *Configuration) StartHTTP(e *echo.Echo) {

// StartTLS starts the encrypted TLS web server.
func (c *Configuration) StartTLS(e *echo.Echo) {
if e == nil {
panic(ErrRoutes)
}
port := c.Import.TLSPort
if port == 0 {
return
Expand All @@ -338,6 +342,9 @@ func (c *Configuration) StartTLS(e *echo.Echo) {
// StartTLSLocal starts the localhost, encrypted TLS web server.
// This should only be triggered when the server is running in local mode.
func (c *Configuration) StartTLSLocal(e *echo.Echo) {
if e == nil {
panic(ErrRoutes)
}
port := c.Import.TLSPort
if port == 0 {
return
Expand Down
15 changes: 8 additions & 7 deletions handler/html3/html3.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,14 @@ const (
)

var (
ErrConn = errors.New("the server cannot connect to the database")
ErrDB = errors.New("database value is nil")
ErrPage = errors.New("unknown records by type")
ErrSQL = errors.New("database connection problem or a SQL error")
ErrTag = errors.New("no database query was for the tag")
ErrTmpl = errors.New("the server could not render the HTML template for this page")
ErrZap = errors.New("zap logger is nil")
ErrConn = errors.New("the server cannot connect to the database")
ErrDB = errors.New("database value is nil")
ErrPage = errors.New("unknown records by type")
ErrRoutes = errors.New("echo instance is nil")
ErrSQL = errors.New("database connection problem or a SQL error")
ErrTag = errors.New("no database query was for the tag")
ErrTmpl = errors.New("the server could not render the HTML template for this page")
ErrZap = errors.New("zap logger is nil")
)

// Clauses for ordering file record queries.
Expand Down
8 changes: 5 additions & 3 deletions handler/html3/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ import (
// Routes for the /html3 sub-route group.
// Any errors are logged and rendered to the client using HTTP codes
// and the custom /html3, group errror template.
func Routes(logr *zap.SugaredLogger, e *echo.Echo) *echo.Group {
s := Sugared{Log: logr}

func Routes(e *echo.Echo, logger *zap.SugaredLogger) *echo.Group {
if e == nil {
panic(ErrRoutes)
}
s := Sugared{Log: logger}
g := e.Group(Prefix)
g.GET("", s.Index)
g.GET("/all:offset", s.All)
Expand Down
Loading

0 comments on commit 739014a

Please sign in to comment.