github.com/richardwilkes/toolbox@v1.121.0/xio/close.go (about) 1 // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved. 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, version 2.0. If a copy of the MPL was not distributed with 5 // this file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 // 7 // This Source Code Form is "Incompatible With Secondary Licenses", as 8 // defined by the Mozilla Public License, version 2.0. 9 10 // Package xio provides i/o utilities. 11 package xio 12 13 import ( 14 "io" 15 "log/slog" 16 17 "github.com/richardwilkes/toolbox/errs" 18 ) 19 20 // CloseIgnoringErrors closes the closer and ignores any error it might produce. Should only be used for read-only 21 // streams of data where closing should never cause an error. 22 func CloseIgnoringErrors(closer io.Closer) { 23 _ = closer.Close() //nolint:errcheck // intentionally ignoring any error 24 } 25 26 // DiscardAndCloseIgnoringErrors reads any content remaining in the body and discards it, then closes the body. 27 func DiscardAndCloseIgnoringErrors(rc io.ReadCloser) { 28 _, _ = io.Copy(io.Discard, rc) //nolint:errcheck // intentionally ignoring any error 29 CloseIgnoringErrors(rc) 30 } 31 32 // CloseLoggingAnyError closes the closer and logs any error that occurs at an error level to the default logger. 33 func CloseLoggingAnyError(closer io.Closer) { 34 CloseLoggingAnyErrorTo(slog.Default(), closer) 35 } 36 37 // CloseLoggingAnyErrorTo closes the closer and logs any error that occurs to the provided logger. 38 func CloseLoggingAnyErrorTo(logger *slog.Logger, closer io.Closer) { 39 if err := closer.Close(); err != nil { 40 errs.LogTo(logger, err) 41 } 42 }