Fix some issues discovered by linting

pull/25/head
Jan-Lukas Else 7 months ago
parent ee2a5359b4
commit 94dba7a9b8
  1. 4
      app.go
  2. 2
      contact.go
  3. 2
      editor.go
  4. 4
      http.go
  5. 24
      indexnow.go
  6. 6
      indexnow_test.go
  7. 5
      indieAuth.go
  8. 2
      media.go
  9. 2
      mediaCompression.go
  10. 2
      micropub.go
  11. 2
      micropubMedia.go
  12. 31
      nodeinfo.go
  13. 4
      pkgs/mocksmtp/backend.go
  14. 2
      robotstxt.go
  15. 2
      sessions.go
  16. 2
      sitemap.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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading…
Cancel
Save