github.com/coreos/mantle@v0.13.0/lang/destructor/destructor.go (about)

     1  // Copyright 2015 CoreOS, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package destructor
    16  
    17  import (
    18  	"io"
    19  
    20  	"github.com/coreos/pkg/capnslog"
    21  )
    22  
    23  var (
    24  	plog = capnslog.NewPackageLogger("github.com/coreos/mantle", "lang/destructor")
    25  )
    26  
    27  // Destructor is a common interface for objects that need to be cleaned up.
    28  type Destructor interface {
    29  	Destroy()
    30  }
    31  
    32  // CloseDestructor wraps any Closer to provide the Destructor interface.
    33  type CloserDestructor struct {
    34  	io.Closer
    35  }
    36  
    37  func (c CloserDestructor) Destroy() {
    38  	if err := c.Close(); err != nil {
    39  		plog.Errorf("Close() returned error: %v", err)
    40  	}
    41  }
    42  
    43  // MultiDestructor wraps multiple Destructors for easy cleanup.
    44  type MultiDestructor []Destructor
    45  
    46  func (m MultiDestructor) Destroy() {
    47  	for _, d := range m {
    48  		d.Destroy()
    49  	}
    50  }
    51  
    52  func (m *MultiDestructor) AddCloser(closer io.Closer) {
    53  	m.AddDestructor(CloserDestructor{closer})
    54  }
    55  
    56  func (m *MultiDestructor) AddDestructor(destructor Destructor) {
    57  	*m = append(*m, destructor)
    58  }