Fix all `errcheck` warnings

This commit is contained in:
Deluan 2020-04-26 12:35:26 -04:00 committed by Deluan Quintão
parent 03c3c192ed
commit 5cd453afeb
14 changed files with 37 additions and 38 deletions

View File

@ -74,7 +74,9 @@ func (c *cover) Get(ctx context.Context, id string, size int, out io.Writer) err
log.Error(ctx, "Error loading cover art", "path", path, "size", size, err) log.Error(ctx, "Error loading cover art", "path", path, "size", size, err)
return return
} }
io.Copy(w, reader) if _, err := io.Copy(w, reader); err != nil {
log.Error(ctx, "Error saving covert art to cache", "path", path, "size", size, err)
}
}() }()
} else { } else {
log.Trace(ctx, "Loading image from cache", "path", path, "size", size, "lastUpdate", lastUpdate) log.Trace(ctx, "Loading image from cache", "path", path, "size", size, "lastUpdate", lastUpdate)

View File

@ -110,7 +110,7 @@ func checkExpired(l *list.List, f func() *list.Element) *list.Element {
return nil return nil
} }
start := e.Value.(*NowPlayingInfo).Start start := e.Value.(*NowPlayingInfo).Start
if time.Now().Sub(start) < NowPlayingExpire { if time.Since(start) < NowPlayingExpire {
return e return e
} }
l.Remove(e) l.Remove(e)

View File

@ -2,7 +2,6 @@ package engine
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"time" "time"
@ -57,7 +56,7 @@ func (s *scrobbler) NowPlaying(ctx context.Context, playerId int, playerName, tr
} }
if mf == nil { if mf == nil {
return nil, errors.New(fmt.Sprintf(`ID "%s" not found`, trackId)) return nil, fmt.Errorf(`ID "%s" not found`, trackId)
} }
log.Info("Now Playing", "title", mf.Title, "artist", mf.Artist, "user", userName(ctx)) log.Info("Now Playing", "title", mf.Title, "artist", mf.Artist, "user", userName(ctx))

View File

@ -38,7 +38,9 @@ func (ff *ffmpeg) Start(ctx context.Context, command, path string, maxBitRate in
if err = cmd.Start(); err != nil { if err = cmd.Start(); err != nil {
return return
} }
go cmd.Wait() // prevent zombies
go func() { _ = cmd.Wait() }() // prevent zombies
return return
} }

View File

