From b453e6b4002d2afd7e9507ef09e8dec63adfa354 Mon Sep 17 00:00:00 2001 From: Jan-Lukas Else Date: Tue, 22 Feb 2022 10:14:48 +0100 Subject: [PATCH] Activate more linters and fix linted problems --- .golangci.yml | 18 +++++++++++++++++- activityPub.go | 3 ++- authentication.go | 2 +- blogroll_test.go | 3 ++- captcha.go | 2 +- captcha_test.go | 4 +++- comments_test.go | 15 +++++---------- contact_test.go | 2 +- databaseHooks.go | 2 +- editor.go | 2 +- editor_test.go | 3 ++- feeds_test.go | 2 +- geoTiles.go | 2 +- geoTiles_test.go | 11 +++++++---- geoTrack.go | 2 +- http.go | 9 +++------ httpClient_test.go | 21 +++++++++++++++++++-- httpLogs_test.go | 9 ++------- httpMiddlewares_test.go | 4 +++- httpRouters.go | 4 ++-- indexnow_test.go | 8 +++++--- indieAuthServer_test.go | 3 +-- pkgs/maprouter/maprouter_test.go | 13 ++++--------- postsDb.go | 2 +- posts_test.go | 6 ++---- privateMode_test.go | 29 ++++++++--------------------- regexRedirects_test.go | 2 ++ sessions.go | 2 +- sitemap_test.go | 3 +-- templateAssets.go | 2 +- templateStrings.go | 2 +- tts.go | 8 ++++++-- ui_test.go | 3 +-- utils.go | 2 +- webmentionVerification.go | 21 ++++++++++++++------- 35 files changed, 124 insertions(+), 102 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 4f6b781..d79e883 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -8,5 +8,21 @@ run: - sqlite_fts5 linters: enable: + # Default linters + - deadcode + - errcheck + - gosimple + - govet + - ineffassign + - structcheck + - typecheck + - unused + - varcheck + # Other linters - dupl - - gofmt \ No newline at end of file + - gofmt + - bodyclose + - noctx + - prealloc + - unparam + - durationcheck \ No newline at end of file diff --git a/activityPub.go b/activityPub.go index d0972cb..7a0ea86 100644 --- a/activityPub.go +++ b/activityPub.go @@ -1,6 +1,7 @@ package main import ( + "context" "crypto/rand" "crypto/rsa" "crypto/x509" @@ -249,7 +250,7 @@ func handleWellKnownHostMeta(w http.ResponseWriter, r *http.Request) { } func (a *goBlog) apGetRemoteActor(iri string) (*asPerson, int, error) { - req, err := http.NewRequest(http.MethodGet, iri, nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, iri, nil) if err != nil { return nil, 0, err } diff --git a/authentication.go b/authentication.go index 4faf8f7..cc22e74 100644 --- a/authentication.go +++ b/authentication.go @@ -100,7 +100,7 @@ func (a *goBlog) checkLogin(w http.ResponseWriter, r *http.Request) bool { } // Prepare original request loginbody, _ := base64.StdEncoding.DecodeString(r.FormValue("loginbody")) - req, _ := http.NewRequest(r.FormValue("loginmethod"), r.RequestURI, bytes.NewReader(loginbody)) + req, _ := http.NewRequestWithContext(r.Context(), r.FormValue("loginmethod"), r.RequestURI, bytes.NewReader(loginbody)) // Copy original headers loginheaders, _ := base64.StdEncoding.DecodeString(r.FormValue("loginheaders")) var headers http.Header diff --git a/blogroll_test.go b/blogroll_test.go index a45af63..69a5549 100644 --- a/blogroll_test.go +++ b/blogroll_test.go @@ -2,6 +2,7 @@ package main import ( "context" + "net/http" "net/http/httptest" "path/filepath" "testing" @@ -46,7 +47,7 @@ func Test_blogroll(t *testing.T) { defer app.db.close() app.initComponents(false) - fc.setFakeResponse(200, ` + fc.setFakeResponse(http.StatusOK, ` Tue, 30 Nov 2021 19:34:38 UTC diff --git a/captcha.go b/captcha.go index 7c94213..b21aa5d 100644 --- a/captcha.go +++ b/captcha.go @@ -96,7 +96,7 @@ func (a *goBlog) checkCaptcha(w http.ResponseWriter, r *http.Request) bool { } // Decode and prepare original request captchabody, _ := base64.StdEncoding.DecodeString(r.FormValue("captchabody")) - origReq, _ := http.NewRequest(r.FormValue("captchamethod"), r.RequestURI, bytes.NewReader(captchabody)) + origReq, _ := http.NewRequestWithContext(r.Context(), r.FormValue("captchamethod"), r.RequestURI, bytes.NewReader(captchabody)) // Copy original headers captchaheaders, _ := base64.StdEncoding.DecodeString(r.FormValue("captchaheaders")) var headers http.Header diff --git a/captcha_test.go b/captcha_test.go index f1ae547..345c5d8 100644 --- a/captcha_test.go +++ b/captcha_test.go @@ -55,9 +55,11 @@ func Test_captchaMiddleware(t *testing.T) { session.Values["captcha"] = true _ = session.Save(req, rec1) - for _, cookie := range rec1.Result().Cookies() { + res1 := rec1.Result() + for _, cookie := range res1.Cookies() { req.AddCookie(cookie) } + _ = res1.Body.Close() rec2 := httptest.NewRecorder() diff --git a/comments_test.go b/comments_test.go index 3814888..b82463d 100644 --- a/comments_test.go +++ b/comments_test.go @@ -2,7 +2,6 @@ package main import ( "context" - "io" "net/http" "net/http/httptest" "net/url" @@ -57,9 +56,9 @@ func Test_comments(t *testing.T) { app.createComment(rec, req.WithContext(context.WithValue(req.Context(), blogKey, "en"))) res := rec.Result() - assert.Equal(t, http.StatusFound, res.StatusCode) assert.Equal(t, "/comment/1", res.Header.Get("Location")) + _ = res.Body.Close() // View comment @@ -72,11 +71,9 @@ func Test_comments(t *testing.T) { mux.ServeHTTP(rec, req) - res = rec.Result() - resBody, _ := io.ReadAll(res.Body) - resBodyStr := string(resBody) + resBodyStr := rec.Body.String() - assert.Equal(t, http.StatusOK, res.StatusCode) + assert.Equal(t, http.StatusOK, rec.Code) assert.Contains(t, resBodyStr, "https://goblog.app") assert.Contains(t, resBodyStr, "Test name") assert.Contains(t, resBodyStr, "This is just a test") @@ -128,9 +125,9 @@ func Test_comments(t *testing.T) { app.createComment(rec, req.WithContext(context.WithValue(req.Context(), blogKey, "en"))) res := rec.Result() - assert.Equal(t, http.StatusFound, res.StatusCode) assert.Equal(t, "/comment/2", res.Header.Get("Location")) + _ = res.Body.Close() // Get comment @@ -163,9 +160,7 @@ func Test_comments(t *testing.T) { app.createComment(rec, req.WithContext(context.WithValue(req.Context(), blogKey, "en"))) - res := rec.Result() - - assert.Equal(t, http.StatusBadRequest, res.StatusCode) + assert.Equal(t, http.StatusBadRequest, rec.Code) cc, err := app.db.countComments(&commentsRequestConfig{}) require.NoError(t, err) diff --git a/contact_test.go b/contact_test.go index 1735140..74d60d5 100644 --- a/contact_test.go +++ b/contact_test.go @@ -65,7 +65,7 @@ func Test_contact(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "/contact", strings.NewReader(data.Encode())) req.Header.Add(contentType, contenttype.WWWForm) app.sendContactSubmission(rec, req.WithContext(context.WithValue(req.Context(), blogKey, "en"))) - require.Equal(t, http.StatusOK, rec.Result().StatusCode) + require.Equal(t, http.StatusOK, rec.Code) // Check sent mail assert.Contains(t, rd.Usernames, "user") diff --git a/databaseHooks.go b/databaseHooks.go index 07c0497..0b24d2f 100644 --- a/databaseHooks.go +++ b/databaseHooks.go @@ -13,7 +13,7 @@ import ( const dbHooksBegin contextKey = "begin" -func (db *database) dbBefore(ctx context.Context, query string, args ...interface{}) context.Context { +func (db *database) dbBefore(ctx context.Context, _ string, _ ...interface{}) context.Context { if !db.debug { return ctx } diff --git a/editor.go b/editor.go index cda4f4b..9f50165 100644 --- a/editor.go +++ b/editor.go @@ -106,7 +106,7 @@ func (a *goBlog) serveEditorPost(w http.ResponseWriter, r *http.Request) { }) _ = pipeWriter.CloseWithError(writeErr) }() - req, err := http.NewRequest(http.MethodPost, "", pipeReader) + req, err := http.NewRequestWithContext(r.Context(), http.MethodPost, "", pipeReader) if err != nil { a.serveError(w, r, err.Error(), http.StatusInternalServerError) return diff --git a/editor_test.go b/editor_test.go index d8ed9d3..ec1ae68 100644 --- a/editor_test.go +++ b/editor_test.go @@ -25,8 +25,9 @@ func Test_editorPreview(t *testing.T) { }) d := wstest.NewDialer(h) - c, _, err := d.Dial("ws://example.com/editor/preview", nil) + c, resp, err := d.Dial("ws://example.com/editor/preview", nil) require.NoError(t, err) + defer resp.Body.Close() require.NotNil(t, c) err = c.WriteMessage(websocket.TextMessage, []byte("---\ntitle: Title\nsection: posts\n---\nContent.")) diff --git a/feeds_test.go b/feeds_test.go index dfd7cc9..296eb9d 100644 --- a/feeds_test.go +++ b/feeds_test.go @@ -19,7 +19,7 @@ func Test_feeds(t *testing.T) { _ = app.initDatabase(false) defer app.db.close() app.initComponents(false) - app.d, _ = app.buildRouter() + app.d = app.buildRouter() handlerClient := newHandlerClient(app.d) err := app.createPost(&post{ diff --git a/geoTiles.go b/geoTiles.go index c5b0b93..f16d2ab 100644 --- a/geoTiles.go +++ b/geoTiles.go @@ -8,7 +8,7 @@ import ( "github.com/go-chi/chi/v5" ) -func (a *goBlog) proxyTiles(basePath string) http.HandlerFunc { +func (a *goBlog) proxyTiles() http.HandlerFunc { tileSource := "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" if c := a.cfg.MapTiles; c != nil && c.Source != "" { tileSource = c.Source diff --git a/geoTiles_test.go b/geoTiles_test.go index 0381ce0..c977e4f 100644 --- a/geoTiles_test.go +++ b/geoTiles_test.go @@ -1,6 +1,7 @@ package main import ( + "context" "net/http" "testing" @@ -23,12 +24,13 @@ func Test_proxyTiles(t *testing.T) { // Default tile source m := chi.NewMux() - m.Get("/-/tiles/{s}/{z}/{x}/{y}.png", app.proxyTiles("/-/tiles")) + m.Get("/-/tiles/{s}/{z}/{x}/{y}.png", app.proxyTiles()) - req, err := http.NewRequest(http.MethodGet, "https://example.org/-/tiles/c/8/134/84.png", nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://example.org/-/tiles/c/8/134/84.png", nil) require.NoError(t, err) resp, err := doHandlerRequest(req, m) require.NoError(t, err) + _ = resp.Body.Close() assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, "https://c.tile.openstreetmap.org/8/134/84.png", hc.req.URL.String()) @@ -40,12 +42,13 @@ func Test_proxyTiles(t *testing.T) { } m = chi.NewMux() - m.Get("/-/tiles/{s}/{z}/{x}/{y}.png", app.proxyTiles("/-/tiles")) + m.Get("/-/tiles/{s}/{z}/{x}/{y}.png", app.proxyTiles()) - req, err = http.NewRequest(http.MethodGet, "https://example.org/-/tiles/c/8/134/84.png", nil) + req, err = http.NewRequestWithContext(context.Background(), http.MethodGet, "https://example.org/-/tiles/c/8/134/84.png", nil) require.NoError(t, err) resp, err = doHandlerRequest(req, m) require.NoError(t, err) + _ = resp.Body.Close() assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, "https://c.tile.opentopomap.org/8/134/84.png", hc.req.URL.String()) diff --git a/geoTrack.go b/geoTrack.go index f40dbfe..1aafd0b 100644 --- a/geoTrack.go +++ b/geoTrack.go @@ -107,7 +107,7 @@ func trackParseGPX(gpxString string) (result *trackParseResult, err error) { return nil, err } - var paths []*trackPath + paths := make([]*trackPath, 0) for _, track := range result.gpxData.Tracks { for _, segment := range track.Segments { md := segment.MovingData() diff --git a/http.go b/http.go index ef4e7db..26ca444 100644 --- a/http.go +++ b/http.go @@ -32,10 +32,7 @@ const ( func (a *goBlog) startServer() (err error) { log.Println("Start server(s)...") // Load router - a.d, err = a.buildRouter() - if err != nil { - return err - } + a.d = a.buildRouter() // Set basic middlewares h := alice.New() h = h.Append(middleware.Heartbeat("/ping")) @@ -115,7 +112,7 @@ const ( feedPath = ".{feed:(rss|json|atom)}" ) -func (a *goBlog) buildRouter() (http.Handler, error) { +func (a *goBlog) buildRouter() http.Handler { mapRouter := &maprouter.MapRouter{ Handlers: map[string]http.Handler{}, } @@ -221,7 +218,7 @@ func (a *goBlog) buildRouter() (http.Handler, error) { r.MethodNotAllowed(a.serveNotAllowed) mapRouter.DefaultHandler = r - return alice.New(headAsGetHandler).Then(mapRouter), nil + return alice.New(headAsGetHandler).Then(mapRouter) } func (a *goBlog) servePostsAliasesRedirects() http.HandlerFunc { diff --git a/httpClient_test.go b/httpClient_test.go index 7b71d9e..3d1a6f3 100644 --- a/httpClient_test.go +++ b/httpClient_test.go @@ -1,10 +1,14 @@ package main import ( + "context" "io" "net/http" "net/http/httptest" "sync" + "testing" + + "github.com/stretchr/testify/require" ) type fakeHttpClient struct { @@ -24,14 +28,17 @@ func newFakeHttpClient() *fakeHttpClient { if fc.handler != nil { rec := httptest.NewRecorder() fc.handler.ServeHTTP(rec, r) - fc.res = rec.Result() + res := rec.Result() + fc.res = res // Copy the headers from the response recorder for k, v := range rec.Header() { rw.Header()[k] = v } // Copy result status code and body - rw.WriteHeader(fc.res.StatusCode) + rw.WriteHeader(rec.Code) _, _ = io.Copy(rw, rec.Body) + // Close response body + _ = res.Body.Close() } })) return fc @@ -58,3 +65,13 @@ func (c *fakeHttpClient) setFakeResponse(statusCode int, body string) { _, _ = rw.Write([]byte(body)) })) } + +func Test_fakeHttpClient(t *testing.T) { + fc := newFakeHttpClient() + fc.setFakeResponse(http.StatusNotFound, "Not found") + req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://localhost:8080/", nil) + resp, err := fc.Client.Do(req) + require.NoError(t, err) + require.Equal(t, http.StatusNotFound, resp.StatusCode) + _ = resp.Body.Close() +} diff --git a/httpLogs_test.go b/httpLogs_test.go index fefd00f..a41b0d8 100644 --- a/httpLogs_test.go +++ b/httpLogs_test.go @@ -1,7 +1,6 @@ package main import ( - "io" "net/http" "net/http/httptest" "os" @@ -66,12 +65,8 @@ func Test_httpLogs(t *testing.T) { // Check response - res := rec.Result() - resBody, _ := io.ReadAll(res.Body) - resBodyStr := string(resBody) - - assert.Equal(t, http.StatusOK, res.StatusCode) - assert.Contains(t, resBodyStr, "Test") + assert.Equal(t, http.StatusOK, rec.Code) + assert.Contains(t, rec.Body.String(), "Test") // Check log diff --git a/httpMiddlewares_test.go b/httpMiddlewares_test.go index 9130dfe..5040f14 100644 --- a/httpMiddlewares_test.go +++ b/httpMiddlewares_test.go @@ -17,7 +17,9 @@ func Test_noIndexHeader(t *testing.T) { rec := httptest.NewRecorder() h.ServeHTTP(rec, req) - assert.Equal(t, "noindex", rec.Result().Header.Get("X-Robots-Tag")) + res := rec.Result() + _ = res.Body.Close() + assert.Equal(t, "noindex", res.Header.Get("X-Robots-Tag")) } func Test_fixHTTPHandler(t *testing.T) { diff --git a/httpRouters.go b/httpRouters.go index 2b5428d..834cae4 100644 --- a/httpRouters.go +++ b/httpRouters.go @@ -99,7 +99,7 @@ func (a *goBlog) mediaFilesRouter(r chi.Router) { // Various other routes func (a *goBlog) otherRoutesRouter(r chi.Router) { r.Use(a.privateModeHandler) - r.Get("/tiles/{s}/{z}/{x}/{y}.png", a.proxyTiles("/-/tiles")) + r.Get("/tiles/{s}/{z}/{x}/{y}.png", a.proxyTiles()) r.With(cacheLoggedIn, a.cacheMiddleware).HandleFunc("/leaflet/*", a.serveFs(leafletFiles, "/-/")) } @@ -311,7 +311,7 @@ func (a *goBlog) blogOnThisDayRouter(conf *configBlog) func(r chi.Router) { } // Blog - Editor -func (a *goBlog) blogEditorRouter(conf *configBlog) func(r chi.Router) { +func (a *goBlog) blogEditorRouter(_ *configBlog) func(r chi.Router) { return func(r chi.Router) { r.Use(a.authMiddleware) r.Get("/", a.serveEditor) diff --git a/indexnow_test.go b/indexnow_test.go index 2fe5f82..0673e57 100644 --- a/indexnow_test.go +++ b/indexnow_test.go @@ -1,6 +1,7 @@ package main import ( + "context" "io" "net/http" "testing" @@ -11,7 +12,7 @@ import ( func Test_indexNow(t *testing.T) { fc := newFakeHttpClient() - fc.setFakeResponse(200, "OK") + fc.setFakeResponse(http.StatusOK, "OK") app := &goBlog{ cfg: createDefaultTestConfig(t), @@ -24,15 +25,16 @@ func Test_indexNow(t *testing.T) { app.initComponents(false) // Create http router - app.d, _ = app.buildRouter() + app.d = app.buildRouter() // Check key require.NotEmpty(t, app.inKey) - req, _ := http.NewRequest("GET", "http://localhost:8080/"+app.inKey+".txt", nil) + req, _ := http.NewRequestWithContext(context.Background(), "GET", "http://localhost:8080/"+app.inKey+".txt", nil) res, err := doHandlerRequest(req, app.d) require.NoError(t, err) require.Equal(t, 200, res.StatusCode) body, _ := io.ReadAll(res.Body) + _ = res.Body.Close() require.Equal(t, app.inKey, string(body)) // Test publish post diff --git a/indieAuthServer_test.go b/indieAuthServer_test.go index 6e793b9..2243923 100644 --- a/indieAuthServer_test.go +++ b/indieAuthServer_test.go @@ -45,8 +45,7 @@ func Test_indieAuthServer(t *testing.T) { }, } - app.d, err = app.buildRouter() - require.NoError(t, err) + app.d = app.buildRouter() _ = app.initDatabase(false) defer app.db.close() diff --git a/pkgs/maprouter/maprouter_test.go b/pkgs/maprouter/maprouter_test.go index e6b3a2b..0289649 100644 --- a/pkgs/maprouter/maprouter_test.go +++ b/pkgs/maprouter/maprouter_test.go @@ -1,7 +1,6 @@ package maprouter import ( - "io" "net/http" "net/http/httptest" "testing" @@ -27,20 +26,17 @@ func TestMapRouter(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "http://a.example.org", nil) rec := httptest.NewRecorder() router.ServeHTTP(rec, req) - resBody, _ := io.ReadAll(rec.Result().Body) - assert.Equal(t, "a", string(resBody)) + assert.Equal(t, "a", rec.Body.String()) req = httptest.NewRequest(http.MethodGet, "http://b.example.org", nil) rec = httptest.NewRecorder() router.ServeHTTP(rec, req) - resBody, _ = io.ReadAll(rec.Result().Body) - assert.Equal(t, "b", string(resBody)) + assert.Equal(t, "b", rec.Body.String()) req = httptest.NewRequest(http.MethodGet, "http://c.example.org", nil) rec = httptest.NewRecorder() router.ServeHTTP(rec, req) - resBody, _ = io.ReadAll(rec.Result().Body) - assert.Equal(t, "Default", string(resBody)) + assert.Equal(t, "Default", rec.Body.String()) router.KeyFunc = func(r *http.Request) string { return "a.example.org" @@ -49,6 +45,5 @@ func TestMapRouter(t *testing.T) { req = httptest.NewRequest(http.MethodGet, "http://c.example.org", nil) rec = httptest.NewRecorder() router.ServeHTTP(rec, req) - resBody, _ = io.ReadAll(rec.Result().Body) - assert.Equal(t, "a", string(resBody)) + assert.Equal(t, "a", rec.Body.String()) } diff --git a/postsDb.go b/postsDb.go index b971659..02d137e 100644 --- a/postsDb.go +++ b/postsDb.go @@ -457,7 +457,7 @@ func (d *database) loadPostParameters(posts []*post, parameters ...string) (err return nil } // Build query - var sqlArgs []interface{} + sqlArgs := make([]interface{}, 0) var queryBuilder strings.Builder queryBuilder.WriteString("select path, parameter, value from post_parameters where") // Paths diff --git a/posts_test.go b/posts_test.go index 53fb871..c535cd0 100644 --- a/posts_test.go +++ b/posts_test.go @@ -21,8 +21,7 @@ func Test_serveDate(t *testing.T) { defer app.db.close() app.initComponents(false) - app.d, err = app.buildRouter() - require.NoError(t, err) + app.d = app.buildRouter() err = app.createPost(&post{ Path: "/testpost", @@ -112,8 +111,7 @@ func Test_servePost(t *testing.T) { defer app.db.close() app.initComponents(false) - app.d, err = app.buildRouter() - require.NoError(t, err) + app.d = app.buildRouter() // Create a post err = app.createPost(&post{ diff --git a/privateMode_test.go b/privateMode_test.go index ef4e73c..9fd73ce 100644 --- a/privateMode_test.go +++ b/privateMode_test.go @@ -1,7 +1,6 @@ package main import ( - "io" "net/http" "net/http/httptest" "path/filepath" @@ -65,12 +64,8 @@ func Test_privateMode(t *testing.T) { handler.ServeHTTP(rec, req) - res := rec.Result() - resBody, _ := io.ReadAll(res.Body) - resBodyStr := string(resBody) - - assert.Equal(t, http.StatusOK, res.StatusCode) - assert.Equal(t, "Awesome", resBodyStr) + assert.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, "Awesome", rec.Body.String()) // Test unauthenticated request @@ -79,14 +74,10 @@ func Test_privateMode(t *testing.T) { handler.ServeHTTP(rec, req) - res = rec.Result() - resBody, _ = io.ReadAll(res.Body) - resBodyStr = string(resBody) - - assert.Equal(t, http.StatusOK, res.StatusCode) // Not 401, to be compatible with some apps - assert.NotEqual(t, "Awesome", resBodyStr) - assert.NotContains(t, resBodyStr, "Awesome") - assert.Contains(t, resBodyStr, "Login") + assert.Equal(t, http.StatusOK, rec.Code) // Not 401, to be compatible with some apps + assert.NotEqual(t, "Awesome", rec.Body.String()) + assert.NotContains(t, rec.Body.String(), "Awesome") + assert.Contains(t, rec.Body.String(), "Login") // Disable private mode @@ -97,11 +88,7 @@ func Test_privateMode(t *testing.T) { handler.ServeHTTP(rec, req) - res = rec.Result() - resBody, _ = io.ReadAll(res.Body) - resBodyStr = string(resBody) - - assert.Equal(t, http.StatusOK, res.StatusCode) - assert.Equal(t, "Awesome", resBodyStr) + assert.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, "Awesome", rec.Body.String()) } diff --git a/regexRedirects_test.go b/regexRedirects_test.go index 12e7880..6b1cf6a 100644 --- a/regexRedirects_test.go +++ b/regexRedirects_test.go @@ -42,6 +42,7 @@ func Test_regexRedirects(t *testing.T) { h.ServeHTTP(rec, req) res := rec.Result() + _ = res.Body.Close() assert.Equal(t, 301, res.StatusCode) assert.Equal(t, "/posts.rss", res.Header.Get("Location")) @@ -54,6 +55,7 @@ func Test_regexRedirects(t *testing.T) { h.ServeHTTP(rec, req) res := rec.Result() + _ = res.Body.Close() assert.Equal(t, http.StatusFound, res.StatusCode) assert.Equal(t, "/def/test", res.Header.Get("Location")) diff --git a/sessions.go b/sessions.go index 10de885..eba51d7 100644 --- a/sessions.go +++ b/sessions.go @@ -96,7 +96,7 @@ func (s *dbSessionStore) Save(r *http.Request, w http.ResponseWriter, ss *sessio return nil } -func (s *dbSessionStore) Delete(r *http.Request, w http.ResponseWriter, session *sessions.Session) error { +func (s *dbSessionStore) Delete(_ *http.Request, w http.ResponseWriter, session *sessions.Session) error { options := *session.Options options.MaxAge = -1 http.SetCookie(w, sessions.NewCookie(session.Name(), "", &options)) diff --git a/sitemap_test.go b/sitemap_test.go index a65ec7e..da84707 100644 --- a/sitemap_test.go +++ b/sitemap_test.go @@ -21,8 +21,7 @@ func Test_sitemap(t *testing.T) { defer app.db.close() app.initComponents(false) - app.d, err = app.buildRouter() - require.NoError(t, err) + app.d = app.buildRouter() err = app.createPost(&post{ Path: "/testpost", diff --git a/templateAssets.go b/templateAssets.go index 63c937b..e236aad 100644 --- a/templateAssets.go +++ b/templateAssets.go @@ -84,7 +84,7 @@ func (a *goBlog) assetFileName(fileName string) string { } func (a *goBlog) allAssetPaths() []string { - var paths []string + paths := make([]string, 0) for _, name := range a.assetFileNames { paths = append(paths, "/"+name) } diff --git a/templateStrings.go b/templateStrings.go index f380834..bff60c7 100644 --- a/templateStrings.go +++ b/templateStrings.go @@ -10,7 +10,7 @@ import ( var stringsFiles embed.FS func (a *goBlog) initTemplateStrings() (err error) { - var blogLangs []string + blogLangs := make([]string, 0) for _, b := range a.cfg.Blogs { blogLangs = append(blogLangs, b.Lang) } diff --git a/tts.go b/tts.go index 3ebce24..16e2cdc 100644 --- a/tts.go +++ b/tts.go @@ -46,7 +46,9 @@ func (a *goBlog) initTTS() { a.pUndeleteHooks = append(a.pUndeleteHooks, createOrUpdate) a.pDeleteHooks = append(a.pDeleteHooks, func(p *post) { // Try to delete the audio file - _ = a.deletePostTTSAudio(p) + if a.deletePostTTSAudio(p) { + log.Println("deleted tts audio for", p.Path) + } }) } @@ -125,7 +127,9 @@ func (a *goBlog) createPostTTSAudio(p *post) error { if old := p.firstParameter(ttsParameter); old != "" && old != loc { // Already has tts audio, but with different location // Try to delete the old audio file - _ = a.deletePostTTSAudio(p) + if a.deletePostTTSAudio(p) { + log.Println("deleted old tts audio for", p.Path) + } } // Set post parameter diff --git a/ui_test.go b/ui_test.go index fe9be72..99d9746 100644 --- a/ui_test.go +++ b/ui_test.go @@ -78,8 +78,7 @@ func Test_renderInteractions(t *testing.T) { _ = app.initDatabase(false) defer app.db.close() app.initComponents(false) - app.d, err = app.buildRouter() - require.NoError(t, err) + app.d = app.buildRouter() err = app.createPost(&post{ Path: "/testpost1", diff --git a/utils.go b/utils.go index 8e85f5e..3c0f02c 100644 --- a/utils.go +++ b/utils.go @@ -91,7 +91,7 @@ func resolveURLReferences(base string, refs ...string) ([]string, error) { if err != nil { return nil, err } - var urls []string + urls := make([]string, 0) for _, r := range refs { u, err := url.Parse(r) if err != nil { diff --git a/webmentionVerification.go b/webmentionVerification.go index 7819534..c4fbddd 100644 --- a/webmentionVerification.go +++ b/webmentionVerification.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "context" "encoding/gob" "errors" "fmt" @@ -62,7 +63,7 @@ func (a *goBlog) queueMention(m *mention) error { func (a *goBlog) verifyMention(m *mention) error { // Request target - targetReq, err := http.NewRequest(http.MethodGet, m.Target, nil) + targetReq, err := http.NewRequestWithContext(context.Background(), http.MethodGet, m.Target, nil) if err != nil { return err } @@ -72,6 +73,7 @@ func (a *goBlog) verifyMention(m *mention) error { if err != nil { return err } + _ = targetResp.Body.Close() // Check if target has a valid status code if targetResp.StatusCode != http.StatusOK { if a.cfg.Debug { @@ -86,7 +88,7 @@ func (a *goBlog) verifyMention(m *mention) error { } } // Request source - sourceReq, err := http.NewRequest(http.MethodGet, m.Source, nil) + sourceReq, err := http.NewRequestWithContext(context.Background(), http.MethodGet, m.Source, nil) if err != nil { return err } @@ -96,12 +98,17 @@ func (a *goBlog) verifyMention(m *mention) error { (a.cfg.Server.ShortPublicAddress != "" && strings.HasPrefix(m.Source, a.cfg.Server.ShortPublicAddress)) { setLoggedIn(sourceReq, true) sourceResp, err = doHandlerRequest(sourceReq, a.getAppRouter()) + if err != nil { + return err + } + defer sourceResp.Body.Close() } else { sourceReq.Header.Set(userAgent, appUserAgent) sourceResp, err = a.httpClient.Do(sourceReq) - } - if err != nil { - return err + if err != nil { + return err + } + defer sourceResp.Body.Close() } // Check if source has a valid status code if sourceResp.StatusCode != http.StatusOK { @@ -118,7 +125,6 @@ func (a *goBlog) verifyMention(m *mention) error { } // Parse response body err = a.verifyReader(m, sourceResp.Body) - _ = sourceResp.Body.Close() if err != nil { if a.cfg.Debug { a.debug(fmt.Sprintf("Delete webmention because verifying %s threw error: %s", m.Source, err.Error())) @@ -176,7 +182,7 @@ func (a *goBlog) verifyReader(m *mention, body io.Reader) error { return false } // Check if link is or redirects to target - req, err := http.NewRequest(http.MethodGet, m.Target, nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, m.Target, nil) if err != nil { return false } @@ -186,6 +192,7 @@ func (a *goBlog) verifyReader(m *mention, body io.Reader) error { if err != nil { return false } + _ = resp.Body.Close() if resp.StatusCode == http.StatusOK && unescapedPath(resp.Request.URL.String()) == unescapedPath(defaultIfEmpty(m.NewTarget, m.Target)) { return true }