From 94dba7a9b8e94f71b35d32276446aa0a207cb229 Mon Sep 17 00:00:00 2001 From: Jan-Lukas Else Date: Fri, 25 Feb 2022 16:29:42 +0100 Subject: [PATCH] Fix some issues discovered by linting --- app.go | 4 ++-- contact.go | 2 +- editor.go | 2 +- http.go | 4 ++-- indexnow.go | 24 +++++++++--------------- indexnow_test.go | 6 +++--- indieAuth.go | 5 +---- media.go | 2 +- mediaCompression.go | 2 +- micropub.go | 2 +- micropubMedia.go | 2 +- nodeinfo.go | 31 +++++++++++++++++++++++-------- pkgs/mocksmtp/backend.go | 4 ++-- robotstxt.go | 2 +- sessions.go | 2 +- sitemap.go | 2 +- 16 files changed, 51 insertions(+), 45 deletions(-) diff --git a/app.go b/app.go index a916fca..890a13f 100644 --- a/app.go +++ b/app.go @@ -54,8 +54,8 @@ type goBlog struct { // HTTP Routers d http.Handler // IndexNow - inKey string - inLoad singleflight.Group + inKey []byte + inLoad sync.Once // IndieAuth ias *indieauth.Server // Logs diff --git a/contact.go b/contact.go index b94974d..943783a 100644 --- a/contact.go +++ b/contact.go @@ -71,7 +71,7 @@ func (a *goBlog) sendContactSubmission(w http.ResponseWriter, r *http.Request) { }) } -func (a *goBlog) sendContactEmail(cc *configContact, body, replyTo string) error { +func (*goBlog) sendContactEmail(cc *configContact, body, replyTo string) error { // Check required config if cc == nil || cc.SMTPHost == "" || cc.EmailFrom == "" || cc.EmailTo == "" { return fmt.Errorf("email not send as config is missing") diff --git a/editor.go b/editor.go index b8625ed..ff9c5be 100644 --- a/editor.go +++ b/editor.go @@ -176,7 +176,7 @@ func (a *goBlog) editorMicropubPost(w http.ResponseWriter, r *http.Request, medi _ = result.Body.Close() } -func (a *goBlog) editorPostTemplate(blog string, bc *configBlog) string { +func (*goBlog) editorPostTemplate(blog string, bc *configBlog) string { builder := bufferpool.Get() defer bufferpool.Put(builder) marsh := func(param string, i interface{}) { diff --git a/http.go b/http.go index 26ca444..747f2c0 100644 --- a/http.go +++ b/http.go @@ -200,8 +200,8 @@ func (a *goBlog) buildRouter() http.Handler { // IndexNow if a.indexNowEnabled() { - if inkey := a.indexNowKey(); inkey != "" { - r.With(cacheLoggedIn, a.cacheMiddleware).Get("/"+inkey+".txt", a.serveIndexNow) + if inkey := a.indexNowKey(); len(inkey) > 0 { + r.With(cacheLoggedIn, a.cacheMiddleware).Get("/"+string(inkey)+".txt", a.serveIndexNow) } } diff --git a/indexnow.go b/indexnow.go index ee1e447..15e4b3e 100644 --- a/indexnow.go +++ b/indexnow.go @@ -2,7 +2,6 @@ package main import ( "context" - "io" "log" "net/http" @@ -43,7 +42,7 @@ func (a *goBlog) indexNowEnabled() bool { } func (a *goBlog) serveIndexNow(w http.ResponseWriter, r *http.Request) { - _, _ = io.WriteString(w, a.indexNowKey()) + _, _ = w.Write(a.indexNowKey()) } func (a *goBlog) indexNow(url string) { @@ -51,7 +50,7 @@ func (a *goBlog) indexNow(url string) { return } key := a.indexNowKey() - if key == "" { + if len(key) == 0 { log.Println("Skipping IndexNow") return } @@ -59,7 +58,7 @@ func (a *goBlog) indexNow(url string) { Client(a.httpClient). UserAgent(appUserAgent). Param("url", url). - Param("key", key). + Param("key", string(key)). Fetch(context.Background()) if err != nil { log.Println("Sending IndexNow request failed:", err.Error()) @@ -69,17 +68,13 @@ func (a *goBlog) indexNow(url string) { } } -func (a *goBlog) indexNowKey() string { - res, _, _ := a.inLoad.Do("", func() (interface{}, error) { - // Check if already loaded - if a.inKey != "" { - return a.inKey, nil - } +func (a *goBlog) indexNowKey() []byte { + a.inLoad.Do(func() { // Try to load key from database keyBytes, err := a.db.retrievePersistentCache("indexnowkey") if err != nil { log.Println("Failed to retrieve cached IndexNow key:", err.Error()) - return "", err + return } if keyBytes == nil { // Generate 128 character key with hexadecimal characters @@ -88,11 +83,10 @@ func (a *goBlog) indexNowKey() string { err = a.db.cachePersistently("indexnowkey", keyBytes) if err != nil { log.Println("Failed to cache IndexNow key:", err.Error()) - return "", err + return } } - a.inKey = string(keyBytes) - return a.inKey, nil + a.inKey = keyBytes }) - return res.(string) + return a.inKey } diff --git a/indexnow_test.go b/indexnow_test.go index 0673e57..dbbc59a 100644 --- a/indexnow_test.go +++ b/indexnow_test.go @@ -29,13 +29,13 @@ func Test_indexNow(t *testing.T) { // Check key require.NotEmpty(t, app.inKey) - req, _ := http.NewRequestWithContext(context.Background(), "GET", "http://localhost:8080/"+app.inKey+".txt", nil) + req, _ := http.NewRequestWithContext(context.Background(), "GET", "http://localhost:8080/"+string(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)) + require.Equal(t, app.inKey, body) // Test publish post _ = app.createPost(&post{ @@ -54,5 +54,5 @@ func Test_indexNow(t *testing.T) { fc.mu.Unlock() // Check fake http client - require.Equal(t, "https://api.indexnow.org/indexnow?key="+app.inKey+"&url=http%3A%2F%2Flocalhost%3A8080%2Ftestpost", fc.req.URL.String()) + require.Equal(t, "https://api.indexnow.org/indexnow?key="+string(app.inKey)+"&url=http%3A%2F%2Flocalhost%3A8080%2Ftestpost", fc.req.URL.String()) } diff --git a/indieAuth.go b/indieAuth.go index d099cb6..a84ee35 100644 --- a/indieAuth.go +++ b/indieAuth.go @@ -19,10 +19,7 @@ func (a *goBlog) initIndieAuth() { func (a *goBlog) checkIndieAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - bearerToken := r.Header.Get("Authorization") - if len(bearerToken) == 0 { - bearerToken = r.URL.Query().Get("access_token") - } + bearerToken := defaultIfEmpty(r.Header.Get("Authorization"), r.URL.Query().Get("access_token")) data, err := a.db.indieAuthVerifyToken(bearerToken) if err != nil { a.serveError(w, r, err.Error(), http.StatusUnauthorized) diff --git a/media.go b/media.go index 1d4fb92..b0d624e 100644 --- a/media.go +++ b/media.go @@ -13,7 +13,7 @@ const ( mediaFileRoute = `/{file:[0-9a-fA-F]+(\.[0-9a-zA-Z]+)?}` ) -func (a *goBlog) serveMediaFile(w http.ResponseWriter, r *http.Request) { +func (*goBlog) serveMediaFile(w http.ResponseWriter, r *http.Request) { f := filepath.Join(mediaFilePath, chi.URLParam(r, "file")) _, err := os.Stat(f) if err != nil { diff --git a/mediaCompression.go b/mediaCompression.go index 932b4d5..e560252 100644 --- a/mediaCompression.go +++ b/mediaCompression.go @@ -149,7 +149,7 @@ func (tf *tinify) compress(url string, upload mediaStorageSaveFunc, hc *http.Cli type cloudflare struct{} -func (cf *cloudflare) compress(url string, upload mediaStorageSaveFunc, hc *http.Client) (string, error) { +func (*cloudflare) compress(url string, upload mediaStorageSaveFunc, hc *http.Client) (string, error) { // Check url if _, allowed := urlHasExt(url, "jpg", "jpeg", "png"); !allowed { return "", nil diff --git a/micropub.go b/micropub.go index cf6be88..71de05b 100644 --- a/micropub.go +++ b/micropub.go @@ -334,7 +334,7 @@ func (a *goBlog) computeExtraPostParameters(p *post) error { p.Parameters = map[string][]string{} } p.Content = regexp.MustCompile("\r\n").ReplaceAllString(p.Content, "\n") - if split := strings.Split(p.Content, "---\n"); len(split) >= 3 && len(strings.TrimSpace(split[0])) == 0 { + if split := strings.Split(p.Content, "---\n"); len(split) >= 3 && strings.TrimSpace(split[0]) == "" { // Contains frontmatter fm := split[1] meta := map[string]interface{}{} diff --git a/micropubMedia.go b/micropubMedia.go index 1540a5d..130c614 100644 --- a/micropubMedia.go +++ b/micropubMedia.go @@ -47,7 +47,7 @@ func (a *goBlog) serveMicropubMedia(w http.ResponseWriter, r *http.Request) { _ = r.Body.Close() // Get file extension fileExtension := filepath.Ext(header.Filename) - if len(fileExtension) == 0 { + if fileExtension == "" { // Find correct file extension if original filename does not contain one mimeType := header.Header.Get(contentType) if len(mimeType) > 0 { diff --git a/nodeinfo.go b/nodeinfo.go index 144e86b..04ba3a7 100644 --- a/nodeinfo.go +++ b/nodeinfo.go @@ -4,14 +4,14 @@ import ( "encoding/json" "net/http" + "go.goblog.app/app/pkgs/bufferpool" "go.goblog.app/app/pkgs/contenttype" ) func (a *goBlog) serveNodeInfoDiscover(w http.ResponseWriter, r *http.Request) { - w.Header().Set(contentType, contenttype.JSONUTF8) - mw := a.min.Writer(contenttype.JSON, w) - defer mw.Close() - _ = json.NewEncoder(mw).Encode(map[string]interface{}{ + buf := bufferpool.Get() + defer bufferpool.Put(buf) + err := json.NewEncoder(buf).Encode(map[string]interface{}{ "links": []map[string]interface{}{ { "href": a.getFullAddress("/nodeinfo"), @@ -19,16 +19,23 @@ func (a *goBlog) serveNodeInfoDiscover(w http.ResponseWriter, r *http.Request) { }, }, }) + if err != nil { + a.serveError(w, r, "", http.StatusInternalServerError) + return + } + w.Header().Set(contentType, contenttype.JSONUTF8) + mw := a.min.Writer(contenttype.JSON, w) + _, _ = buf.WriteTo(mw) + _ = mw.Close() } func (a *goBlog) serveNodeInfo(w http.ResponseWriter, r *http.Request) { localPosts, _ := a.db.countPosts(&postsRequestConfig{ status: statusPublished, }) - mw := a.min.Writer(contenttype.JSON, w) - defer mw.Close() - w.Header().Set(contentType, contenttype.JSONUTF8) - _ = json.NewEncoder(mw).Encode(map[string]interface{}{ + buf := bufferpool.Get() + defer bufferpool.Put(buf) + err := json.NewEncoder(buf).Encode(map[string]interface{}{ "version": "2.1", "software": map[string]interface{}{ "name": "goblog", @@ -47,4 +54,12 @@ func (a *goBlog) serveNodeInfo(w http.ResponseWriter, r *http.Request) { }, "metadata": map[string]interface{}{}, }) + if err != nil { + a.serveError(w, r, "", http.StatusInternalServerError) + return + } + w.Header().Set(contentType, contenttype.JSONUTF8) + mw := a.min.Writer(contenttype.JSON, w) + _, _ = buf.WriteTo(mw) + _ = mw.Close() } diff --git a/pkgs/mocksmtp/backend.go b/pkgs/mocksmtp/backend.go index 686e0d5..5899b2f 100644 --- a/pkgs/mocksmtp/backend.go +++ b/pkgs/mocksmtp/backend.go @@ -60,8 +60,8 @@ func (s *session) Data(r io.Reader) error { return nil } -func (s *session) Reset() {} +func (*session) Reset() {} -func (s *session) Logout() error { +func (*session) Logout() error { return nil } diff --git a/robotstxt.go b/robotstxt.go index 222798b..1965bb7 100644 --- a/robotstxt.go +++ b/robotstxt.go @@ -7,7 +7,7 @@ import ( const robotsTXTPath = "/robots.txt" -func (a *goBlog) serveRobotsTXT(w http.ResponseWriter, r *http.Request) { +func (a *goBlog) serveRobotsTXT(w http.ResponseWriter, _ *http.Request) { _, _ = fmt.Fprint(w, "User-agent: *\n") if a.isPrivate() { _, _ = fmt.Fprint(w, "Disallow: /\n") diff --git a/sessions.go b/sessions.go index eba51d7..2a89da0 100644 --- a/sessions.go +++ b/sessions.go @@ -80,7 +80,7 @@ func (s *dbSessionStore) New(r *http.Request, name string) (session *sessions.Se return session, err } -func (s *dbSessionStore) Save(r *http.Request, w http.ResponseWriter, ss *sessions.Session) (err error) { +func (s *dbSessionStore) Save(_ *http.Request, w http.ResponseWriter, ss *sessions.Session) (err error) { if ss.ID == "" { // Is new session, save it to database if err = s.insert(ss); err != nil { diff --git a/sitemap.go b/sitemap.go index 99280b0..6400a36 100644 --- a/sitemap.go +++ b/sitemap.go @@ -20,7 +20,7 @@ const ( sitemapBlogPostsPath = "/sitemap-blog-posts.xml" ) -func (a *goBlog) serveSitemap(w http.ResponseWriter, r *http.Request) { +func (a *goBlog) serveSitemap(w http.ResponseWriter, _ *http.Request) { // Create sitemap sm := sitemap.NewSitemapIndex() // Add blog sitemap indices