@ -22,7 +22,7 @@ func TestPersistence(t *testing.T) {
//os.Remove("./test-123.db") //os.Remove("./test-123.db")
//conf.Server.Path = "./test-123.db" //conf.Server.Path = "./test-123.db"
conf.Server.DbPath = "file::memory:?cache=shared" conf.Server.DbPath = "file::memory:?cache=shared"
orm.RegisterDataBase("default", db.Driver, conf.Server.DbPath) _ = orm.RegisterDataBase("default", db.Driver, conf.Server.DbPath)
db.EnsureLatestVersion() db.EnsureLatestVersion()
log.SetLevel(log.LevelCritical) log.SetLevel(log.LevelCritical)
RegisterFailHandler(Fail) RegisterFailHandler(Fail)

View File

@ -103,8 +103,8 @@ var _ = Describe("ChangeDetector", func() {
Expect(changed).To(BeEmpty()) Expect(changed).To(BeEmpty())
Expect(changed).To(BeEmpty()) Expect(changed).To(BeEmpty())
f, err := os.Create(filepath.Join(testFolder, "a", "b", "new.txt")) f, _ := os.Create(filepath.Join(testFolder, "a", "b", "new.txt"))
f.Close() _ = f.Close()
changed, deleted, err = newScanner.Scan(lastModifiedSince) changed, deleted, err = newScanner.Scan(lastModifiedSince)
Expect(err).To(BeNil()) Expect(err).To(BeNil())
Expect(deleted).To(BeEmpty()) Expect(deleted).To(BeEmpty())

View File

@ -72,7 +72,9 @@ func (s *Scanner) getLastModifiedSince(folder string) time.Time {
func (s *Scanner) updateLastModifiedSince(folder string, t time.Time) { func (s *Scanner) updateLastModifiedSince(folder string, t time.Time) {
millis := t.UnixNano() / int64(time.Millisecond) millis := t.UnixNano() / int64(time.Millisecond)
s.ds.Property(nil).Put(model.PropLastScan+"-"+folder, fmt.Sprint(millis)) if err := s.ds.Property(context.TODO()).Put(model.PropLastScan+"-"+folder, fmt.Sprint(millis)); err != nil {
log.Error("Error updating DB after scan", err)
}
} }
func (s *Scanner) loadFolders() { func (s *Scanner) loadFolders() {
@ -85,12 +87,6 @@ func (s *Scanner) loadFolders() {
type Status int type Status int
const (
StatusComplete Status = iota
StatusInProgress
StatusError
)
type StatusInfo struct { type StatusInfo struct {
MediaFolder string MediaFolder string
Status Status Status Status

View File

@ -49,7 +49,7 @@ func (app *Router) routes(path string) http.Handler {
app.R(r, "/player", model.Player{}) app.R(r, "/player", model.Player{})
// Keepalive endpoint to be used to keep the session valid (ex: while playing songs) // Keepalive endpoint to be used to keep the session valid (ex: while playing songs)
r.Get("/keepalive/*", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"response":"ok"}`)) }) r.Get("/keepalive/*", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`{"response":"ok"}`)) })
}) })
// Serve UI app assets // Serve UI app assets

View File

@ -6,7 +6,6 @@ import (
"errors" "errors"
"net/http" "net/http"
"strings" "strings"
"sync"
"time" "time"
"github.com/deluan/navidrome/consts" "github.com/deluan/navidrome/consts"
@ -20,7 +19,6 @@ import (
) )
var ( var (
once sync.Once
ErrFirstTime = errors.New("no users created") ErrFirstTime = errors.New("no users created")
) )
@ -31,7 +29,7 @@ func Login(ds model.DataStore) func(w http.ResponseWriter, r *http.Request) {
username, password, err := getCredentialsFromBody(r) username, password, err := getCredentialsFromBody(r)
if err != nil { if err != nil {
log.Error(r, "Parsing request body", err) log.Error(r, "Parsing request body", err)
rest.RespondWithError(w, http.StatusUnprocessableEntity, err.Error()) _ = rest.RespondWithError(w, http.StatusUnprocessableEntity, err.Error())
return return
} }
@ -42,21 +40,21 @@ func Login(ds model.DataStore) func(w http.ResponseWriter, r *http.Request) {
func handleLogin(ds model.DataStore, username string, password string, w http.ResponseWriter, r *http.Request) { func handleLogin(ds model.DataStore, username string, password string, w http.ResponseWriter, r *http.Request) {
user, err := validateLogin(ds.User(r.Context()), username, password) user, err := validateLogin(ds.User(r.Context()), username, password)
if err != nil { if err != nil {
rest.RespondWithError(w, http.StatusInternalServerError, "Unknown error authentication user. Please try again") _ = rest.RespondWithError(w, http.StatusInternalServerError, "Unknown error authentication user. Please try again")
return return
} }
if user == nil { if user == nil {
log.Warn(r, "Unsuccessful login", "username", username, "request", r.Header) log.Warn(r, "Unsuccessful login", "username", username, "request", r.Header)
rest.RespondWithError(w, http.StatusUnauthorized, "Invalid username or password") _ = rest.RespondWithError(w, http.StatusUnauthorized, "Invalid username or password")
return return
} }
tokenString, err := auth.CreateToken(user) tokenString, err := auth.CreateToken(user)
if err != nil { if err != nil {
rest.RespondWithError(w, http.StatusInternalServerError, "Unknown error authenticating user. Please try again") _ = rest.RespondWithError(w, http.StatusInternalServerError, "Unknown error authenticating user. Please try again")
return return
} }
rest.RespondWithJSON(w, http.StatusOK, _ = rest.RespondWithJSON(w, http.StatusOK,
map[string]interface{}{ map[string]interface{}{
"message": "User '" + username + "' authenticated successfully", "message": "User '" + username + "' authenticated successfully",
"token": tokenString, "token": tokenString,
@ -71,7 +69,7 @@ func getCredentialsFromBody(r *http.Request) (username string, password string,
decoder := json.NewDecoder(r.Body) decoder := json.NewDecoder(r.Body)
if err = decoder.Decode(&data); err != nil { if err = decoder.Decode(&data); err != nil {
log.Error(r, "parsing request body", err) log.Error(r, "parsing request body", err)
err = errors.New("Invalid request payload") err = errors.New("invalid request payload")
return return
} }
username = data["username"] username = data["username"]
@ -86,21 +84,21 @@ func CreateAdmin(ds model.DataStore) func(w http.ResponseWriter, r *http.Request
username, password, err := getCredentialsFromBody(r) username, password, err := getCredentialsFromBody(r)
if err != nil { if err != nil {
log.Error(r, "parsing request body", err) log.Error(r, "parsing request body", err)
rest.RespondWithError(w, http.StatusUnprocessableEntity, err.Error()) _ = rest.RespondWithError(w, http.StatusUnprocessableEntity, err.Error())
return return
} }
c, err := ds.User(r.Context()).CountAll() c, err := ds.User(r.Context()).CountAll()
if err != nil { if err != nil {
rest.RespondWithError(w, http.StatusInternalServerError, err.Error()) _ = rest.RespondWithError(w, http.StatusInternalServerError, err.Error())
return return
} }
if c > 0 { if c > 0 {
rest.RespondWithError(w, http.StatusForbidden, "Cannot create another first admin") _ = rest.RespondWithError(w, http.StatusForbidden, "Cannot create another first admin")
return return
} }
err = createDefaultUser(r.Context(), ds, username, password) err = createDefaultUser(r.Context(), ds, username, password)
if err != nil { if err != nil {
rest.RespondWithError(w, http.StatusInternalServerError, err.Error()) _ = rest.RespondWithError(w, http.StatusInternalServerError, err.Error())
return return
} }
handleLogin(ds, username, password, w, r) handleLogin(ds, username, password, w, r)
@ -186,11 +184,11 @@ func authenticator(ds model.DataStore) func(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) {
token, err := getToken(ds, r.Context()) token, err := getToken(ds, r.Context())
if err == ErrFirstTime { if err == ErrFirstTime {
rest.RespondWithJSON(w, http.StatusUnauthorized, map[string]string{"message": ErrFirstTime.Error()}) _ = rest.RespondWithJSON(w, http.StatusUnauthorized, map[string]string{"message": ErrFirstTime.Error()})
return return
} }
if err != nil { if err != nil {
rest.RespondWithError(w, http.StatusUnauthorized, "Not authenticated") _ = rest.RespondWithError(w, http.StatusUnauthorized, "Not authenticated")
return return
} }
@ -200,7 +198,7 @@ func authenticator(ds model.DataStore) func(next http.Handler) http.Handler {
newTokenString, err := auth.TouchToken(token) newTokenString, err := auth.TouchToken(token)
if err != nil { if err != nil {
log.Error(r, "signing new token", err) log.Error(r, "signing new token", err)
rest.RespondWithError(w, http.StatusUnauthorized, "Not authenticated") _ = rest.RespondWithError(w, http.StatusUnauthorized, "Not authenticated")
return return
} }

View File

@ -162,7 +162,7 @@ func H(r chi.Router, path string, f Handler) {
func HGone(r chi.Router, path string) { func HGone(r chi.Router, path string) {
handle := func(w http.ResponseWriter, r *http.Request) { handle := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(410) w.WriteHeader(410)
w.Write([]byte("This endpoint will not be implemented")) _, _ = w.Write([]byte("This endpoint will not be implemented"))
} }
r.HandleFunc("/"+path, handle) r.HandleFunc("/"+path, handle)
r.HandleFunc("/"+path+".view", handle) r.HandleFunc("/"+path+".view", handle)
@ -207,5 +207,7 @@ func SendResponse(w http.ResponseWriter, r *http.Request, payload *responses.Sub
} else { } else {
log.Warn(r.Context(), "API: Failed response", "error", payload.Error.Code, "message", payload.Error.Message) log.Warn(r.Context(), "API: Failed response", "error", payload.Error.Code, "message", payload.Error.Message)
} }
w.Write(response) if _, err := w.Write(response); err != nil {
log.Error(r, "Error sending response to client", "payload", string(response), err)
}
} }

View File

@ -27,7 +27,7 @@ func (c *MediaRetrievalController) GetAvatar(w http.ResponseWriter, r *http.Requ
return nil, NewError(responses.ErrorDataNotFound, "Avatar image not found") return nil, NewError(responses.ErrorDataNotFound, "Avatar image not found")
} }
defer f.Close() defer f.Close()
io.Copy(w, f) _, _ = io.Copy(w, f)
return nil, nil return nil, nil
} }

View File

@ -24,8 +24,8 @@ func (c *fakeCover) Get(ctx context.Context, id string, size int, out io.Writer)
} }
c.recvId = id c.recvId = id
c.recvSize = size c.recvSize = size
out.Write([]byte(c.data)) _, err := out.Write([]byte(c.data))
return nil return err
} }
var _ = Describe("MediaRetrievalController", func() { var _ = Describe("MediaRetrievalController", func() {

View File

@ -22,7 +22,7 @@ func Init(t *testing.T, skipOnShort bool) {
appPath, _ := filepath.Abs(filepath.Join(filepath.Dir(file), "..")) appPath, _ := filepath.Abs(filepath.Join(filepath.Dir(file), ".."))
confPath, _ := filepath.Abs(filepath.Join(appPath, "tests", "navidrome-test.toml")) confPath, _ := filepath.Abs(filepath.Join(appPath, "tests", "navidrome-test.toml"))
println("Loading test configuration file from " + confPath) println("Loading test configuration file from " + confPath)
os.Chdir(appPath) _ = os.Chdir(appPath)
conf.LoadFromFile("tests/navidrome-test.toml", true) conf.LoadFromFile("tests/navidrome-test.toml", true)
noLog := os.Getenv("NOLOG") noLog := os.Getenv("NOLOG")

View File

@ -68,5 +68,5 @@ func ParamBool(r *http.Request, param string, def bool) bool {
if p == "" { if p == "" {
return def return def
} }
return strings.Index("/true/on/1/", "/"+p+"/") != -1 return strings.Contains("/true/on/1/", "/"+p+"/")
} }