github.com/graemephi/kahugo@v0.62.3-0.20211121071557-d78c0423784d/common/hugio/writers.go (about) 1 // Copyright 2018 The Hugo Authors. All rights reserved. 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 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package hugio 15 16 import ( 17 "io" 18 "io/ioutil" 19 ) 20 21 type multiWriteCloser struct { 22 io.Writer 23 closers []io.WriteCloser 24 } 25 26 func (m multiWriteCloser) Close() error { 27 var err error 28 for _, c := range m.closers { 29 if closeErr := c.Close(); err != nil { 30 err = closeErr 31 } 32 } 33 return err 34 } 35 36 // NewMultiWriteCloser creates a new io.WriteCloser that duplicates its writes to all the 37 // provided writers. 38 func NewMultiWriteCloser(writeClosers ...io.WriteCloser) io.WriteCloser { 39 writers := make([]io.Writer, len(writeClosers)) 40 for i, w := range writeClosers { 41 writers[i] = w 42 } 43 return multiWriteCloser{Writer: io.MultiWriter(writers...), closers: writeClosers} 44 } 45 46 // ToWriteCloser creates an io.WriteCloser from the given io.Writer. 47 // If it's not already, one will be created with a Close method that does nothing. 48 func ToWriteCloser(w io.Writer) io.WriteCloser { 49 if rw, ok := w.(io.WriteCloser); ok { 50 return rw 51 } 52 53 return struct { 54 io.Writer 55 io.Closer 56 }{ 57 w, 58 ioutil.NopCloser(nil), 59 } 60 } 61 62 // ToReadCloser creates an io.ReadCloser from the given io.Reader. 63 // If it's not already, one will be created with a Close method that does nothing. 64 func ToReadCloser(r io.Reader) io.ReadCloser { 65 if rc, ok := r.(io.ReadCloser); ok { 66 return rc 67 } 68 69 return struct { 70 io.Reader 71 io.Closer 72 }{ 73 r, 74 ioutil.NopCloser(nil), 75 } 76 }