handle errors in defer close

This commit is contained in:
2026-05-07 08:56:38 -06:00
parent c565a2d97a
commit 0eedf23667
3 changed files with 15 additions and 5 deletions
-2
View File
@@ -17,7 +17,6 @@ func (s *Server) handlerRefresh(w http.ResponseWriter, req *http.Request) {
respondWithError(w, http.StatusUnauthorized, "unauthorized") respondWithError(w, http.StatusUnauthorized, "unauthorized")
return return
} }
defer req.Body.Close()
if err := s.c.Refresh(); err != nil { if err := s.c.Refresh(); err != nil {
slog.Error("refresh failed", "err", err) slog.Error("refresh failed", "err", err)
@@ -37,7 +36,6 @@ func (s *Server) handlerLogLevel(w http.ResponseWriter, req *http.Request) {
respondWithError(w, http.StatusUnauthorized, "unauthorized") respondWithError(w, http.StatusUnauthorized, "unauthorized")
return return
} }
defer req.Body.Close()
type reqParameters struct { type reqParameters struct {
NewLevel string `json:"loglevel"` NewLevel string `json:"loglevel"`
+5 -1
View File
@@ -41,7 +41,11 @@ func (s *Server) handlerPackage(w http.ResponseWriter, req *http.Request) {
http.Error(w, "Failed to fetch from upstream", http.StatusBadGateway) http.Error(w, "Failed to fetch from upstream", http.StatusBadGateway)
return return
} }
defer cachedFile.Reader.Close() defer func() {
if closeErr := cachedFile.Reader.Close(); closeErr != nil {
err = closeErr
}
}()
w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename="+cachedFile.Filename) w.Header().Set("Content-Disposition", "attachment; filename="+cachedFile.Filename)
+10 -2
View File
@@ -32,7 +32,11 @@ func (c *Cache) downloadToDisk(url, relPath string) error {
slog.Info("fetch returned", "url", url, "status", resp.StatusCode) slog.Info("fetch returned", "url", url, "status", resp.StatusCode)
return &UpstreamError{StatusCode: resp.StatusCode} return &UpstreamError{StatusCode: resp.StatusCode}
} }
defer resp.Body.Close() defer func() {
if closeErr := resp.Body.Close(); closeErr != nil {
err = closeErr
}
}()
// make sure the dir structure exists // make sure the dir structure exists
err = c.cr.MkdirAll(filepath.Dir(relPath), 0750) err = c.cr.MkdirAll(filepath.Dir(relPath), 0750)
@@ -46,7 +50,11 @@ func (c *Cache) downloadToDisk(url, relPath string) error {
if err != nil { if err != nil {
return err return err
} }
defer tmpFile.Close() defer func() {
if closeErr := tmpFile.Close(); closeErr != nil {
err = closeErr
}
}()
_, err = io.Copy(tmpFile, resp.Body) _, err = io.Copy(tmpFile, resp.Body)
if err != nil { if err != nil {