Activate more linters and fix linted problems

pull/25/head
Jan-Lukas Else 7 months ago
parent 505641170e
commit b453e6b400
  1. 18
      .golangci.yml
  2. 3
      activityPub.go
  3. 2
      authentication.go
  4. 3
      blogroll_test.go
  5. 2
      captcha.go
  6. 4
      captcha_test.go
  7. 15
      comments_test.go
  8. 2
      contact_test.go
  9. 2
      databaseHooks.go
  10. 2
      editor.go
  11. 3
      editor_test.go
  12. 2
      feeds_test.go
  13. 2
      geoTiles.go
  14. 11
      geoTiles_test.go
  15. 2
      geoTrack.go
  16. 9
      http.go
  17. 21
      httpClient_test.go
  18. 9
      httpLogs_test.go
  19. 4
      httpMiddlewares_test.go
  20. 4
      httpRouters.go
  21. 8
      indexnow_test.go
  22. 3
      indieAuthServer_test.go
  23. 13
      pkgs/maprouter/maprouter_test.go
  24. 2
      postsDb.go
  25. 6
      posts_test.go
  26. 29
      privateMode_test.go
  27. 2
      regexRedirects_test.go
  28. 2
      sessions.go
  29. 3
      sitemap_test.go
  30. 2
      templateAssets.go
  31. 2
      templateStrings.go
  32. 8
      tts.go
  33. 3
      ui_test.go
  34. 2
      utils.go
  35. 21
      webmentionVerification.go

@ -8,5 +8,21 @@ run:
- sqlite_fts5
linters:
enable:
# Default linters
- deadcode
- errcheck
- gosimple
- govet
- ineffassign
- structcheck
- typecheck
- unused
- varcheck
# Other linters
- dupl
- gofmt
- gofmt
- bodyclose
- noctx
- prealloc
- unparam
- durationcheck

@ -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
}

@ -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

@ -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, `
<opml version="2.0">
<head>
<dateCreated>Tue, 30 Nov 2021 19:34:38 UTC</dateCreated>

@ -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

@ -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()

@ -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)

@ -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")

@ -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
}

@ -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

@ -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."))

@ -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{

@ -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

@ -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())

@ -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()

@ -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 {

@ -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()
}

@ -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

@ -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) {

@ -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)

@ -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

@ -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()

@ -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())
}

@ -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

@ -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{

@ -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())
}

@ -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"))

@ -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))

@ -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",

@ -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)
}

@ -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)
}

@ -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

@ -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",

@ -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 {

@ -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
}

Loading…
Cancel
Save