github.com/minio/minio@v0.0.0-20240328213742-3f72439b8a27/internal/deadlineconn/deadlineconn.go (about) 1 // Copyright (c) 2015-2022 MinIO, Inc. 2 // 3 // This file is part of MinIO Object Storage stack 4 // 5 // This program is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Affero General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // This program is distributed in the hope that it will be useful 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Affero General Public License for more details. 14 // 15 // You should have received a copy of the GNU Affero General Public License 16 // along with this program. If not, see <http://www.gnu.org/licenses/>. 17 18 // Package deadlineconn implements net.Conn wrapper with configured deadlines. 19 package deadlineconn 20 21 import ( 22 "net" 23 "time" 24 ) 25 26 // DeadlineConn - is a generic stream-oriented network connection supporting buffered reader and read/write timeout. 27 type DeadlineConn struct { 28 net.Conn 29 readDeadline time.Duration // sets the read deadline on a connection. 30 writeDeadline time.Duration // sets the write deadline on a connection. 31 } 32 33 // Sets read deadline 34 func (c *DeadlineConn) setReadDeadline() { 35 if c.readDeadline > 0 { 36 c.SetReadDeadline(time.Now().UTC().Add(c.readDeadline)) 37 } 38 } 39 40 func (c *DeadlineConn) setWriteDeadline() { 41 if c.writeDeadline > 0 { 42 c.SetWriteDeadline(time.Now().UTC().Add(c.writeDeadline)) 43 } 44 } 45 46 // Read - reads data from the connection using wrapped buffered reader. 47 func (c *DeadlineConn) Read(b []byte) (n int, err error) { 48 c.setReadDeadline() 49 n, err = c.Conn.Read(b) 50 return n, err 51 } 52 53 // Write - writes data to the connection. 54 func (c *DeadlineConn) Write(b []byte) (n int, err error) { 55 c.setWriteDeadline() 56 n, err = c.Conn.Write(b) 57 return n, err 58 } 59 60 // WithReadDeadline sets a new read side net.Conn deadline. 61 func (c *DeadlineConn) WithReadDeadline(d time.Duration) *DeadlineConn { 62 c.readDeadline = d 63 return c 64 } 65 66 // WithWriteDeadline sets a new write side net.Conn deadline. 67 func (c *DeadlineConn) WithWriteDeadline(d time.Duration) *DeadlineConn { 68 c.writeDeadline = d 69 return c 70 } 71 72 // New - creates a new connection object wrapping net.Conn with deadlines. 73 func New(c net.Conn) *DeadlineConn { 74 return &DeadlineConn{ 75 Conn: c, 76 } 77 }