Fix some issues discovered by linting

This commit is contained in:
Jan-Lukas Else 2022-02-25 16:29:42 +01:00
parent ee2a5359b4
commit 94dba7a9b8
16 changed files with 51 additions and 45 deletions

4
app.go
View File

@ -54,8 +54,8 @@ type goBlog struct {
// HTTP Routers // HTTP Routers
d http.Handler d http.Handler
// IndexNow // IndexNow
inKey string inKey []byte
inLoad singleflight.Group inLoad sync.Once
// IndieAuth // IndieAuth
ias *indieauth.Server ias *indieauth.Server
// Logs // Logs

View File

@ -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 // Check required config
if cc == nil || cc.SMTPHost == "" || cc.EmailFrom == "" || cc.EmailTo == "" { if cc == nil || cc.SMTPHost == "" || cc.EmailFrom == "" || cc.EmailTo == "" {
return fmt.Errorf("email not send as config is missing") return fmt.Errorf("email not send as config is missing")

View File

@ -176,7 +176,7 @@ func (a *goBlog) editorMicropubPost(w http.ResponseWriter, r *http.Request, medi
_ = result.Body.Close() _ = result.Body.Close()
} }
func (a *goBlog) editorPostTemplate(blog string, bc *configBlog) string { func (*goBlog) editorPostTemplate(blog string, bc *configBlog) string {
builder := bufferpool.Get() builder := bufferpool.Get()
defer bufferpool.Put(builder) defer bufferpool.Put(builder)
marsh := func(param string, i interface{}) { marsh := func(param string, i interface{}) {

View File

@ -200,8 +200,8 @@ func (a *goBlog) buildRouter() http.Handler {
// IndexNow // IndexNow
if a.indexNowEnabled() { if a.indexNowEnabled() {
if inkey := a.indexNowKey(); inkey != "" { if inkey := a.indexNowKey(); len(inkey) > 0 {
r.With(cacheLoggedIn, a.cacheMiddleware).Get("/"+inkey+".txt", a.serveIndexNow) r.With(cacheLoggedIn, a.cacheMiddleware).Get("/"+string(inkey)+".txt", a.serveIndexNow)
} }
} }

View File

@ -2,7 +2,6 @@ package main
import ( import (
"context" "context"
"io"
"log" "log"
"net/http" "net/http"
@ -43,7 +42,7 @@ func (a *goBlog) indexNowEnabled() bool {
} }
func (a *goBlog) serveIndexNow(w http.ResponseWriter, r *http.Request) { 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) { func (a *goBlog) indexNow(url string) {
@ -51,7 +50,7 @@ func (a *goBlog) indexNow(url string) {
return return
} }
key := a.indexNowKey() key := a.indexNowKey()
if key == "" { if len(key) == 0 {
log.Println("Skipping IndexNow") log.Println("Skipping IndexNow")
return return
} }
@ -59,7 +58,7 @@ func (a *goBlog) indexNow(url string) {
Client(a.httpClient). Client(a.httpClient).
UserAgent(appUserAgent). UserAgent(appUserAgent).
Param("url", url). Param("url", url).
Param("key", key). Param("key", string(key)).
Fetch(context.Background()) Fetch(context.Background())
if err != nil { if err != nil {
log.Println("Sending IndexNow request failed:", err.Error()) log.Println("Sending IndexNow request failed:", err.Error())
@ -69,17 +68,13 @@ func (a *goBlog) indexNow(url string) {
} }
} }
func (a *goBlog) indexNowKey() string { func (a *goBlog) indexNowKey() []byte {
res, _, _ := a.inLoad.Do("", func() (interface{}, error) { a.inLoad.Do(func() {
// Check if already loaded
if a.inKey != "" {
return a.inKey, nil
}
// Try to load key from database // Try to load key from database
keyBytes, err := a.db.retrievePersistentCache("indexnowkey") keyBytes, err := a.db.retrievePersistentCache("indexnowkey")
if err != nil { if err != nil {
log.Println("Failed to retrieve cached IndexNow key:", err.Error()) log.Println("Failed to retrieve cached IndexNow key:", err.Error())
return "", err return
} }
if keyBytes == nil { if keyBytes == nil {
// Generate 128 character key with hexadecimal characters // Generate 128 character key with hexadecimal characters
@ -88,11 +83,10 @@ func (a *goBlog) indexNowKey() string {
err = a.db.cachePersistently("indexnowkey", keyBytes) err = a.db.cachePersistently("indexnowkey", keyBytes)
if err != nil { if err != nil {
log.Println("Failed to cache IndexNow key:", err.Error()) log.Println("Failed to cache IndexNow key:", err.Error())
return "", err return
} }
} }
a.inKey = string(keyBytes) a.inKey = keyBytes
return a.inKey, nil
}) })
return res.(string) return a.inKey
} }

View File

@ -29,13 +29,13 @@ func Test_indexNow(t *testing.T) {
// Check key // Check key
require.NotEmpty(t, app.inKey) 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) res, err := doHandlerRequest(req, app.d)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, 200, res.StatusCode) require.Equal(t, 200, res.StatusCode)
body, _ := io.ReadAll(res.Body) body, _ := io.ReadAll(res.Body)
_ = res.Body.Close() _ = res.Body.Close()
require.Equal(t, app.inKey, string(body)) require.Equal(t, app.inKey, body)
// Test publish post // Test publish post
_ = app.createPost(&post{ _ = app.createPost(&post{
@ -54,5 +54,5 @@ func Test_indexNow(t *testing.T) {
fc.mu.Unlock() fc.mu.Unlock()
// Check fake http client // 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())
} }

View File

@ -19,10 +19,7 @@ func (a *goBlog) initIndieAuth() {
func (a *goBlog) checkIndieAuth(next http.Handler) http.Handler { func (a *goBlog) checkIndieAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
bearerToken := r.Header.Get("Authorization") bearerToken := defaultIfEmpty(r.Header.Get("Authorization"), r.URL.Query().Get("access_token"))
if len(bearerToken) == 0 {
bearerToken = r.URL.Query().Get("access_token")
}
data, err := a.db.indieAuthVerifyToken(bearerToken) data, err := a.db.indieAuthVerifyToken(bearerToken)
if err != nil { if err != nil {
a.serveError(w, r, err.Error(), http.StatusUnauthorized) a.serveError(w, r, err.Error(), http.StatusUnauthorized)

View File

@ -13,7 +13,7 @@ const (
mediaFileRoute = `/{file:[0-9a-fA-F]+(\.[0-9a-zA-Z]+)?}` 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")) f := filepath.Join(mediaFilePath, chi.URLParam(r, "file"))
_, err := os.Stat(f) _, err := os.Stat(f)
if err != nil { if err != nil {

View File

@ -149,7 +149,7 @@ func (tf *tinify) compress(url string, upload mediaStorageSaveFunc, hc *http.Cli
type cloudflare struct{} 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 // Check url
if _, allowed := urlHasExt(url, "jpg", "jpeg", "png"); !allowed { if _, allowed := urlHasExt(url, "jpg", "jpeg", "png"); !allowed {
return "", nil return "", nil

View File

@ -334,7 +334,7 @@ func (a *goBlog) computeExtraPostParameters(p *post) error {
p.Parameters = map[string][]string{} p.Parameters = map[string][]string{}
} }
p.Content = regexp.MustCompile("\r\n").ReplaceAllString(p.Content, "\n") 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 // Contains frontmatter
fm := split[1] fm := split[1]
meta := map[string]interface{}{} meta := map[string]interface{}{}

View File

@ -47,7 +47,7 @@ func (a *goBlog) serveMicropubMedia(w http.ResponseWriter, r *http.Request) {
_ = r.Body.Close() _ = r.Body.Close()
// Get file extension // Get file extension
fileExtension := filepath.Ext(header.Filename) fileExtension := filepath.Ext(header.Filename)
if len(fileExtension) == 0 { if fileExtension == "" {
// Find correct file extension if original filename does not contain one // Find correct file extension if original filename does not contain one
mimeType := header.Header.Get(contentType) mimeType := header.Header.Get(contentType)
if len(mimeType) > 0 { if len(mimeType) > 0 {

View File

@ -4,14 +4,14 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"go.goblog.app/app/pkgs/bufferpool"
"go.goblog.app/app/pkgs/contenttype" "go.goblog.app/app/pkgs/contenttype"
) )
func (a *goBlog) serveNodeInfoDiscover(w http.ResponseWriter, r *http.Request) { func (a *goBlog) serveNodeInfoDiscover(w http.ResponseWriter, r *http.Request) {
w.Header().Set(contentType, contenttype.JSONUTF8) buf := bufferpool.Get()
mw := a.min.Writer(contenttype.JSON, w) defer bufferpool.Put(buf)
defer mw.Close() err := json.NewEncoder(buf).Encode(map[string]interface{}{
_ = json.NewEncoder(mw).Encode(map[string]interface{}{
"links": []map[string]interface{}{ "links": []map[string]interface{}{
{ {
"href": a.getFullAddress("/nodeinfo"), "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) { func (a *goBlog) serveNodeInfo(w http.ResponseWriter, r *http.Request) {
localPosts, _ := a.db.countPosts(&postsRequestConfig{ localPosts, _ := a.db.countPosts(&postsRequestConfig{
status: statusPublished, status: statusPublished,
}) })
mw := a.min.Writer(contenttype.JSON, w) buf := bufferpool.Get()
defer mw.Close() defer bufferpool.Put(buf)
w.Header().Set(contentType, contenttype.JSONUTF8) err := json.NewEncoder(buf).Encode(map[string]interface{}{
_ = json.NewEncoder(mw).Encode(map[string]interface{}{
"version": "2.1", "version": "2.1",
"software": map[string]interface{}{ "software": map[string]interface{}{
"name": "goblog", "name": "goblog",
@ -47,4 +54,12 @@ func (a *goBlog) serveNodeInfo(w http.ResponseWriter, r *http.Request) {
}, },
"metadata": map[string]interface{}{}, "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()
} }

View File

@ -60,8 +60,8 @@ func (s *session) Data(r io.Reader) error {
return nil return nil
} }
func (s *session) Reset() {} func (*session) Reset() {}
func (s *session) Logout() error { func (*session) Logout() error {
return nil return nil
} }

View File

@ -7,7 +7,7 @@ import (
const robotsTXTPath = "/robots.txt" 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") _, _ = fmt.Fprint(w, "User-agent: *\n")
if a.isPrivate() { if a.isPrivate() {
_, _ = fmt.Fprint(w, "Disallow: /\n") _, _ = fmt.Fprint(w, "Disallow: /\n")

View File

@ -80,7 +80,7 @@ func (s *dbSessionStore) New(r *http.Request, name string) (session *sessions.Se
return session, err 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 == "" { if ss.ID == "" {
// Is new session, save it to database // Is new session, save it to database
if err = s.insert(ss); err != nil { if err = s.insert(ss); err != nil {

View File

@ -20,7 +20,7 @@ const (
sitemapBlogPostsPath = "/sitemap-blog-posts.xml" 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 // Create sitemap
sm := sitemap.NewSitemapIndex() sm := sitemap.NewSitemapIndex()
// Add blog sitemap indices // Add blog sitemap indices